Public: anyone can read this; the crew can change it.
A forge that lapses, sits in grace, pauses and is paid again is proven by one test with a fake clock #13060
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/13034-a-forge-that-lapses-sits-in-grace-pauses → main 4 commits fork 2 threads · 2 unresolved
1 file
changed +158
−0
test/billing-lifecycle.test.ts added +158
| @@ -0,0 +1,158 @@ | ||
| 1 | // A forge that lapses, sits in grace, pauses and is paid again, on one fake clock (#13034): | |
| 2 | // nothing is deleted at any step, its apps pause only after grace, the owner's line changes at each | |
| 3 | // step, paying resumes it. | |
| 4 | import { afterAll, beforeAll, expect, setSystemTime, test } from "bun:test"; | |
| 5 | import { existsSync } from "node:fs"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { childDirOf, listChildrenNow, spawnForge } from "../src/actions/spawn.ts"; | |
| 11 | import { sealKey, sealWebhook } from "../src/billing/connection.ts"; | |
| 12 | import { useCheckout } from "../src/billing/checkout.ts"; | |
| 13 | import { lapseFor } from "../src/billing/lapse.ts"; | |
| 14 | import { lapseRule, lapseRuleWords } from "../src/billing/lapse_rule.ts"; | |
| 15 | import { exportSentence, lapsedSentence } from "../src/billing/lapse_words.ts"; | |
| 16 | import { noticeOf } from "../src/billing/notice.ts"; | |
| 17 | import { setStripeFetch } from "../src/billing/sync.ts"; | |
| 18 | import { createUser } from "../src/core/users.ts"; | |
| 19 | import { ok } from "../src/kernel/result.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { graceWords } from "../src/spawn/clients.ts"; | |
| 22 | import { bootHostedChild, childAwake, closeHostedChildren, payAgainGate, sleepLapsed, wakeGate } from "../src/spawn/host.ts"; | |
| 23 | import { hostedPlacement } from "../src/spawn/placement.ts"; | |
| 24 | import { quietLogs } from "./helpers/globals.ts"; | |
| 25 | ||
| 26 | quietLogs(); | |
| 27 | const secret = "whsec_lifecycle_secret"; | |
| 28 | const DAY = 86_400_000; | |
| 29 | const T0 = Date.parse("2026-06-01T12:00:00Z"); | |
| 30 | let dir: string; | |
| 31 | let app: App; | |
| 32 | let servers: Servers; | |
| 33 | let status = "active"; | |
| 34 | let n = 0; | |
| 35 | ||
| 36 | async function deliver(next: string): Promise<void> { | |
| 37 | status = next; | |
| 38 | const body = JSON.stringify({ id: `evt_lc${++n}`, type: "customer.subscription.updated", data: { object: { id: "sub_lc", status: next } } }); | |
| 39 | const t = Math.floor(Date.now() / 1000); | |
| 40 | const k = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); | |
| 41 | const mac = new Uint8Array(await crypto.subtle.sign("HMAC", k, new TextEncoder().encode(`${t}.${body}`))); | |
| 42 | const res = await fetch(`http://127.0.0.1:${servers.port}/hooks/stripe`, { | |
| 43 | method: "POST", headers: { "stripe-signature": `t=${t},v1=${Buffer.from(mac).toString("hex")}`, "x-forwarded-for": `10.7.0.${n}` }, body, | |
| 44 | }); | |
| 45 | expect(res.status).toBe(200); | |
| 46 | } | |
| 47 | ||
| 48 | beforeAll(async () => { | |
| 49 | dir = await mkdtemp(join(tmpdir(), "billing-lifecycle-")); | |
| 50 | app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 }); | |
| 51 | servers = await serve(app); | |
| 52 | sealKey(app.db, dir, "sk_test_abcdefgh12345678"); | |
| 53 | sealWebhook(app.db, dir, secret); | |
| 54 | setStripeFetch(app, (async () => | |
| 55 | new Response(JSON.stringify({ id: "sub_lc", status, customer: "cus_lc", metadata: { forge: "kid", plan: "medium" }, items: { data: [{ current_period_end: 1900000000 }] } }), { status: 200 })) as unknown as typeof fetch); | |
| 56 | useCheckout(app, { | |
| 57 | name: "fake", | |
| 58 | create: async () => ok({ id: "cs_lc", url: "https://pay.test/cs_lc" }), | |
| 59 | state: async () => ok({ paid: false, customer: "", subscription: "" }), | |
| 60 | }); | |
| 61 | const admin = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", isAdmin: true }); | |
| 62 | if (!admin.ok) throw new Error("user"); | |
| 63 | const out = await spawnForge( | |
| 64 | app, admin.value, { name: "kid", org: "kid", apps: [], carryBriefs: false, carrySubscriptions: false }, | |
| 65 | { catalog: [], briefs: [], subscriptions: [] }, | |
| 66 | { 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") }, | |
| 67 | ); | |
| 68 | if (!out.ok) throw new Error(JSON.stringify(out.error)); | |
| 69 | await bootHostedChild(app, "kid"); | |
| 70 | // warm the first webhook (key import, route, sqlite) so the timed span below is the steps only | |
| 71 | await deliver("active"); | |
| 72 | }); | |
| 73 | afterAll(async () => { | |
| 74 | setSystemTime(); | |
| 75 | useCheckout(app, undefined); | |
| 76 | setStripeFetch(app, undefined); | |
| 77 | closeHostedChildren(app); | |
| 78 | await servers.stop(); | |
| 79 | await rm(dir, { recursive: true, force: true }); | |
| 80 | }); | |
| 81 | ||
| 82 | test("paid → past due → grace → paused → paid again, nothing deleted, the line changes at each step", async () => { | |
| 83 | const child = listChildrenNow(app).find((c) => c.name === "kid")!; | |
| 84 | const kept = () => existsSync(childDirOf(app, child.bodyId)) && listChildrenNow(app).some((c) => c.name === "kid"); | |
| 85 | const graceDays = lapseRule(app.db).graceDays; | |
| 86 | expect(lapseRuleWords(lapseRule(app.db))).toContain(`${graceDays} days of grace`); | |
| 87 | setSystemTime(new Date(T0)); | |
| 88 | const started = performance.now(); | |
| 89 | ||
| 90 | // paid: awake, no line | |
| 91 | await deliver("active"); | |
| 92 | expect(lapseFor(app.db, "kid").state).toBe("active"); | |
| 93 | expect(noticeOf(childDirOf(app, child.bodyId))?.status).toBe("active"); | |
| 94 | expect(graceWords({})).toBeNull(); | |
| 95 | expect(await sleepLapsed(app)).toEqual([]); | |
| 96 | expect(childAwake(app, "kid")).toBe(true); | |
| 97 | expect(kept()).toBe(true); | |
| 98 | ||
| 99 | // past due: grace begins, the owner is told the day it pauses; apps still run | |
| 100 | await deliver("past_due"); | |
| 101 | const graceEnd = T0 + graceDays * DAY; | |
| 102 | const due = lapseFor(app.db, "kid"); | |
| 103 | expect(due).toMatchObject({ state: "grace", graceUntil: graceEnd }); | |
| 104 | const dueLine = graceWords({ graceUntil: graceEnd })!; | |
| 105 | expect(dueLine).toBe("grace until 2026-06-08"); | |
| 106 | expect(noticeOf(childDirOf(app, child.bodyId))).toMatchObject({ status: "grace", periodEnd: graceEnd / 1000 }); | |
| 107 | expect(await sleepLapsed(app)).toEqual([]); | |
| 108 | expect(childAwake(app, "kid")).toBe(true); | |
| 109 | ||
| 110 | // the last moment of grace: still running | |
| 111 | setSystemTime(new Date(graceEnd - 1000)); | |
| 112 | expect(lapseFor(app.db, "kid").state).toBe("grace"); | |
| 113 | expect(await sleepLapsed(app)).toEqual([]); | |
| 114 | expect(childAwake(app, "kid")).toBe(true); | |
| 115 | expect(kept()).toBe(true); | |
| 116 | ||
| 117 | // grace over: paused, data kept, the line is now the lapsed sentence and the keep-until | |
| 118 | setSystemTime(new Date(graceEnd + 1000)); | |
| 119 | const none = lapseFor(app.db, "kid"); | |
| 120 | expect(none.state).toBe("none"); | |
| 121 | if (none.state !== "none") throw new Error("not lapsed"); | |
| 122 | expect(await sleepLapsed(app)).toEqual(["kid"]); | |
| 123 | expect(childAwake(app, "kid")).toBe(false); | |
| 124 | expect(kept()).toBe(true); | |
| 125 | const lapsedLines = [lapsedSentence("kid"), exportSentence(none, "forge.test")]; | |
| 126 | expect(lapsedLines[0]).toBe("kid is asleep because its subscription ended and was not paid again."); | |
| 127 | expect(lapsedLines[1]).toContain("Your data is kept until 2026-07-08"); | |
| 128 | expect(graceWords({})).toBeNull(); | |
| 129 | expect(new Set([dueLine, ...lapsedLines]).size).toBe(3); | |
| 130 | ||
| 131 | // months later it is still paused and still kept | |
| 132 | setSystemTime(new Date(graceEnd + 20 * DAY)); | |
| 133 | expect(await sleepLapsed(app)).toEqual([]); | |
| 134 | expect(kept()).toBe(true); | |
| 135 | ||
| 136 | const visit = () => new Request("https://kid--forge.test/", { headers: { host: "kid--forge.test", accept: "text/html" } }); | |
| 137 | const paused = await wakeGate(app, visit()); | |
| 138 | expect(paused?.status).toBe(402); | |
| 139 | const page = await paused!.text(); | |
| 140 | expect(page).toContain(lapsedSentence("kid")); | |
| 141 | expect(page).toContain("Your data is kept until 2026-07-08"); | |
| 142 | ||
| 143 | // pay again: the button makes the checkout, the provider's webhook pays, the forge resumes and | |
| 144 | // the line clears | |
| 145 | const press = new Request("https://kid--forge.test/pay-again", { method: "POST", headers: { host: "kid--forge.test", origin: "https://kid--forge.test" } }); | |
| 146 | const paying = await payAgainGate(app, press); | |
| 147 | expect(paying?.status).toBe(303); | |
| 148 | expect(paying?.headers.get("location")).toBe("https://pay.test/cs_lc"); | |
| 149 | await deliver("active"); | |
| 150 | expect(lapseFor(app.db, "kid")).toEqual({ state: "active" }); | |
| 151 | expect(noticeOf(childDirOf(app, child.bodyId))?.status).toBe("active"); | |
outdated
This budget fails on a cold run (about 1.3 s reported). Warm the slow step before |
||
| 152 | expect((await wakeGate(app, visit()))?.status).not.toBe(402); | |
| 153 | expect(await payAgainGate(app, new Request(press))).toBeUndefined(); | |
| 154 | expect(await sleepLapsed(app)).toEqual([]); | |
| 155 | expect(kept()).toBe(true); | |
| 156 | ||
| 157 | expect(performance.now() - started).toBeLessThan(500); | |
| 158 | }); |
new above
offline
These are helper outputs, not the line the owner reads on the page. Assert the served home HTML contains each sentence at its step if the page renders them.