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

POST /hooks/stripe verifies the signature on the raw body and turns each event into an entitlement #11219

Parked opened this in answer to
Closed without merging

torque/forge:torque/11137-post-hooks-stripe-verifies-the-signature → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +580 −3
docs/features/billing.md +2 −1
@@ -6,7 +6,8 @@ Billing records the plan each forge is on (`src/billing/`): a store of entitleme
66 - **Grant by hand (admin, a person):** the Billing page, the terminal screen, `PUT /api/v1/forges/{name}/plan` with `{ "plan": "large" }` (`GET` reads it), or the MCP `forges` tool with `{ forge, plan }` (planned first; `dryRun: false` grants).
77 - **Audit:** every grant is a row in `entitlement_change` and a `billing.plan` event.
88 - **Terminal:** the palette's *Billing* (admins), `src/tui/screens/billing.ts`: `j`/`k` pick a forge, `s`, `m` or `l` grants that plan after a yes/no; `c` connects Stripe (key shown as dots), `w` saves a signing secret, `x` disconnects after a yes/no.
9 - **Stripe (#11136):** Settings → Billing → Provider takes one key (`src/billing/stripe.ts`, `connection.ts`); how to connect it is in `docs/PROFIT.md`. Not yet: the `/hooks/stripe` receiver, and checkout, portal and reconcile, which come with the pull that calls them.
9 - **Stripe (#11136):** Settings → Billing → Provider takes one key (`src/billing/stripe.ts`, `connection.ts`); how to connect it is in `docs/PROFIT.md`. Not yet: checkout and the portal, which come with the pull that calls them.
10 - **Webhook (#11137):** `POST /hooks/stripe` (`src/http/stripe_hook.ts`) reads the raw body, checks `Stripe-Signature` (`t=…,v1=…`, HMAC-SHA256 over `t.body` keyed by the `whsec_` string, every `v1` compared in constant time, 300 s tolerance; `src/billing/signature.ts`) and answers 400 for a bad one, counted on the Billing page (an alarm from 5 a day). Public, rate limited, no cookies. Each event id is kept once; a repeat answers 200 and does nothing. `checkout.session.completed` marks the order (`client_reference_id`) paid and binds its customer and subscription; any subscription or invoice event re-reads the subscription from Stripe (`src/billing/reconcile.ts`) and writes what Stripe says now, after the answer is sent. A sweep reconciles every paid subscription once a day (checked hourly). Settings → Billing → Provider shows the last event and when, refusals today and the last sweep. Orders are made by checkout, which is not here yet.
1011
1112 ## Gift codes
1213 A code gives a plan for free, with or without a payment provider (`src/billing/codes.ts`, `src/actions/codes.ts`). No provider is asked: a redeemed code writes the entitlement itself, source `code:<id>`.
src/actions/billing.ts +4
@@ -6,6 +6,7 @@
66 * shows in the audit trail. Anyone else is told `not_found`.
77 */
88
9 import { hookState, type HookState } from "../billing/orders.ts";
910 import type { App } from "../app.ts";
1011 import { changesOf, entitlementOf, putEntitlement, type EntitlementChange } from "../billing/store.ts";
1112 import type { Entitlement } from "../billing/types.ts";
@@ -41,6 +42,8 @@ export interface BillingView {
4142 readonly forges: readonly (Entitlement & { size: string })[];
4243 /** The Stripe connection (mode, whether events are signed), never the key. */
4344 readonly stripe: Connection | undefined;
45 /** The probe: the last event received, refused deliveries today, the last sweep (#11137). */
46 readonly hook: HookState;
4447 }
4548
4649 const admin = (a: User | undefined): Result<User, "not_found"> => (a?.isAdmin === true && a.kind !== "agent" ? ok(a) : err("not_found"));
@@ -51,6 +54,7 @@ export function readBilling(app: App, actor: User | undefined): Result<BillingVi
5154 return ok({
5255 forges: listChildrenNow(app).map((c) => ({ ...entitlementOf(app.db, c.name, c.size), size: c.size })),
5356 stripe: connectionOf(app.db),
57 hook: hookState(app.db),
5458 });
5559 }
5660
src/billing/connection.ts +11 −2
@@ -44,10 +44,10 @@ export function sealWebhook(db: Database, dataDir: string, secret: string, endpo
4444 }
4545
4646 /** The sealed key and the endpoint id, opened (audited as `secret.read`). */
47 export function openKey(db: Database, dataDir: string, bus: EventBus, actor: string): { key: string; endpointId: string } | undefined {
47 export function openKey(db: Database, dataDir: string, bus: EventBus, actor?: string): { key: string; endpointId: string } | undefined {
4848 const c = connectionOf(db);
4949 if (!c) return undefined;
50 const got = resolveSecrets(db, dataDir, bus, [KEY_NAME[c.mode], ENDPOINT], { actor });
50 const got = resolveSecrets(db, dataDir, bus, [KEY_NAME[c.mode], ENDPOINT], actor === undefined ? {} : { actor });
5151 const key = got[KEY_NAME[c.mode]];
5252 if (key === undefined) return undefined;
5353 holdValues("stripe", [key]);
@@ -57,3 +57,12 @@ export function openKey(db: Database, dataDir: string, bus: EventBus, actor: str
5757 export function forget(db: Database): void {
5858 for (const n of [...Object.values(KEY_NAME), SECRET, ENDPOINT]) deleteSecret(db, "forge", "", n);
5959 }
60
61 /** The sealed signing secret, opened for one verification (audited as `secret.read`); undefined when none is saved. */
62 export function openSigningSecret(db: Database, dataDir: string, bus: EventBus): string | undefined {
63 if (!listSecretNames(db, "forge").some((s) => s.name === SECRET)) return undefined;
64 const v = resolveSecrets(db, dataDir, bus, [SECRET], {})[SECRET];
65 if (v === undefined) return undefined;
66 holdValues("stripe", [v]);
67 return v;
68 }
src/billing/orders.ts added +91
@@ -0,0 +1,91 @@
1 /**
2 * Orders and what the webhook knows (#11137): an order is one forge's wish
3 * for one plan, `open` until Stripe says the checkout completed, then `paid`
4 * and bound to Stripe's customer and subscription. Also here: each event id
5 * kept once (`claimEvent`) and the probe's numbers (`hookState`). Plain data;
6 * the HTTP route is `http/stripe_hook.ts`, the entitlement write `reconcile.ts`.
7 */
8
9 import type { Database } from "bun:sqlite";
10
11 export interface Order {
12 readonly id: string;
13 readonly forge: string;
14 readonly plan: string;
15 readonly status: "open" | "paid";
16 readonly customerId: string;
17 readonly subscriptionId: string;
18 }
19
20 interface Row { id: string; forge: string; plan: string; status: "open" | "paid"; customer_id: string; subscription_id: string }
21 const fromRow = (r: Row): Order => ({ id: r.id, forge: r.forge, plan: r.plan, status: r.status, customerId: r.customer_id, subscriptionId: r.subscription_id });
22
23 export function createOrder(db: Database, o: { id: string; forge: string; plan: string }, now = Date.now()): void {
24 db.query("INSERT INTO billing_order (id, forge, plan, created_at) VALUES (?1, ?2, ?3, ?4)").run(o.id, o.forge, o.plan, now);
25 }
26
27 export const getOrder = (db: Database, id: string): Order | undefined => {
28 const r = db.query<Row, [string]>("SELECT * FROM billing_order WHERE id = ?1").get(id);
29 return r ? fromRow(r) : undefined;
30 };
31
32 export const orderBySubscription = (db: Database, subscriptionId: string): Order | undefined => {
33 const r = db.query<Row, [string]>("SELECT * FROM billing_order WHERE subscription_id = ?1 AND status = 'paid' ORDER BY paid_at DESC LIMIT 1").get(subscriptionId);
34 return r ? fromRow(r) : undefined;
35 };
36
37 /** Every paid order with a subscription, one per subscription: what the daily sweep reconciles. */
38 export const paidSubscriptions = (db: Database): string[] =>
39 db.query<{ s: string }, []>("SELECT DISTINCT subscription_id AS s FROM billing_order WHERE status = 'paid' AND subscription_id <> ''").all().map((r) => r.s);
40
41 /** Bind the order to its customer and subscription and mark it paid; false when there is no such order. */
42 export function markPaid(db: Database, id: string, customerId: string, subscriptionId: string, now = Date.now()): boolean {
43 return db.query("UPDATE billing_order SET status = 'paid', customer_id = ?2, subscription_id = ?3, paid_at = ?4 WHERE id = ?1").run(id, customerId, subscriptionId, now).changes > 0;
44 }
45
46 /** Keep the event id; false when it was already kept (a replay). Old ids are dropped after 35 days, past Stripe's retry window. */
47 export function claimEvent(db: Database, id: string, type: string, now = Date.now()): boolean {
48 const fresh = db.query("INSERT OR IGNORE INTO stripe_event (id, type, received_at) VALUES (?1, ?2, ?3)").run(id, type, now).changes > 0;
49 if (fresh) db.query("DELETE FROM stripe_event WHERE received_at < ?1").run(now - 35 * 86_400_000);
50 return fresh;
51 }
52
53 const setState = (db: Database, k: string, v: string): void => {
54 db.query("INSERT INTO stripe_hook_state (k, v) VALUES (?1, ?2) ON CONFLICT (k) DO UPDATE SET v = excluded.v").run(k, v);
55 };
56 const getState = (db: Database, k: string): string | undefined => db.query<{ v: string }, [string]>("SELECT v FROM stripe_hook_state WHERE k = ?1").get(k)?.v;
57
58 export function noteReceived(db: Database, id: string, type: string, now = Date.now()): void {
59 setState(db, "last_id", id); setState(db, "last_type", type); setState(db, "last_at", String(now));
60 }
61
62 /** A refused delivery counts toward the alarm (`ALARM_AT` in a day shows it on the page). */
63 export function noteRefused(db: Database, why: string, now = Date.now()): void {
64 const day = new Date(now).toISOString().slice(0, 10);
65 const n = getState(db, `refused:${day}`);
66 setState(db, `refused:${day}`, String((n === undefined ? 0 : Number(n)) + 1));
67 setState(db, "refused_at", String(now)); setState(db, "refused_why", why);
68 db.query("DELETE FROM stripe_hook_state WHERE k LIKE 'refused:%' AND k < ?1").run(`refused:${new Date(now - 7 * 86_400_000).toISOString().slice(0, 10)}`);
69 }
70
71 export const noteSwept = (db: Database, now = Date.now()): void => setState(db, "swept_at", String(now));
72
73 export interface HookState {
74 readonly last?: { readonly id: string; readonly type: string; readonly at: number };
75 readonly refusedToday: number;
76 readonly lastRefused?: { readonly why: string; readonly at: number };
77 readonly sweptAt?: number;
78 }
79 /** More refusals than this in a day is an alarm on the page: someone is guessing, or the secret is wrong. */
80 export const ALARM_AT = 5;
81
82 export function hookState(db: Database, now = Date.now()): HookState {
83 const id = getState(db, "last_id"), at = getState(db, "last_at");
84 const ra = getState(db, "refused_at"), sw = getState(db, "swept_at");
85 return {
86 ...(id !== undefined && at !== undefined ? { last: { id, type: getState(db, "last_type") ?? "", at: Number(at) } } : {}),
87 refusedToday: Number(getState(db, `refused:${new Date(now).toISOString().slice(0, 10)}`) ?? 0),
88 ...(ra !== undefined ? { lastRefused: { why: getState(db, "refused_why") ?? "", at: Number(ra) } } : {}),
89 ...(sw !== undefined ? { sweptAt: Number(sw) } : {}),
90 };
91 }
src/billing/reconcile.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * Reconcile (#11137): read the subscription from Stripe now and write what
3 * Stripe says, never what an event's body says — events arrive out of order,
4 * so the last one delivered is not the latest truth. The status becomes the
5 * entitlement's: active and trialing are `active`, past_due is `grace`,
6 * anything else is `none`. The plan is the paid order's. Source `stripe`.
7 * Also the daily sweep over every paid subscription, so a missed webhook heals.
8 */
9
10 import type { App } from "../app.ts";
11 import type { Result } from "../kernel/result.ts";
12 import { err, ok } from "../kernel/result.ts";
13 import { openKey } from "./connection.ts";
14 import { hookState, noteSwept, orderBySubscription, paidSubscriptions } from "./orders.ts";
15 import { getStored, putEntitlement } from "./store.ts";
16 import { stripeClient } from "./stripe.ts";
17 import type { EntitlementStatus } from "./types.ts";
18
19 export type ReconcileError = "not_connected" | "unknown_subscription" | "stripe_failed";
20
21 export const statusOf = (stripe: string): EntitlementStatus =>
22 stripe === "active" || stripe === "trialing" ? "active" : stripe === "past_due" ? "grace" : "none";
23
24 export async function reconcile(app: App, subscriptionId: string, fetchFn: typeof fetch = fetch): Promise<Result<{ forge: string; status: EntitlementStatus }, ReconcileError>> {
25 const order = orderBySubscription(app.db, subscriptionId);
26 if (order === undefined) return err("unknown_subscription");
27 const opened = openKey(app.db, app.config.dataDir, app.bus);
28 if (opened === undefined) return err("not_connected");
29 const got = await stripeClient(opened.key, fetchFn).getSubscription(subscriptionId);
30 if (!got.ok) return err("stripe_failed");
31 const status = statusOf(got.value.status);
32 const before = getStored(app.db, order.forge);
33 const same = before !== undefined && before.plan === order.plan && before.status === status && before.periodEnd === got.value.periodEnd && before.source === "stripe" && before.subscriptionId === subscriptionId;
34 if (!same)
35 putEntitlement(app.db, {
36 forge: order.forge, plan: order.plan, status, ...(got.value.periodEnd === undefined ? {} : { periodEnd: got.value.periodEnd }),
37 provider: "stripe", customerId: order.customerId, subscriptionId, source: "stripe",
38 }, order.plan, "stripe");
39 return ok({ forge: order.forge, status });
40 }
41
42 /** Reconcile every paid subscription, one after another; how many were read and how many failed. */
43 export async function sweep(app: App, fetchFn: typeof fetch = fetch): Promise<{ read: number; failed: number }> {
44 let read = 0, failed = 0;
45 for (const id of paidSubscriptions(app.db)) {
46 const r = await reconcile(app, id, fetchFn);
47 if (r.ok) read++; else failed++;
48 }
49 noteSwept(app.db);
50 return { read, failed };
51 }
52
53 /** The sweep when the last one is a day old (or none ran); true when it ran. */
54 export async function sweepDue(app: App, now = Date.now(), fetchFn: typeof fetch = fetch): Promise<boolean> {
55 const at = hookState(app.db, now).sweptAt;
56 if (at !== undefined && now - at < 86_400_000) return false;
57 await sweep(app, fetchFn);
58 return true;
59 }
src/billing/signature.ts added +58
@@ -0,0 +1,58 @@
1 /**
2 * Stripe's webhook signature, checked on the raw bytes (#11137).
3 * `Stripe-Signature: t=<unix>,v1=<hex>[,v1=<hex>…]`; other keys are ignored.
4 * The signed payload is `${t}.${rawBody}`; the key is the `whsec_…` string as
5 * UTF-8 bytes (Stripe's documented scheme: the whole string, prefix included);
6 * the MAC is HMAC-SHA256. Every `v1` is compared in constant time (a secret
7 * being rotated sends two). A timestamp more than 300 s from now is refused.
8 * Plain data in, a verdict out; the body is never parsed here.
9 */
10
11 export const TOLERANCE_S = 300;
12 export type Verdict = "ok" | "malformed" | "stale" | "mismatch";
13
14 const HEX = /^[0-9a-f]{64}$/;
15
16 export function parseHeader(header: string | null): { t: number; v1: string[] } | undefined {
17 if (header === null || header.length > 1024) return undefined;
18 let t: number | undefined;
19 const v1: string[] = [];
20 for (const part of header.split(",")) {
21 const eq = part.indexOf("=");
22 if (eq < 0) continue;
23 const k = part.slice(0, eq).trim(), v = part.slice(eq + 1).trim();
24 if (k === "t" && /^\d{1,12}$/.test(v)) t = Number(v);
25 else if (k === "v1" && HEX.test(v.toLowerCase())) v1.push(v.toLowerCase());
26 }
27 return t === undefined || v1.length === 0 ? undefined : { t, v1 };
28 }
29
30 const hex = (b: ArrayBuffer): string => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
31
32 /** Constant time over equal-length strings: no early exit on the first differing byte. */
33 function same(a: string, b: string): boolean {
34 if (a.length !== b.length) return false;
35 let d = 0;
36 for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i);
37 return d === 0;
38 }
39
40 /** `hex(HMAC-SHA256(secret, "<t>." + body))`. */
41 export async function sign(secret: string, t: number, body: Uint8Array): Promise<string> {
42 const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
43 const head = new TextEncoder().encode(`${t}.`);
44 const payload = new Uint8Array(head.length + body.length);
45 payload.set(head);
46 payload.set(body, head.length);
47 return hex(await crypto.subtle.sign("HMAC", key, payload));
48 }
49
50 export async function verify(secret: string, header: string | null, body: Uint8Array, nowS: number): Promise<Verdict> {
51 const h = parseHeader(header);
52 if (h === undefined) return "malformed";
53 if (Math.abs(nowS - h.t) > TOLERANCE_S) return "stale";
54 const want = await sign(secret, h.t, body);
55 let ok = false;
56 for (const v of h.v1) ok = same(want, v) || ok;
57 return ok ? "ok" : "mismatch";
58 }
src/billing/stripe.ts +12
@@ -66,6 +66,8 @@ export function formBody(data: { [k: string]: Value }): string {
6666 export interface StripeClient {
6767 addWebhook(url: string): Promise<Result<{ id: string; secret: string }, StripeError>>;
6868 removeWebhook(id: string): Promise<Result<true, StripeError>>;
69 /** What Stripe says about a subscription now: its status and the end of the paid period (unix seconds). */
70 getSubscription(id: string): Promise<Result<{ status: string; periodEnd?: number }, StripeError>>;
6971 }
7072
7173 const PERMISSION = "This key may not create webhook endpoints. Paste a signing secret from Stripe's webhook page instead.";
@@ -112,5 +114,15 @@ export function stripeClient(key: string, fetchFn: typeof fetch = fetch): Stripe
112114 const r = await call("DELETE", `/v1/webhook_endpoints/${encodeURIComponent(id)}`);
113115 return r.ok ? ok(true as const) : r;
114116 },
117 async getSubscription(id) {
118 const r = await call("GET", `/v1/subscriptions/${encodeURIComponent(id)}`);
119 if (!r.ok) return r;
120 const status = str(r.value, "status");
121 if (!status) return err(missing("status"));
122 // The period end moved onto the items in the 2025 API versions; the older top-level field is read too.
123 const items = ((r.value["items"] as { data?: unknown } | undefined)?.data ?? []) as Record<string, unknown>[];
124 const ends = [r.value["current_period_end"], ...items.map((i) => i["current_period_end"])].filter((n): n is number => typeof n === "number" && Number.isFinite(n));
125 return ok({ status, ...(ends.length ? { periodEnd: Math.max(...ends) } : {}) });
126 },
115127 };
116128 }
src/core/migration-pins/20261111120000-stripe-hook.pin added +1
@@ -0,0 +1,1 @@
1 922a00e76e7538e8cd7361206bf5a510b996450d5f44fc1f75351f2cc850d493
src/core/migrations/20261111120000-stripe-hook.ts added +26
@@ -0,0 +1,26 @@
1 // The Stripe webhook (#11137): each event id kept once, so a repeat does
2 // nothing; the orders a checkout binds to a customer and subscription; and
3 // the one row of what the probe on Billing shows. Additive.
4 export default `
5 CREATE TABLE stripe_event (
6 id TEXT PRIMARY KEY,
7 type TEXT NOT NULL,
8 received_at INTEGER NOT NULL
9 );
10 CREATE INDEX stripe_event_received ON stripe_event (received_at);
11 CREATE TABLE billing_order (
12 id TEXT PRIMARY KEY,
13 forge TEXT NOT NULL,
14 plan TEXT NOT NULL,
15 status TEXT NOT NULL CHECK (status IN ('open','paid')) DEFAULT 'open',
16 customer_id TEXT NOT NULL DEFAULT '',
17 subscription_id TEXT NOT NULL DEFAULT '',
18 created_at INTEGER NOT NULL,
19 paid_at INTEGER
20 );
21 CREATE INDEX billing_order_subscription ON billing_order (subscription_id);
22 CREATE TABLE stripe_hook_state (
23 k TEXT PRIMARY KEY,
24 v TEXT NOT NULL
25 );
26 `;
src/core/reserved.ts +1
@@ -33,6 +33,7 @@ export const SYSTEM_NAMES: readonly string[] = [
3333 "platform",
3434 "forge",
3535 "crew",
36 "hooks",
3637 "agent",
3738 "agents",
3839 "bot",
src/http/server.ts +3
@@ -37,6 +37,7 @@ import { plansSet } from "../web/settings/plans.ts";
3737 import { allFlowsPage } from "../web/pages/flows-all.ts";
3838 import { measureSubmit } from "./measure.ts";
3939 import { cspReportSubmit } from "./csp_report.ts";
40 import { stripeHook } from "./stripe_hook.ts";
4041 import { settingsRoutes } from "./settings_routes.ts";
4142 import { pluginRoutes } from "./plugin_routes.ts";
4243 import { pinnedRoutes } from "./pinned_routes.ts";
@@ -827,6 +828,8 @@ export function buildRouter(): Router<Handler> {
827828 router.add("POST", "/_measure", (ctx) => measureSubmit(ctx, routeOf));
828829 // What a page's Content-Security-Policy blocked (http/csp_report.ts): counts only.
829830 router.add("POST", "/csp-report", cspReportSubmit);
831 // Stripe's events, signed on the raw body (http/stripe_hook.ts).
832 router.add("POST", "/hooks/stripe", stripeHook);
830833 router.add("GET", "/", home);
831834 // A spawned child's claim link: GET shows, POST takes it (spawn/claim.ts).
832835 router.add("GET", "/claim", claimFragmentPage);
src/http/stripe_hook.ts added +100
@@ -0,0 +1,100 @@
1 /**
2 * POST /hooks/stripe: Stripe tells the forge who paid and who stopped (#11137).
3 *
4 * Public by nature, so everything is proved here: the raw bytes are read
5 * first and the signature checked on them (`billing/signature.ts`) before
6 * anything is parsed; a bad one answers 400 and counts toward the alarm on
7 * Billing. The route is rate limited per client and for the forge, reads no
8 * cookie and sets none. Each event id is kept once: a repeat answers 200 and
9 * does nothing. The delivery is answered from local work only (the order is
10 * bound in one statement); the read of the subscription from Stripe
11 * (`reconcile`) runs after the answer, and a failure there heals in the
12 * daily sweep. Events arrive out of order, so no event's own body is
13 * trusted for the plan: any subscription or invoice event re-reads the
14 * subscription and writes what Stripe says now.
15 */
16
17 import type { App } from "../app.ts";
18 import { openSigningSecret } from "../billing/connection.ts";
19 import { claimEvent, markPaid, noteReceived, noteRefused } from "../billing/orders.ts";
20 import { reconcile } from "../billing/reconcile.ts";
21 import { verify } from "../billing/signature.ts";
22 import { RateLimiter } from "../core/ratelimit.ts";
23 import type { Ctx } from "./context.ts";
24 import { readBounded } from "./limits.ts";
25 import { clientBucket } from "./peer.ts";
26
27 export const STRIPE_HOOK_PATH = "/hooks/stripe";
28 export const STRIPE_HOOK_MAX = 512 * 1024;
29 const PER_CLIENT = 60;
30 const PER_FORGE = 600;
31 const ID = /^[A-Za-z0-9_]{1,100}$/;
32
33 const limiter = (perMinute: number) => new RateLimiter({ perMinute, adminPerMinute: perMinute, enabled: true });
34 const limits = new WeakMap<App, { client: RateLimiter; forge: RateLimiter }>();
35 const inFlight = new Set<Promise<unknown>>();
36
37 /** Resolves when every reconcile a delivery started has finished (tests, and a clean shutdown). */
38 export const idle = async (): Promise<void> => {
39 while (inFlight.size > 0) await Promise.allSettled([...inFlight]);
40 };
41
42 const answer = (status: number, body: Record<string, unknown>, headers?: Record<string, string>): Response =>
43 new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } });
44
45 const rec = (v: unknown): Record<string, unknown> => (typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
46 const id = (v: unknown): string | undefined => (typeof v === "string" && ID.test(v) ? v : typeof v === "object" && v !== null && ID.test(String(rec(v)["id"])) ? String(rec(v)["id"]) : undefined);
47
48 /** The subscription an event is about, whichever shape Stripe's API version gives it. */
49 export function subscriptionOf(type: string, obj: Record<string, unknown>): string | undefined {
50 if (type.startsWith("customer.subscription.")) return id(obj["id"]);
51 if (type.startsWith("invoice.")) return id(obj["subscription"]) ?? id(rec(rec(obj["parent"])["subscription_details"])["subscription"]);
52 return undefined;
53 }
54
55 export async function stripeHook(ctx: Ctx): Promise<Response> {
56 const { request, app } = ctx;
57 let pair = limits.get(app);
58 if (pair === undefined) {
59 pair = { client: limiter(PER_CLIENT), forge: limiter(PER_FORGE) };
60 limits.set(app, pair);
61 }
62 for (const v of [pair.client.take(clientBucket(request), "ro"), pair.forge.take("forge", "ro")])
63 if (!v.allowed) return answer(429, { error: "rate_limited" }, { "retry-after": String(Math.max(1, v.retryAfter)) });
64
65 const raw = await readBounded(request, STRIPE_HOOK_MAX);
66 if (raw === "too_large") return answer(413, { error: "too_large" });
67
68 const secret = openSigningSecret(app.db, app.config.dataDir, app.bus);
69 const verdict = secret === undefined ? "unsigned" : await verify(secret, request.headers.get("stripe-signature"), raw, Math.floor(Date.now() / 1000));
70 if (verdict !== "ok") {
71 noteRefused(app.db, verdict);
72 return answer(400, { error: "bad_signature" });
73 }
74
75 let event: Record<string, unknown>;
76 try {
77 event = rec(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw)));
78 } catch {
79 return answer(400, { error: "bad_body" });
80 }
81 const eventId = typeof event["id"] === "string" && ID.test(event["id"]) ? event["id"] : undefined;
82 const type = typeof event["type"] === "string" && /^[a-z_.]{1,80}$/.test(event["type"]) ? event["type"] : undefined;
83 if (eventId === undefined || type === undefined) return answer(400, { error: "bad_body" });
84
85 if (!claimEvent(app.db, eventId, type)) return answer(200, { received: true, duplicate: true });
86 noteReceived(app.db, eventId, type);
87
88 const obj = rec(rec(event["data"])["object"]);
89 let subscription = subscriptionOf(type, obj);
90 if (type === "checkout.session.completed") {
91 const order = id(obj["client_reference_id"]), customer = id(obj["customer"]), sub = id(obj["subscription"]);
92 if (order !== undefined && customer !== undefined && sub !== undefined && markPaid(app.db, order, customer, sub)) subscription = sub;
93 }
94 if (subscription !== undefined) {
95 const p = reconcile(app, subscription).catch((error) => app.log.warn("stripe reconcile failed", { error: String(error) }));
96 inFlight.add(p);
97 void p.finally(() => inFlight.delete(p));
98 }
99 return answer(200, { received: true });
100 }
src/main.ts +4
@@ -4,6 +4,7 @@
44 * environment-only — a handful of variables, all with sane defaults.
55 */
66
7 import { sweepDue } from "./billing/reconcile.ts";
78 import { sweepStarts } from "./actions/start_sweep.ts";
89 import { scanNightly } from "./checks/scan.ts";
910 import { nightlyDue } from "./checks/scan_store.ts";
@@ -693,6 +694,8 @@ const staleTimer = setInterval(() => void during("asks", tickAsks), 120_000);
693694 // archived after a month (`actions/start_sweep.ts`, #10912): hourly, and on boot.
694695 const startsTimer = setInterval(() => during("starts", () => void sweepStarts(app)), 3_600_000);
695696 during("starts", () => void sweepStarts(app));
697 // Every paid subscription is read from Stripe once a day, so a webhook that never arrived heals (billing/reconcile.ts, #11137): checked hourly, run when a day has passed.
698 const billingSweepTimer = setInterval(() => during("billing-sweep", () => void sweepDue(app)), 3_600_000);
696699 void during("asks", tickAsks);
697700
698701 // Every start is counted, and one that follows a process that never said
@@ -921,6 +924,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> {
921924 clearInterval(syncTimer);
922925 clearInterval(staleTimer);
923926 clearInterval(startsTimer);
927 clearInterval(billingSweepTimer);
924928 clearInterval(followTimer);
925929 stopClogTick();
926930 stopKeeper();
src/web/pages/billing.ts +13
@@ -14,6 +14,7 @@ import { SIZES } from "../../spawn/sizes.ts";
1414 import { BILLING_SIZES, parseBillingLinks } from "../../settings/billing.ts";
1515 import { getPlans } from "../../settings/plans.ts";
1616 import { changeBillingLinks, readBillingLinks } from "../../actions/signup.ts";
17 import { ALARM_AT, type HookState } from "../../billing/orders.ts";
1718 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
1819 import { field, readForm } from "../form.ts";
1920 import { html, type Html } from "../html.ts";
@@ -119,6 +120,17 @@ export async function billingSetLinks(ctx: Ctx): Promise<Response> {
119120 return billingView(ctx, undefined, {}, undefined, 422, { values: next, error });
120121 }
121122
123 const stamp = (ms: number): string => `${new Date(ms).toISOString().slice(0, 16).replace("T", " ")} UTC`;
124
125 /** What the webhook last did: the last event and when, the refusals today, the last daily sweep. */
126 function hookProbe(h: HookState): Html {
127 return html`<dl class="status-rows" data-probe="stripe-hook">
128 <div class="status-row"><dt>Last event</dt><dd>${h.last === undefined ? "none received yet" : html`<span class="mono">${h.last.type}</span> · ${stamp(h.last.at)}`}</dd></div>
129 <div class="status-row"><dt>Refused today</dt><dd ${h.refusedToday >= ALARM_AT ? html`class="error" role="alert"` : null}>${h.refusedToday}${h.refusedToday >= ALARM_AT ? " — check the signing secret" : ""}${h.lastRefused === undefined ? "" : ` · last ${stamp(h.lastRefused.at)}`}</dd></div>
130 <div class="status-row"><dt>Daily check</dt><dd>${h.sweptAt === undefined ? "not yet run" : stamp(h.sweptAt)}</dd></div>
131 </dl>`;
132 }
133
122134 // GET /settings/billing
123135 export function billingPage(ctx: Ctx): Response {
124136 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
@@ -158,6 +170,7 @@ function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {
158170 <input class="input mono" type="password" name="secret" autocomplete="off" placeholder="whsec_…" aria-label="Webhook signing secret" required />
159171 ${btn("Save signing secret")}
160172 </form>`}
173 ${hookProbe(b.hook)}
161174 <form method="post" action="${PATH}/stripe/disconnect">${btn("Disconnect")}</form>`
162175 : html`<p class="muted small">Paste a Stripe secret or restricted key; the forge registers its own webhook.</p>
163176 <form class="row-fields" method="post" action="${PATH}/stripe/connect">
test/stripe-hook.test.ts added +195
@@ -0,0 +1,195 @@
1 /**
2 * POST /hooks/stripe (#11137): the signature on the raw bytes, a replay, out
3 * of order events, the order bound at checkout, the sweep, and the probe.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
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 { readBilling } from "../src/actions/billing.ts";
11 import { sealKey, sealWebhook } from "../src/billing/connection.ts";
12 import { createOrder, getOrder, hookState, markPaid } from "../src/billing/orders.ts";
13 import { sweep } from "../src/billing/reconcile.ts";
14 import { parseHeader, sign, verify } from "../src/billing/signature.ts";
15 import { getStored, putEntitlement } from "../src/billing/store.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { idle } from "../src/http/stripe_hook.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 const SECRET = "whsec_testsecret0123456789";
24 const now = () => Math.floor(Date.now() / 1000);
25
26 describe("signature", () => {
27 const body = new TextEncoder().encode('{"id":"evt_1"}');
28 test("matches a hand computation: HMAC-SHA256 over `t.body`, key the whole secret as UTF-8", async () => {
29 const t = 1_700_000_000;
30 const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(SECRET), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
31 const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${t}.{"id":"evt_1"}`)));
32 expect(await sign(SECRET, t, body)).toBe([...mac].map((b) => b.toString(16).padStart(2, "0")).join(""));
33 });
34 test("verdicts: ok, stale, mismatch, malformed; other keys ignored; any v1 may match", async () => {
35 const t = now();
36 const good = await sign(SECRET, t, body), bad = "0".repeat(64);
37 expect(await verify(SECRET, `t=${t},v1=${good}`, body, t)).toBe("ok");
38 expect(await verify(SECRET, `v0=abc,t=${t},v1=${bad},v1=${good}`, body, t)).toBe("ok");
39 expect(await verify(SECRET, `t=${t},v1=${bad}`, body, t)).toBe("mismatch");
40 expect(await verify(SECRET, `t=${t},v1=${good}`, body, t + 301)).toBe("stale");
41 expect(await verify(SECRET, `t=${t},v1=${good}`, body, t + 300)).toBe("ok");
42 expect(await verify(SECRET, `t=${t}`, body, t)).toBe("malformed");
43 expect(await verify(SECRET, null, body, t)).toBe("malformed");
44 expect(parseHeader("t=1,v1=zz")).toBeUndefined();
45 });
46 });
47
48 describe("the route", () => {
49 let dataDir: string, app: App, servers: Servers, alice: User;
50 const realFetch = globalThis.fetch;
51 let subscription = { status: "active", current_period_end: 2_000_000_000 };
52 let stripeCalls = 0;
53
54 beforeAll(async () => {
55 dataDir = await mkdtemp(join(tmpdir(), "forge-hook-"));
56 app = createApp({ dataDir, port: 0, url: "https://f.test" });
57 servers = await serve(app);
58 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
59 if (!a.ok) throw new Error("user");
60 alice = a.value;
61 sealKey(app.db, dataDir, "sk_test_AbCdEf1234567890");
62 sealWebhook(app.db, dataDir, SECRET);
63 globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
64 if (String(url).startsWith("https://api.stripe.com/v1/subscriptions/")) {
65 stripeCalls++;
66 return new Response(JSON.stringify(subscription), { status: 200 });
67 }
68 return realFetch(url, init);
69 }) as typeof fetch;
70 }, 30_000);
71 afterAll(async () => {
72 globalThis.fetch = realFetch;
73 servers.stop();
74 app.close();
75 await rm(dataDir, { recursive: true, force: true });
76 });
77
78 async function post(raw: string, headerFor?: (t: number, mac: string) => string, secret = SECRET, extra: Record<string, string> = {}): Promise<Response> {
79 const t = now();
80 const mac = await sign(secret, t, new TextEncoder().encode(raw));
81 return fetch(`${servers.url}/hooks/stripe`, {
82 method: "POST", body: raw,
83 headers: { "stripe-signature": headerFor ? headerFor(t, mac) : `t=${t},v1=${mac}`, ...extra },
84 });
85 }
86 const ev = (id: string, type: string, object: Record<string, unknown>) => JSON.stringify({ id, type, data: { object } });
87 const checkout = (evt: string, order: string) =>
88 ev(evt, "checkout.session.completed", { client_reference_id: order, customer: "cus_1", subscription: "sub_1" });
89
90 test("a bad signature answers 400, grants nothing, and counts toward the alarm", async () => {
91 createOrder(app.db, { id: "ord_forged", forge: "acme", plan: "large" });
92 const r = await post(checkout("evt_forged", "ord_forged"), undefined, "whsec_wrong_wrong_wrong");
93 expect(r.status).toBe(400);
94 expect(getOrder(app.db, "ord_forged")?.status).toBe("open");
95 expect(getStored(app.db, "acme")).toBeUndefined();
96 expect(hookState(app.db).refusedToday).toBe(1);
97 expect(hookState(app.db).last).toBeUndefined();
98 });
99
100 test("a stale timestamp is refused", async () => {
101 const raw = checkout("evt_stale", "ord_forged");
102 const t = now() - 301;
103 const mac = await sign(SECRET, t, new TextEncoder().encode(raw));
104 const r = await fetch(`${servers.url}/hooks/stripe`, { method: "POST", body: raw, headers: { "stripe-signature": `t=${t},v1=${mac}` } });
105 expect(r.status).toBe(400);
106 expect(getOrder(app.db, "ord_forged")?.status).toBe("open");
107 });
108
109 test("a good signature binds the order, marks it paid and writes what Stripe says; no cookie is set", async () => {
110 createOrder(app.db, { id: "ord_1", forge: "acme", plan: "large" });
111 const r = await post(checkout("evt_1", "ord_1"), undefined, SECRET, { cookie: "forge_session=x" });
112 expect(r.status).toBe(200);
113 expect(r.headers.get("set-cookie")).toBeNull();
114 expect(getOrder(app.db, "ord_1")).toMatchObject({ status: "paid", customerId: "cus_1", subscriptionId: "sub_1" });
115 await idle();
116 expect(getStored(app.db, "acme")).toMatchObject({ plan: "large", status: "active", source: "stripe", periodEnd: 2_000_000_000, subscriptionId: "sub_1" });
117 expect(hookState(app.db).last).toMatchObject({ id: "evt_1", type: "checkout.session.completed" });
118 });
119
120 test("two v1 values (a secret being rotated): either may match", async () => {
121 const r = await post(ev("evt_rot", "invoice.paid", { subscription: "sub_1" }), (t, mac) => `t=${t},v1=${"a".repeat(64)},v1=${mac}`);
122 expect(r.status).toBe(200);
123 await idle();
124 });
125
126 test("a replayed event answers 200 and does nothing", async () => {
127 const before = stripeCalls;
128 const r = await post(checkout("evt_1", "ord_1"));
129 expect(r.status).toBe(200);
130 expect(await r.json()).toMatchObject({ duplicate: true });
131 await idle();
132 expect(stripeCalls).toBe(before);
133 });
134
135 test("events out of order: the event's body is not trusted, the subscription is re-read", async () => {
136 subscription = { status: "canceled", current_period_end: 2_000_000_000 };
137 // A late "invoice.paid" arriving after the cancellation still ends with what Stripe says now.
138 await post(ev("evt_late_paid", "invoice.paid", { subscription: "sub_1", status: "paid" }));
139 await idle();
140 expect(getStored(app.db, "acme")?.status).toBe("none");
141 subscription = { status: "past_due", current_period_end: 2_000_000_000 };
142 await post(ev("evt_old_deleted", "customer.subscription.deleted", { id: "sub_1", status: "canceled" }));
143 await idle();
144 expect(getStored(app.db, "acme")?.status).toBe("grace");
145 // the new API version names the subscription under the invoice's parent
146 subscription = { status: "active", current_period_end: 2_000_000_000 };
147 await post(ev("evt_parent", "invoice.payment_failed", { parent: { subscription_details: { subscription: "sub_1" } } }));
148 await idle();
149 expect(getStored(app.db, "acme")?.status).toBe("active");
150 });
151
152 test("a body whose bytes differ from its re-serialized JSON verifies on the bytes", async () => {
153 const pretty = `{\n "id": "evt_bytes",\n "type": "invoice.paid",\n "data": { "object": { "subscription": "sub_1" } }\n}`;
154 const compact = JSON.stringify(JSON.parse(pretty));
155 expect(compact).not.toBe(pretty);
156 // signed over the compact form, sent as the pretty one: refused
157 const t = now();
158 const wrong = await sign(SECRET, t, new TextEncoder().encode(compact));
159 const refused = await fetch(`${servers.url}/hooks/stripe`, { method: "POST", body: pretty, headers: { "stripe-signature": `t=${t},v1=${wrong}` } });
160 expect(refused.status).toBe(400);
161 expect((await post(pretty)).status).toBe(200);
162 await idle();
163 });
164
165 test("a validly signed body that is not an event is refused; a body over the cap too", async () => {
166 expect((await post("not json")).status).toBe(400);
167 expect((await post(JSON.stringify({ type: "x" }))).status).toBe(400);
168 expect((await post(`{"id":"evt_big","type":"x","pad":"${"a".repeat(600 * 1024)}"}`)).status).toBe(413);
169 });
170
171 test("the sweep heals a missed webhook, and the probe shows the last event and its time", async () => {
172 putEntitlement(app.db, { forge: "acme", plan: "large", status: "none", source: "stripe" }, "large", "test");
173 subscription = { status: "active", current_period_end: 2_100_000_000 };
174 expect(await sweep(app)).toEqual({ read: 1, failed: 0 });
175 expect(getStored(app.db, "acme")).toMatchObject({ status: "active", periodEnd: 2_100_000_000 });
176 const view = readBilling(app, alice);
177 expect(view.ok && view.value.hook.last?.at).toBeGreaterThan(0);
178 expect(view.ok && view.value.hook.sweptAt).toBeGreaterThan(0);
179 });
180
181 test("an order that is not there changes nothing", async () => {
182 expect(markPaid(app.db, "ord_none", "cus_x", "sub_x")).toBe(false);
183 const r = await post(checkout("evt_noorder", "ord_none"));
184 expect(r.status).toBe(200);
185 await idle();
186 expect(getStored(app.db, "acme")?.subscriptionId).toBe("sub_1");
187 });
188
189 test("no GET, and rate limited", async () => {
190 expect((await fetch(`${servers.url}/hooks/stripe`)).status).not.toBe(200);
191 let last = 0;
192 for (let i = 0; i < 70; i++) last = (await fetch(`${servers.url}/hooks/stripe`, { method: "POST", body: "x" })).status;
193 expect(last).toBe(429);
194 });
195 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs