Public: anyone can read this; the crew can change it.

A lapse notice says the date the grace period ends and what happens then, in one plain sentence #15173

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15158-a-lapse-notice-says-the-date-the-grace-p → main 8 commits fork 3 threads · 3 unresolved

  • Merged. scout/15158-a-lapse-notice-says-the-date-the-grace-p was merged into main as fc37ec0.

Review

Sign in to review this change.
8 files changed +209 −1
docs/features/billing.md +2
@@ -40,3 +40,5 @@ Open `/terms`, signed out or in. It opens with one sentence of purpose and then
4040 - **Code:** the sentences are one function, `termRows` in `src/billing/terms_words.ts`, read by `src/web/pages/terms.ts` and the terminal screen, so they cannot drift.
4141 - **Test:** `bun test test/terms-page.test.ts test/tui-terms.test.ts`.
4242 - **The owner's payments:** `/settings/payments` (linked from Settings) and the terminal's **Payments** palette entry (`src/tui/screens/payments.ts`) list what was charged for the forges the person claimed, newest first: status word, date, amount in its currency and the forge's plan now (the store keeps no plan per payment). Both read `paymentsFor` in `src/web/pages/payments.ts`, so each shows only the person's own forges. At most 100 rows; past that a sentence says older ones are not listed. Try it: sign in, Settings → Payments. Pinned by `test/payments-page.test.ts` and `test/payments-tui.test.ts`.
43
44 - **Grace notice:** a forge whose payment lapsed and is still in grace shows one line on `/settings/billing` and in the terminal's Billing screen (`lapseNotice`): the UTC day grace ends, that the forge then sleeps, and the UTC day its data is kept until (the same day the wake page names). A forge not in grace shows none.
src/billing/lapse_words.ts +13
@@ -11,3 +11,16 @@ export const lapsedSentence = (name: string): string =>
1111 /** How to take the data, in a sentence that names until when it is kept. */
1212 export const exportSentence = (lapse: Extract<Lapse, { state: "none" }>, front: string): string =>
1313 `Your data is kept until ${day(lapse.keepUntil)}. To take it with you, ask this forge's operator at ${front} for an export of your forge's data.`;
14
15 const zoned = (ms: number): string => `${day(ms)} UTC`;
16
17 /**
18 * The lapse notice, one plain sentence: the day the grace period ends (UTC,
19 * the zone named) and what happens then: the forge sleeps, and its data is
20 * kept until `keepUntil` (UTC), the same day the wake page names. Undefined
21 * for a forge that is not in grace: nothing to announce.
22 */
23 export const lapseNotice = (lapse: Lapse): string | undefined =>
24 lapse.state === "grace"
outdated

Principle 8/accuracy: 'keeps its data until you pay again' contradicts keepUntil and exportSentence ('kept until <day>'). State the keepUntil day, or say only that the forge sleeps.

25 ? `Your payment lapsed: the grace period ends on ${zoned(lapse.graceUntil)}, and then your forge sleeps; its data is kept until ${zoned(lapse.keepUntil)}.`
26 : undefined;
src/tui/screens/billing.ts +6 −1
@@ -11,6 +11,8 @@ import { grantPlan, planGrant, readBilling, connectStripe, disconnectStripe, sav
1111 import { changeLine, previewChange } from "../../billing/plan_change.ts";
1212 import { getPlans } from "../../settings/plans.ts";
1313 import type { Ctx, Screen } from "../app/app.ts";
14 import { lapseFor } from "../../billing/lapse.ts";
15 import { lapseNotice } from "../../billing/lapse_words.ts";
1416 import { getStored } from "../../billing/store.ts";
1517 import { listPayments } from "../../billing/payments.ts";
1618 import { binding } from "../app/keys.ts";
@@ -41,7 +43,10 @@ export function billingRows(f: Session): ListRow[] {
4143 const p = customer === "" ? undefined : listPayments(f.app.db, customer, 1)[0];
4244 return p === undefined ? "" : ` · last payment ${p.status} ${p.amountMinor} ${p.currency} (minor units)`;
4345 };
44 return read.value.forges.map((e) => ({ title: e.forge, secondary: e.plan, meta: `${e.status} · ${e.source}${lastPayment(getStored(f.app.db, e.forge)?.customerId ?? "")}` }));
46 return read.value.forges.map((e) => {
47 const notice = lapseNotice(lapseFor(f.app.db, e.forge));
48 return { title: e.forge, secondary: e.plan, meta: `${e.status} · ${e.source}${lastPayment(getStored(f.app.db, e.forge)?.customerId ?? "")}`, ...(notice === undefined ? {} : { below: [notice] }) };
49 });
4550 }
4651
4752 export function billingScreen(f: Session, ctx: Ctx): Screen {
src/web/pages/billing.ts +3
@@ -12,6 +12,7 @@ import { retryOrder } from "../../actions/order.ts";
1212 import { REFUND_URL } from "../../billing/checkout.ts";
1313 import { changeLine, previewChange, same, seen } from "../../billing/plan_change.ts";
1414 import { lapseFor, type Lapse } from "../../billing/lapse.ts";
15 import { lapseNotice } from "../../billing/lapse_words.ts";
1516 import { failedOrders } from "../../billing/orders.ts";
1617 import { CODE_ERRORS, makeCode, readCodes, revoke, type CodeError } from "../../actions/codes.ts";
1718 import { publicOrigin } from "../../core/public_origin.ts";
@@ -200,6 +201,7 @@ function billingView(ctx: Ctx, shown?: Shown, status = 200, refusal?: Refused):
200201 const read = readBilling(ctx.app, ctx.auth.user);
201202 if (!read.ok) return notFoundPage(ctx);
202203 const b = read.value;
204 const notices = new Map(b.forges.map((f) => [f.forge, lapseNotice(lapseFor(ctx.app.db, f.forge))]));
203205 const rows = b.forges.map(
204206 (f) => html`<li class="row" data-forge="${f.forge}">
205207 <form class="row-fields" method="get" action="/settings/billing/change">
@@ -211,6 +213,7 @@ function billingView(ctx: Ctx, shown?: Shown, status = 200, refusal?: Refused):
211213 </select>
212214 ${btn("Review change")}
213215 </form>
216 ${notices.get(f.forge) === undefined ? null : html`<p class="muted small" data-lapse-notice>${notices.get(f.forge)}</p>`}
214217 </li>`,
215218 );
216219 const rendering = performance.now();
test/billing-tui.test.ts +9
@@ -212,3 +212,12 @@ test("a forge's row shows its customer's newest payment in minor units, and noth
212212 recordPayment(app.db, { kind: "refund", invoice: "in_tui1" });
213213 expect(kid()).toContain("last payment refunded 1999 usd (minor units)");
214214 });
215
216 test("a forge in grace shows the lapse notice on its terminal row", () => {
217 const was = getStored(app.db, "kid")!;
218 putEntitlement(app.db, { forge: "kid", plan: was.plan, status: "grace", source: "stripe", provider: "stripe" }, "small", "u");
219 const row = billingRows(open(alice).session).find((r) => r.title === "kid");
220 putEntitlement(app.db, { forge: "kid", plan: was.plan, status: was.status, source: was.source, provider: was.provider }, "small", "u");
221 expect(row?.meta).not.toContain("lapsed");
222 expect(row?.below?.[0]).toMatch(/Your payment lapsed: the grace period ends on \d{4}-\d\d-\d\d UTC/);
223 });
test/billing-webhook-keeps.test.ts added +125
@@ -0,0 +1,125 @@
1 // A lapse webhook delivered to the real handler (`POST /hooks/stripe`) leaves every forge, repo and
2 // app row and the data dir as they were: only billing's own tables and the event log may change.
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { readdirSync, statSync } from "node:fs";
5 import { mkdtemp, rm } from "node:fs/promises";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { createApp, type App } from "../src/app.ts";
9 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
10 import { spawnForge } from "../src/actions/spawn.ts";
11 import { sealKey, sealWebhook } from "../src/billing/connection.ts";
12 import { setStripeFetch } from "../src/billing/sync.ts";
13 import { createApp as createAppRow } from "../src/core/apps.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { bootHostedChild, closeHostedChildren } from "../src/spawn/host.ts";
17 import { hostedPlacement } from "../src/spawn/placement.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21 const secret = "whsec_keeps_secret";
22 let dir: string;
23 let app: App;
24 let servers: Servers;
25 let status = "active";
26 let n = 0;
27
28 async function deliver(type: string, next: string): Promise<void> {
29 status = next;
30 const body = JSON.stringify({ id: `evt_k${++n}`, type, data: { object: { id: "sub_keep", status: next } } });
31 const t = Math.floor(Date.now() / 1000);
32 const k = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
33 const mac = new Uint8Array(await crypto.subtle.sign("HMAC", k, new TextEncoder().encode(`${t}.${body}`)));
34 const res = await fetch(`http://127.0.0.1:${servers.port}/hooks/stripe`, {
35 method: "POST", headers: { "stripe-signature": `t=${t},v1=${Buffer.from(mac).toString("hex")}`, "x-forwarded-for": `10.9.0.${n}` }, body,
36 });
37 expect(res.status).toBe(200);

This name regex hides any table containing 'rate', 'hit', 'event', 'setting' or 'secret' from the comparison. Use an explicit allow-list of the billing tables the webhook writes.

38 }
39
40 /**
41 * The tables the webhook writes, named one by one: every other table is compared whole, so a write
42 * anywhere else (a forge, repo or app row deleted) turns this red.
43 */
44 const WRITABLE = new Set(["entitlement", "entitlement_change", "stripe_event", "event"]);
45
46 /**
47 * Columns a write may touch in a table otherwise compared: reading the sealed Stripe secrets stamps
48 * when.
49 */
50 const STAMPS: Record<string, string> = { secret: "last_read_at" };
51
52 function rows(): Record<string, unknown[]> {
53 const out: Record<string, unknown[]> = {};
54 const names = app.db.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all() as { name: string }[];
55 for (const { name } of names) if (!WRITABLE.has(name)) {
56 const all = app.db.query(`SELECT * FROM "${name}"`).all() as Record<string, unknown>[];
57 const stamp = STAMPS[name];
58 out[name] = stamp ? all.map(({ [stamp]: _, ...rest }) => rest) : all;
59 }
60 return out;
61 }
62
63 /**
64 * Every file under the data dir, with its size (but the plan notice the webhook writes to a child):
65 * the forge's and app's directories included.
66 */
67 function files(root: string): string[] {
68 const out: string[] = [];
69 const walk = (d: string): void => {
70 for (const e of readdirSync(d, { withFileTypes: true })) {
71 const p = join(d, e.name);
72 if (e.isDirectory()) walk(p);
73 else if (!/\.(db|sqlite)(-wal|-shm)?$|\.log$|^plan\.json$/.test(e.name)) out.push(`${p.slice(root.length)}:${statSync(p).size}`);
74 }
75 };
76 walk(root);
77 return out.sort();
78 }
79
80 beforeAll(async () => {
81 dir = await mkdtemp(join(tmpdir(), "billing-keeps-"));
82 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
83 servers = await serve(app);
84 sealKey(app.db, dir, "sk_test_abcdefgh12345678");
85 sealWebhook(app.db, dir, secret);
86 setStripeFetch(app, (async () =>
87 new Response(JSON.stringify({ id: "sub_keep", status, customer: "cus_keep", metadata: { forge: "kid", plan: "medium" }, items: { data: [{ current_period_end: 1900000000 }] } }), { status: 200 })) as unknown as typeof fetch);
88 const admin = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", isAdmin: true });
89 if (!admin.ok) throw new Error("user");
90 const repo = await createRepo(app, admin.value, { name: "site", visibility: "private" });
91 if (!repo.ok) throw new Error("repo");
92 await commitToBranch(app, admin.value, repo.value, { message: "v1", files: [{ path: "index.html", content: "hi" }] });
93 const made = createAppRow(app.db, { repoId: repo.value.id, slug: "site", access: "private" });
94 if (!made.ok) throw new Error("app");
95 const out = await spawnForge(
96 app, admin.value, { name: "kid", org: "kid", apps: [], carryBriefs: false, carrySubscriptions: false },
97 { catalog: [], briefs: [], subscriptions: [] },
98 { placement: hostedPlacement({ host: "forge.test" }), request: new Request("https://forge.test/spawn", { method: "POST", headers: { origin: "https://forge.test" } }), url: new URL("https://forge.test/spawn") },
99 );
100 if (!out.ok) throw new Error(JSON.stringify(out.error));
101 await bootHostedChild(app, "kid");
102 await deliver("customer.subscription.updated", "active");
103 });
104 afterAll(async () => {
105 setStripeFetch(app, undefined);
106 closeHostedChildren(app);
107 await servers.stop();
108 await rm(dir, { recursive: true, force: true });
109 });
110
111 test("past-due, unpaid and canceled webhooks leave forge, repo and app rows and the data dir unchanged", async () => {
112 const before = rows();
113 for (const t of ["forge", "repo", "app"]) expect(Object.keys(before).some((k) => k.toLowerCase().includes(t))).toBe(true);
114 expect((before["app"] ?? []).length).toBeGreaterThan(0);
115 const filesBefore = files(dir);
116 expect(filesBefore.length).toBeGreaterThan(0);
117 for (const next of ["past_due", "unpaid", "canceled"]) {
118 await deliver("customer.subscription.updated", next);
119 expect(rows()).toEqual(before);
120 expect(files(dir)).toEqual(filesBefore);
121 }
122 await deliver("customer.subscription.deleted", "canceled");
123 expect(rows()).toEqual(before);
124 expect(files(dir)).toEqual(filesBefore);
125 });
test/billing.test.ts +8
@@ -190,6 +190,14 @@ describe("billing seam", () => {
190190 expect(entitlementOf(app.db, "kid", "small").plan).toBe(from);
191191 });
192192
193 test("a forge in grace is told the UTC day grace ends, in one sentence, on the Billing page", async () => {
194 const was = getStored(app.db, "kid")!;
195 putEntitlement(app.db, { forge: "kid", plan: was.plan, status: "grace", source: "stripe", provider: "stripe" }, "small", "u");
196 const text = await (await send("GET", "/settings/billing", admin)).text();
197 putEntitlement(app.db, { forge: "kid", plan: was.plan, status: was.status, source: was.source, provider: was.provider }, "small", "u");
198 expect(text).toMatch(/data-lapse-notice>Your payment lapsed: the grace period ends on \d{4}-\d\d-\d\d UTC, and then your forge sleeps; its data is kept until \d{4}-\d\d-\d\d UTC\./);
199 });
200
193201 test("the Billing page's row leads to the preview, not straight to the grant", async () => {
194202 const text = await (await send("GET", "/settings/billing", admin)).text();
195203 expect(text).toContain('action="/settings/billing/change"');
test/lapse-words.test.ts added +43
@@ -0,0 +1,43 @@
1 // The lapse notice names the day grace ends (UTC) and what follows; no billing path deletes
2 // anything.
3 import { describe, expect, test } from "bun:test";
4 import { readFileSync } from "node:fs";
5 import { join } from "node:path";
6 import { lapseOf } from "../src/billing/lapse.ts";
7 import { exportSentence, lapseNotice } from "../src/billing/lapse_words.ts";
8
9 const DAY = 86_400_000;
10 const past = { plan: "pro", status: "grace", source: "stripe", subscribed: true } as const;
11
12 describe("lapse notice", () => {
13 test("one sentence with the UTC end date and the consequence", () => {
14 const since = Date.parse("2026-03-01T23:30:00Z");
15 const s = lapseNotice(lapseOf({ ...past, since }, since + DAY, 7, 30));
16 expect(s).toBe("Your payment lapsed: the grace period ends on 2026-03-08 UTC, and then your forge sleeps; its data is kept until 2026-04-07 UTC.");
17 expect(s!.match(/\.(\s|$)/g)?.length).toBe(1);
18 });
19 test("names the same keep-until day the wake page names once the grace is over", () => {
20 const since = Date.parse("2026-03-01T23:30:00Z");
21 const notice = lapseNotice(lapseOf({ ...past, since }, since + DAY, 7, 30))!;
22 const asleep = lapseOf({ ...past, since }, since + 8 * DAY, 7, 30);
23 if (asleep.state !== "none") throw new Error(asleep.state);
24 const kept = /kept until (\d{4}-\d\d-\d\d)/;
25 expect(kept.exec(notice)?.[1]).toBe(kept.exec(exportSentence(asleep, "https://forge.test"))![1]!);
26 });
27 test("says nothing for an active or already-asleep forge", () => {
28 expect(lapseNotice({ state: "active" })).toBeUndefined();
29 expect(lapseNotice(lapseOf({ ...past, since: 0 }, 99 * DAY, 7, 30))).toBeUndefined();
outdated

Pins nothing about the webhook path: src/actions/billing.ts (where webhooks arrive) is not in this list, and a regex over file text does not show that delivering a webhook leaves rows intact. Replace with a behavioural test that delivers a past-due webhook and checks forge/repo/app rows are unchanged.

30 });
31 });
32
33 // The behaviour is pinned by test/billing-webhook-keeps.test.ts (a real webhook, rows and files
34 // unchanged); this scan is the second guard, over the modules the handler enters through.
35 describe("billing source never deletes a forge's data", () => {
36 test("no webhook-path module removes forge, repo or app data", () => {
37 const risky = /DELETE FROM (forge|repo|app|user|issue|pull|run)\w*\b|rmSync|unlink|\brm\(|rimraf|dropForge|removeForge/i;
38 const files = ["actions/billing.ts", "http/stripe_hook.ts", ...["sync.ts", "stripe.ts", "subscription.ts", "checkout_completed.ts", "lapse.ts", "lapse_rule.ts", "lapse_words.ts", "payments.ts", "store.ts"].map((f) => `billing/${f}`)];
39 for (const f of files) {
40 expect({ f, hit: risky.exec(readFileSync(join(import.meta.dir, "../src", f), "utf8"))?.[0] }).toEqual({ f, hit: undefined });
41 }
42 });
43 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs