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

Each Stripe invoice the webhook verifies is kept as one payment row: amount, currency, status, when #13095

Merged opened this

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

Merged

torque/forge:torque/13092-each-stripe-invoice-the-webhook-verifies → main 9 commits fork 4 threads · 4 unresolved

  • Merged. torque/13092-each-stripe-invoice-the-webhook-verifies was merged into main as 3dfc394.

Review

Sign in to review this change.
13 files changed +370 −17
docs/features/billing.md +9
@@ -15,3 +15,12 @@ A code gives a plan for free, with or without a payment provider (`src/billing/c
1515 - **List / revoke:** the same page (one row per code: plan and note, used of limit, who redeemed, and one *Stop this code working* button), `GET /api/v1/codes`, `DELETE /api/v1/codes/{id}`, MCP `codes: true` / `revoke: <id>`. Revoking stops new uses; forges already made keep their plan.
1616 - **Redeem:** the link moves the code into an HttpOnly cookie and opens `/forges/new` (no code in the address, the log or the history) with the code filled in ("A gift: a medium forge, free."; the admin is not named). Without a code the field sits behind a "Have a code?" disclosure; `POST /api/v1/forges` and the MCP `spawn` take `code`. A wrong, used-up, expired or revoked code is said on the same form. A client may try 10 codes in 10 minutes.
1717 - **Audit:** `billing.code.make`, `billing.code.redeem`, `billing.code.revoke` events.
18
19 ## Payments kept
20 Each invoice the verified Stripe webhook tells of is one `payment` row (`src/billing/payments.ts`, #13092): the invoice id, customer, amount in Stripe's integer minor units and its currency, both as sent, status `paid`, `failed` or `refunded`, and when.
21
22 - **Events:** `invoice.paid`, `invoice.payment_failed`, `charge.refunded`. A malformed one answers 200 and is audited as `billing.payment_refused`.
23 - **Order:** Stripe does not promise it. An event older than the row's own changes nothing, so a late `payment_failed` cannot undo `paid`.
24 - **Refunds:** only a charge refunded in full marks the invoice `refunded`; a partial refund leaves it. A refund seen before its invoice is kept and applied when the row arrives. A refunded row stays refunded. A charge not tied to an invoice changes nothing and is not audited.
25 - **Retries:** the row is written in the same transaction as the event id; if the write fails the id is not kept and Stripe retries.
26 - **Where to see it:** Settings → Billing, "Payments kept" (count and refunded); the terminal's Billing screen shows the newest payment on each forge's line.
src/billing/payments.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * One payment row per Stripe invoice (#13092). Plain data in, plain data out.
3 * Amounts are Stripe's integer minor units (cents for usd) and the currency
4 * is Stripe's lowercase ISO 4217 code, both stored exactly as sent; nothing
5 * here converts or recomputes money.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { subscriptionIdOf } from "./subscription.ts";
10
11 export type PaymentStatus = "paid" | "failed" | "refunded";
12
13 export interface Payment {
14 readonly id: string;
15 readonly subscriptionId: string | undefined;
16 readonly customerId: string;
17 readonly amountMinor: number;
18 readonly currency: string;
19 readonly status: PaymentStatus;
20 readonly at: string;
21 }
22
23 /** What a verified event asks the store to do: write an invoice's row, or mark one refunded. */
24 export type PaymentChange = { kind: "upsert"; payment: Payment } | { kind: "refund"; invoice: string };
25
26 const INVOICE = /^in_[A-Za-z0-9_]{1,200}$/;
27 const CUSTOMER = /^cus_[A-Za-z0-9_]{1,200}$/;
28 const CURRENCY = /^[a-z]{3}$/;
29
30 const idOf = (v: unknown): string | undefined =>
31 typeof v === "string" ? v : typeof v === "object" && v !== null && typeof (v as { id?: unknown }).id === "string" ? (v as { id: string }).id : undefined;
32
33 /**
34 * Read an event for its payment change. undefined when the event is not a
35 * payment event; the string "malformed" when it is one but a field is missing
36 * or not what Stripe documents (a non-integer or negative amount, a bad id).
37 */
38 export function paymentChangeOf(event: unknown, now: Date): PaymentChange | "malformed" | undefined {
39 const e = event as { type?: unknown; created?: unknown; data?: { object?: unknown } } | null;
40 const type = e?.type;
41 if (type !== "invoice.paid" && type !== "invoice.payment_failed" && type !== "charge.refunded") return undefined;
42 const o = e?.data?.object;
43 if (o === null || typeof o !== "object") return "malformed";
44 const obj = o as Record<string, unknown>;
45 if (type === "charge.refunded") {
46 // A charge not tied to an invoice (no `invoice`, or null) has no payment row: nothing to do.
47 if (obj["invoice"] === undefined || obj["invoice"] === null) return undefined;
outdated

charge.refunded also fires for partial refunds. Mark refunded only when obj.refunded === true (or amount_refunded === amount); otherwise leave status. Add a test for a partial refund.

48 const invoice = idOf(obj["invoice"]);
49 if (invoice === undefined || !INVOICE.test(invoice)) return "malformed";
50 // charge.refunded also fires for a partial refund: only a charge refunded in full is refunded.
51 const full = obj["refunded"] === true || (typeof obj["amount"] === "number" && obj["amount_refunded"] === obj["amount"]);
52 return full ? { kind: "refund", invoice } : undefined;
53 }
54 const id = obj["id"];
55 const customer = idOf(obj["customer"]);
56 const amount = type === "invoice.paid" ? obj["amount_paid"] : obj["amount_due"];
57 const currency = obj["currency"];
58 if (typeof id !== "string" || !INVOICE.test(id)) return "malformed";
59 if (customer === undefined || !CUSTOMER.test(customer)) return "malformed";
60 if (typeof amount !== "number" || !Number.isSafeInteger(amount) || amount < 0) return "malformed";
61 if (typeof currency !== "string" || !CURRENCY.test(currency)) return "malformed";
62 const created = e?.created;
63 if (created !== undefined && (typeof created !== "number" || !Number.isSafeInteger(created) || created < 0)) return "malformed";
64 const subscription = subscriptionIdOf(event);
65 return {
66 kind: "upsert",
67 payment: {
68 id, subscriptionId: subscription, customerId: customer, amountMinor: amount, currency,
69 status: type === "invoice.paid" ? "paid" : "failed",
70 at: (created === undefined ? now : new Date(created * 1000)).toISOString(),
71 },
72 };
73 }
74
75 /**
76 * Apply a change. A refunded row stays refunded when a late paid or failed event arrives, and an
77 * event older than the row's own (Stripe does not promise order) changes nothing. A refund whose
78 * invoice has no row yet is kept and applied when the row arrives.
79 */
80 export function recordPayment(db: Database, change: PaymentChange): void {
81 if (change.kind === "refund") {
82 const done = db.query("UPDATE payment SET status = 'refunded' WHERE id = ?1").run(change.invoice);
outdated

Any later-delivered event overwrites the row, including an older one. Stripe does not guarantee order, so a stale payment_failed can replace paid. Only update when excluded.at >= payment.at, and add a test.

83 if (done.changes === 0) db.query("INSERT OR IGNORE INTO payment_refund (invoice) VALUES (?1)").run(change.invoice);
84 return;
85 }
86 const p = change.payment;
87 const owed = db.query("SELECT 1 FROM payment_refund WHERE invoice = ?1").get(p.id) !== null;
88 db.query(
89 `INSERT INTO payment (id, subscription_id, customer_id, amount_minor, currency, status, at)
90 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
91 ON CONFLICT (id) DO UPDATE SET subscription_id = excluded.subscription_id, customer_id = excluded.customer_id,
92 amount_minor = excluded.amount_minor, currency = excluded.currency, status = excluded.status, at = excluded.at
93 WHERE payment.status <> 'refunded' AND excluded.at >= payment.at`,
94 ).run(p.id, p.subscriptionId ?? null, p.customerId, p.amountMinor, p.currency, owed ? "refunded" : p.status, p.at);
95 if (owed) db.query("DELETE FROM payment_refund WHERE invoice = ?1").run(p.id);
96 }
97
98 interface Row {
99 id: string; subscription_id: string | null; customer_id: string; amount_minor: number; currency: string; status: PaymentStatus; at: string;
100 }
101
102 /** One customer's payments, newest first. */
103 export function listPayments(db: Database, customerId: string, limit = 100): Payment[] {
104 return db
105 .query<Row, [string, number]>("SELECT * FROM payment WHERE customer_id = ?1 ORDER BY at DESC, id DESC LIMIT ?2")
106 .all(customerId, Math.max(1, Math.min(500, Math.floor(limit))))
107 .map((r) => ({ id: r.id, subscriptionId: r.subscription_id ?? undefined, customerId: r.customer_id, amountMinor: r.amount_minor, currency: r.currency, status: r.status, at: r.at }));
108 }
src/billing/stripe.ts +8 −3
@@ -25,6 +25,7 @@ export const WEBHOOK_EVENTS = [
2525 "customer.subscription.deleted",
2626 "invoice.paid",
2727 "invoice.payment_failed",
28 "charge.refunded",
2829 ] as const;
2930
3031 /** What the forge declares for itself: the only vendor its own process calls. */
@@ -72,7 +73,9 @@ export interface CheckoutRequest {
7273 readonly email: string;
7374 readonly successUrl: string;
7475 readonly cancelUrl: string;
75 /** Unix seconds after which the checkout cannot be paid (Stripe: 30 minutes to 24 hours from now). */
76 /**
77 * Unix seconds after which the checkout cannot be paid (Stripe: 30 minutes to 24 hours from now).
78 */
7679 readonly expiresAt?: number;
7780 }
7881
@@ -171,7 +174,8 @@ export function stripeClient(key: string, fetchFn: typeof fetch = fetch): Stripe
171174 },
172175 async addWebhook(url) {
173176 const r = await call("POST", "/v1/webhook_endpoints", { url, enabled_events: [...WEBHOOK_EVENTS] },
174 // fresh per attempt: Stripe replays an answer for a repeated key for 24h, and a reconnect must not get a deleted endpoint back
177 // fresh per attempt: Stripe replays an answer for a repeated key for 24h, and a reconnect
178 // must not get a deleted endpoint back
175179 crypto.randomUUID());
176180 if (!r.ok) return r;
177181 const id = str(r.value, "id"), secret = str(r.value, "secret");
@@ -187,7 +191,8 @@ export function stripeClient(key: string, fetchFn: typeof fetch = fetch): Stripe
187191 const v = r.value;
188192 if (str(v, "id") === "" || str(v, "status") === "") return err(missing("subscription"));
189193 const customer = typeof v["customer"] === "object" && v["customer"] !== null ? str(v["customer"] as Record<string, unknown>, "id") : str(v, "customer");
190 // the period end is on the subscription in older API versions and on its first item in newer ones
194 // the period end is on the subscription in older API versions and on its first item in newer
195 // ones
191196 const item = ((v["items"] as { data?: unknown } | undefined)?.data as Record<string, unknown>[] | undefined)?.[0];
192197 const end = [v["current_period_end"], item?.["current_period_end"]].find((n) => typeof n === "number") as number | undefined;
193198 const metadata: Record<string, string> = {};
src/core/migration-pins/20261115110000-payments.pin added +1
@@ -0,0 +1,1 @@
1 23fb41b930811c9110b25ba774b108c56850360b0fc00870a3527a0bb5fbf845
src/core/migration-pins/20261115120000-payment-refund-pending.pin added +1
@@ -0,0 +1,1 @@
1 844556ca009da77f6ffe4046db3ab9261a053aef2038f049a7ed66fd4251477f
src/core/migrations/20261115110000-payments.ts added +16
@@ -0,0 +1,16 @@
1 // One row per Stripe invoice the verified webhook told us of (#13092):
2 // amount in integer minor units and currency exactly as Stripe sent them,
3 // never recomputed. id is the Stripe invoice id, so a redelivery or a later
4 // event for the same invoice updates the one row. Additive. Undone with DROP TABLE.
5 export default `
6 CREATE TABLE IF NOT EXISTS payment (
7 id TEXT PRIMARY KEY,
8 subscription_id TEXT,
9 customer_id TEXT NOT NULL,
10 amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
11 currency TEXT NOT NULL,
12 status TEXT NOT NULL CHECK (status IN ('paid', 'failed', 'refunded')),
13 at TEXT NOT NULL
14 );
15 CREATE INDEX IF NOT EXISTS payment_customer ON payment(customer_id, at DESC);
16 `;
src/core/migrations/20261115120000-payment-refund-pending.ts added +5
@@ -0,0 +1,5 @@
1 // A refund seen before its invoice's row (#13092): kept by invoice id and applied when the row
2 // arrives, then deleted. Additive. Undone with DROP TABLE.
3 export default `
4 CREATE TABLE IF NOT EXISTS payment_refund (invoice TEXT PRIMARY KEY);
5 `;
src/http/stripe_hook.ts +29 −6
@@ -16,6 +16,7 @@ import type { App } from "../app.ts";
1616 import { settleSession } from "../actions/order.ts";
1717 import { bindCheckout } from "../billing/checkout_completed.ts";
1818 import { openWebhookSecret } from "../billing/connection.ts";
19 import { paymentChangeOf, recordPayment } from "../billing/payments.ts";
1920 import { syncSubscription } from "../billing/sync.ts";
2021 import { subscriptionIdOf } from "../billing/subscription.ts";
2122 import { verifyStripeSignature } from "../billing/signature.ts";
@@ -56,7 +57,10 @@ export function setStripeHookCaps(app: App, perClient: number, wholeForge: numbe
5657 const answer = (status: number, headers?: Record<string, string>, body: string | null = null): Response =>
5758 new Response(body, { status, headers: { "cache-control": "no-store", ...headers } });
5859
59 /** What a redelivered event id is told: a 200, so Stripe stops, and these words, so a person reading the log knows. */
60 /**
61 * What a redelivered event id is told: a 200, so Stripe stops, and these words, so a person reading
62 * the log knows.
63 */
6064 export const ALREADY_HANDLED = "already handled";
6165
6266 /** Bad and stale signatures refused today and earlier, by kind. */
@@ -66,12 +70,21 @@ export function refusedCount(app: App, kind: "bad" | "stale"): number {
6670 );
6771 }
6872
69 /** The newest event kept, and the signatures refused on this UTC day: what the admin Billing page says. */
70 export function hookSummary(app: App, now = new Date()): { last: { type: string; at: string } | undefined; refusedToday: number } {
73 /**
74 * The newest event kept, and the signatures refused on this UTC day: what the admin Billing page
75 * says.
76 */
77 export function hookSummary(
78 app: App,
79 now = new Date(),
80 ): { last: { type: string; at: string } | undefined; refusedToday: number; payments: number; refunded: number } {
7181 const last = app.db.query<{ type: string; at: string }, []>("SELECT type, at FROM stripe_event ORDER BY at DESC LIMIT 1").get() ?? undefined;
7282 const refusedToday =
7383 app.db.query<{ n: number }, [string]>("SELECT COALESCE(SUM(n), 0) AS n FROM stripe_hook_refused WHERE day = ?1").get(now.toISOString().slice(0, 10))?.n ?? 0;
74 return { last, refusedToday };
84 const pay = app.db
85 .query<{ n: number; r: number }, []>("SELECT COUNT(*) AS n, COALESCE(SUM(status = 'refunded'), 0) AS r FROM payment")
86 .get();
87 return { last, refusedToday, payments: pay?.n ?? 0, refunded: pay?.r ?? 0 };
7588 }
7689
7790 function countRefused(app: App, kind: "bad" | "stale", now: Date): void {
@@ -117,13 +130,23 @@ export async function stripeHook(ctx: Ctx): Promise<Response> {
117130 if (e === null || typeof e !== "object" || typeof e.id !== "string" || !EVENT_ID.test(e.id)) return answer(400);
118131 const type = typeof e.type === "string" && EVENT_TYPE.test(e.type) ? e.type : "unknown";
119132 // A repeated id changes nothing: the primary key refuses it.
120 // One transaction: if binding throws, the id is not kept, so Stripe's retry is not taken for a replay.
133 // One transaction: if binding throws, the id is not kept, so Stripe's retry is not taken for a
134 // replay. A payment is written in the same transaction as the event id, so a row that cannot
135 // be written rolls the id back and Stripe retries. A malformed one is audited after and answered
136 // 200: a retry would not mend it.
137 const change = paymentChangeOf(event, now);
138 const paymentFailure: string | undefined = change === "malformed" ? "malformed" : undefined;
121139 const fresh = app.db.transaction(() => {
122140 const stored = app.db.query("INSERT OR IGNORE INTO stripe_event (id, type, at) VALUES (?1, ?2, ?3)").run(e.id as string, type, now.toISOString());
123141 if (stored.changes === 1 && type === "checkout.session.completed") bindCheckout(app, event);
142 if (stored.changes === 1 && change !== undefined && change !== "malformed") {
143 recordPayment(app.db, change);
144 }
outdated

Swallowing the write error while keeping the stripe_event id means Stripe is told 200 and the payment is never recorded. Let the error roll back the transaction so Stripe retries, as the comment above says for bindCheckout; the issue asks for the same transaction.

124145 return stored.changes === 1;
125146 })();
126 // A paid checkout that is one of our orders makes its forge (once, whoever sees the payment first), then binds it to the customer.
147 if (fresh && paymentFailure !== undefined) app.bus.append({ kind: "billing.payment_refused", payload: { event: e.id, type, reason: paymentFailure } });
148 // A paid checkout that is one of our orders makes its forge (once, whoever sees the payment
149 // first), then binds it to the customer.
127150 if (fresh && type === "checkout.session.completed") {
128151 const session = (event as { data?: { object?: unknown } }).data?.object;
129152 if (session !== null && typeof session === "object") {
src/tui/screens/billing.ts +10 −2
@@ -9,6 +9,8 @@
99
1010 import { grantPlan, readBilling, connectStripe, disconnectStripe, saveSigningSecret, BILLING_WORDS, STRIPE_WORDS } from "../../actions/billing.ts";
1111 import type { Ctx, Screen } from "../app/app.ts";
12 import { getStored } from "../../billing/store.ts";
13 import { listPayments } from "../../billing/payments.ts";
1214 import { binding } from "../app/keys.ts";
1315 import { fill, len, split } from "../ui/layout.ts";
1416 import { style } from "../term/style.ts";
@@ -26,7 +28,13 @@ const PLANS: Record<string, string> = { s: "small", m: "medium", l: "large" };
2628 export function billingRows(f: Session): ListRow[] {
2729 const read = readBilling(f.app, f.user);
2830 if (!read.ok) return [];
29 return read.value.forges.map((e) => ({ title: e.forge, secondary: e.plan, meta: `${e.status} · ${e.source}` }));
31 // The newest payment kept for the forge's Stripe customer: Stripe's minor units and currency, as
32 // sent.
33 const lastPayment = (customer: string): string => {

Untested behaviour: the last-payment text in the terminal row. Add a test through billingRows that fails without this line.

34 const p = customer === "" ? undefined : listPayments(f.app.db, customer, 1)[0];
35 return p === undefined ? "" : ` · last payment ${p.status} ${p.amountMinor} ${p.currency} (minor units)`;
36 };
37 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 ?? "")}` }));
3038 }
3139
3240 export function billingScreen(f: Session, ctx: Ctx): Screen {
@@ -42,7 +50,7 @@ export function billingScreen(f: Session, ctx: Ctx): Screen {
4250 const sc = readBilling(f.app, f.user);
4351 const stripe = sc.ok && sc.value.stripe ? `Stripe ${sc.value.stripe.mode}, ${sc.value.stripe.signed ? "signed" : "no signing secret"}` : "Stripe not connected";
4452 const ev = sc.ok ? sc.value.events : undefined;
45 const events = ev === undefined ? "" : `Last event: ${ev.last === undefined ? "No event yet" : `${ev.last.type} ${ev.last.at.slice(0, 16).replace("T", " ")} UTC`}. Refused today: ${ev.refusedToday}`;
53 const events = ev === undefined ? "" : `Last event: ${ev.last === undefined ? "No event yet" : `${ev.last.type} ${ev.last.at.slice(0, 16).replace("T", " ")} UTC`}. Refused today: ${ev.refusedToday}. Payments kept: ${ev.payments} (${ev.refunded} refunded)`;
4654 if (rows.length === 0) {
4755 emptyState(s, area, c, { title: "No forge has been sent from here.", body: note === "" ? `Billing has nothing to grant yet. ${stripe}. ${events}.` : note });
4856 return;
src/web/pages/billing.ts +7 −2
@@ -151,7 +151,10 @@ export async function billingSetLinks(ctx: Ctx): Promise<Response> {
151151 return billingView(ctx, undefined, {}, undefined, 422, { values: next, error });
152152 }
153153
154 /** Last 7 days, from visit to paid: one `dl` row per step with its share of the step before; clicks by plan and where they came from as rows under it. */
154 /**
155 * Last 7 days, from visit to paid: one `dl` row per step with its share of the step before; clicks
156 * by plan and where they came from as rows under it.
157 */
155158 function funnelRow(r: FunnelReport): Html {
156159 const row = (label: string, value: string): Html => html`<div class="status-row"><dt>${label}</dt><dd>${value}</dd></div>`;
157160 return html`<section class="settings-block" id="funnel">
@@ -202,6 +205,7 @@ function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {
202205 const hookRows = html`<dl class="status-rows" data-stripe-events>
203206 <div class="status-row"><dt>Last event</dt><dd>${hook.last === undefined ? "No event yet" : html`<span class="mono">${hook.last.type}</span> <time datetime="${hook.last.at}">${hook.last.at.slice(0, 16).replace("T", " ")} UTC</time>`}</dd></div>
204207 <div class="status-row"><dt>Refused today</dt><dd>${hook.refusedToday}</dd></div>
208 <div class="status-row"><dt>Payments kept</dt><dd>${hook.payments} (${hook.refunded} refunded)</dd></div>
205209 </dl>`;
206210 const stripe = html`<section class="settings-block">
207211 <h2>Provider</h2>
@@ -325,7 +329,8 @@ export async function stripeDisconnect(ctx: Ctx): Promise<Response> {
325329 return back(ctx, r.ok ? { ok: true, message: "Stripe is disconnected." } : r);
326330 }
327331
328 // POST /settings/billing/orders/retry — an admin who is a person retries a paid order whose forge was not made.
332 // POST /settings/billing/orders/retry — an admin who is a person retries a paid order whose forge
333 // was not made.
329334 export async function orderRetry(ctx: Ctx): Promise<Response> {
330335 if (!isPerson(ctx)) return notFoundPage(ctx);
331336 const form = await readForm(ctx, "admin");
test/billing-payments.test.ts added +151
@@ -0,0 +1,151 @@
1 // A verified invoice event is one payment row; charge.refunded marks it refunded (#13092).
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { sealKey, sealWebhook } from "../src/billing/connection.ts";
8 import { listPayments, paymentChangeOf, recordPayment } from "../src/billing/payments.ts";
9 import { WEBHOOK_EVENTS } from "../src/billing/stripe.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { hookSummary, setStripeHookCaps } from "../src/http/stripe_hook.ts";
12 import { setStripeFetch } from "../src/billing/sync.ts";
13
14 const secret = "whsec_payments_test";
15 let dir: string, app: App, servers: Servers, base: string;
16
17 beforeAll(async () => {
18 dir = await mkdtemp(join(tmpdir(), "payments-"));
19 app = createApp({ dataDir: dir, port: 0 });
20 servers = await serve(app);
21 base = `http://127.0.0.1:${servers.port}`;
22 sealKey(app.db, dir, "sk_test_abcdefgh12345678");
23 sealWebhook(app.db, dir, secret);
24 setStripeHookCaps(app, 100000, 100000);
25 setStripeFetch(app, (async () => new Response("{}", { status: 500 })) as unknown as typeof fetch);
26 });
27 afterAll(async () => {
28 await servers.stop();
29 await rm(dir, { recursive: true, force: true });
30 });
31
32 async function sign(body: string): Promise<string> {
33 const t = Math.floor(Date.now() / 1000);
34 const k = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
35 const mac = new Uint8Array(await crypto.subtle.sign("HMAC", k, new TextEncoder().encode(`${t}.${body}`)));
36 return `t=${t},v1=${Buffer.from(mac).toString("hex")}`;
37 }
38 let n = 0;
39 async function send(event: unknown): Promise<Response> {
40 const body = JSON.stringify(event);
41 return fetch(`${base}/hooks/stripe`, { method: "POST", headers: { "stripe-signature": await sign(body), "x-forwarded-for": `10.9.0.${++n % 250}` }, body });
42 }
43 const invoice = (over: Record<string, unknown> = {}) => ({
44 id: "in_1", customer: "cus_1", subscription: "sub_1", amount_paid: 1999, amount_due: 1999, currency: "usd", ...over,
45 });
46 const evt = (id: string, type: string, object: unknown, created = 1_700_000_000) => ({ id, type, created, data: { object } });
47 const rows = (c = "cus_1") => listPayments(app.db, c);
48
49 describe("payments from the webhook", () => {
50 test("charge.refunded is an accepted event", () => {
51 expect(WEBHOOK_EVENTS).toContain("charge.refunded");
52 });
53
54 test("invoice.paid writes one row in integer minor units as sent", async () => {
55 expect((await send(evt("evt_p1", "invoice.paid", invoice()))).status).toBe(200);
56 expect(rows()).toEqual([{ id: "in_1", subscriptionId: "sub_1", customerId: "cus_1", amountMinor: 1999, currency: "usd", status: "paid", at: "2023-11-14T22:13:20.000Z" }]);
57 });
58
59 test("a replayed event id changes nothing", async () => {
60 app.db.query("UPDATE payment SET amount_minor = 5 WHERE id = 'in_1'").run();
61 expect((await send(evt("evt_p1", "invoice.paid", invoice()))).status).toBe(200);
62 expect(rows()[0]?.amountMinor).toBe(5);
63 app.db.query("UPDATE payment SET amount_minor = 1999 WHERE id = 'in_1'").run();
64 });
65
66 test("invoice.payment_failed on a new invoice is a failed row; a later paid event updates the same row", async () => {
67 await send(evt("evt_f1", "invoice.payment_failed", invoice({ id: "in_2", amount_due: 500, currency: "eur" }), 1_700_000_100));
68 expect(rows().map((r) => [r.id, r.status, r.amountMinor, r.currency])).toEqual([["in_2", "failed", 500, "eur"], ["in_1", "paid", 1999, "usd"]]);
69 await send(evt("evt_f2", "invoice.paid", invoice({ id: "in_2", amount_paid: 500, currency: "eur" }), 1_700_000_200));
70 expect(rows().filter((r) => r.id === "in_2")).toHaveLength(1);
71 expect(rows()[0]).toMatchObject({ id: "in_2", status: "paid" });
72 });
73
74 test("charge.refunded marks the matching invoice refunded, and a late paid event does not undo it", async () => {
75 expect((await send(evt("evt_r1", "charge.refunded", { id: "ch_1", invoice: "in_1", amount: 1999, amount_refunded: 1999, refunded: true }))).status).toBe(200);
76 expect(rows().find((r) => r.id === "in_1")?.status).toBe("refunded");
77 await send(evt("evt_r2", "invoice.paid", invoice()));
78 expect(rows().find((r) => r.id === "in_1")?.status).toBe("refunded");
79 });
80
81 test("a partial refund leaves the invoice's status; a full one marks it refunded", async () => {
82 await send(evt("evt_pp0", "invoice.paid", invoice({ id: "in_part", customer: "cus_part" })));
83 await send(evt("evt_pp1", "charge.refunded", { id: "ch_p", invoice: "in_part", amount: 1999, amount_refunded: 500, refunded: false }));
84 expect(rows("cus_part")[0]?.status).toBe("paid");
85 await send(evt("evt_pp2", "charge.refunded", { id: "ch_p", invoice: "in_part", amount: 1999, amount_refunded: 1999, refunded: true }));
86 expect(rows("cus_part")[0]?.status).toBe("refunded");
87 });
88
89 test("an older event delivered late does not overwrite a newer one", async () => {
90 await send(evt("evt_o_paid", "invoice.paid", invoice({ id: "in_ooo", customer: "cus_ooo" }), 1_700_000_500));
91 await send(evt("evt_o_fail", "invoice.payment_failed", invoice({ id: "in_ooo", customer: "cus_ooo" }), 1_700_000_100));
92 expect(rows("cus_ooo")).toMatchObject([{ status: "paid", at: new Date(1_700_000_500_000).toISOString() }]);
93 });
94
95 test("a refund before its invoice is kept and applied when the row arrives", async () => {
96 await send(evt("evt_early", "charge.refunded", { id: "ch_e", invoice: "in_early", amount: 700, amount_refunded: 700, refunded: true }));
97 expect(rows("cus_early")).toEqual([]);
98 await send(evt("evt_early_paid", "invoice.paid", invoice({ id: "in_early", customer: "cus_early", amount_paid: 700 })));
99 expect(rows("cus_early")).toMatchObject([{ id: "in_early", status: "refunded", amountMinor: 700 }]);
100 expect(app.db.query("SELECT COUNT(*) AS n FROM payment_refund").get()).toEqual({ n: 0 });
101 });
102
103 test("a row that cannot be written is not kept as handled: the answer is an error and the retry lands", async () => {
104 app.db.exec("ALTER TABLE payment RENAME TO payment_away");
105 let res: Response;
106 try {
107 res = await send(evt("evt_w1", "invoice.paid", invoice({ id: "in_w", customer: "cus_w" })));
108 } finally {
109 app.db.exec("ALTER TABLE payment_away RENAME TO payment");
110 }
111 expect(res.status).toBeGreaterThanOrEqual(500);
112 expect(app.db.query("SELECT COUNT(*) AS n FROM stripe_event WHERE id = 'evt_w1'").get()).toEqual({ n: 0 });
113 expect((await send(evt("evt_w1", "invoice.paid", invoice({ id: "in_w", customer: "cus_w" })))).status).toBe(200);
114 expect(rows("cus_w")).toHaveLength(1);
115 });
116
117 test("a malformed amount answers 200, leaves no row, and is audited", async () => {
118 for (const [i, amount] of [12.5, "1999", -1, null].entries()) {
119 expect((await send(evt(`evt_m${i}`, "invoice.paid", invoice({ id: `in_bad${i}`, customer: "cus_bad", amount_paid: amount })))).status).toBe(200);
120 }
121 expect(rows("cus_bad")).toEqual([]);
122 expect(app.db.query("SELECT COUNT(*) AS n FROM payment WHERE id LIKE 'in_bad%'").get()).toEqual({ n: 0 });
123 });
124
125 test("lists only one customer's rows", async () => {
126 await send(evt("evt_o1", "invoice.paid", invoice({ id: "in_other", customer: "cus_2" })));
127 expect(rows("cus_2").map((r) => r.id)).toEqual(["in_other"]);
128 expect(rows().map((r) => r.id)).not.toContain("in_other");
129 });
130 });
131
132 test("the admin summary counts payments kept and refunded", () => {
133 const before = hookSummary(app);
134 const p = { id: "in_s1", subscriptionId: undefined, customerId: "cus_s", amountMinor: 500, currency: "usd", status: "paid" as const, at: "2026-01-01T00:00:00.000Z" };
135 recordPayment(app.db, { kind: "upsert", payment: p });
136 recordPayment(app.db, { kind: "upsert", payment: { ...p, id: "in_s2" } });
137 recordPayment(app.db, { kind: "refund", invoice: "in_s2" });
138 const s = hookSummary(app);
139 expect([s.payments - before.payments, s.refunded - before.refunded]).toEqual([2, 1]);
140 });
141
142 test("a refunded charge with no invoice is not a payment event; a bad invoice id is malformed", () => {
143 const now = new Date(0);
144 const charge = (o: Record<string, unknown>) => evt("evt_c", "charge.refunded", { id: "ch_x", amount: 100, amount_refunded: 40, refunded: false, ...o });
145 expect(paymentChangeOf(charge({}), now)).toBeUndefined();
146 expect(paymentChangeOf(charge({ invoice: null }), now)).toBeUndefined();
147 expect(paymentChangeOf(charge({ invoice: null, amount_refunded: 100, refunded: true }), now)).toBeUndefined();
148 expect(paymentChangeOf(charge({ invoice: "nope" }), now)).toBe("malformed");
149 expect(paymentChangeOf(charge({ invoice: "in_ok" }), now)).toBeUndefined();
150 expect(paymentChangeOf(charge({ invoice: "in_ok", refunded: true }), now)).toEqual({ kind: "refund", invoice: "in_ok" });
151 });
test/billing-tui.test.ts +24 −3
@@ -1,4 +1,7 @@
1 /** Billing in the terminal (#11134): the admin sees each forge's plan and grants one; no one else is offered it. */
1 /**
2 * Billing in the terminal (#11134): the admin sees each forge's plan and grants one; no one else is
3 * offered it.
4 */
25 import { afterAll, beforeAll, expect, test } from "bun:test";
36 import { mkdtemp, rm } from "node:fs/promises";
47 import { tmpdir } from "node:os";
@@ -7,14 +10,15 @@ import { createApp, type App } from "../src/app.ts";
710 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
811 import { connectStripe } from "../src/actions/billing.ts";
912 import { connectionOf } from "../src/billing/connection.ts";
10 import { entitlementOf } from "../src/billing/store.ts";
13 import { entitlementOf, getStored, putEntitlement } from "../src/billing/store.ts";
14 import { recordPayment } from "../src/billing/payments.ts";
1115 import { createUser, type User } from "../src/core/users.ts";
1216 import { ok } from "../src/kernel/result.ts";
1317 import { serve, type Servers } from "../src/http/server.ts";
1418 import { usePlacement, useProbe } from "../src/spawn/door.ts";
1519 import { bootHostedChild } from "../src/spawn/host.ts";
1620 import { createForgeApp } from "../src/tui/forge.ts";
17 import { billingScreen, entry } from "../src/tui/screens/billing.ts";
21 import { billingRows, billingScreen, entry } from "../src/tui/screens/billing.ts";
1822 import { headlessTerminal } from "../src/tui/term/terminal.ts";
1923 import { quietLogs } from "./helpers/globals.ts";
2024 import { settleApp } from "./helpers/tui.ts";
@@ -176,3 +180,20 @@ test("the terminal Billing screen shows the last Stripe event and refusals to an
176180 expect(bobs.tui.screen.toText()).not.toContain("Refused today");
177181 bobs.tui.stop?.();
178182 });
183
184 test("a forge's row shows its customer's newest payment in minor units, and nothing without a customer or a payment", () => {
185 const { session } = open(alice);
186 const kid = () => billingRows(session).find((r) => r.title === "kid")!.meta ?? "";
187 const pay = { subscriptionId: undefined, customerId: "cus_tui", currency: "usd", status: "paid" as const };
188 recordPayment(app.db, { kind: "upsert", payment: { ...pay, id: "in_tui0", amountMinor: 1, at: "2026-01-01T00:00:00.000Z" } });
189 expect(getStored(app.db, "kid")?.customerId ?? "").toBe("");
190 expect(kid()).not.toContain("last payment");
191 const s = getStored(app.db, "kid")!;
192 putEntitlement(app.db, { forge: "kid", plan: s.plan, status: s.status, source: s.source, customerId: "cus_tui2" }, "small", alice.id);
193 expect(kid()).not.toContain("last payment");
194 putEntitlement(app.db, { forge: "kid", plan: s.plan, status: s.status, source: s.source, customerId: "cus_tui" }, "small", alice.id);
195 recordPayment(app.db, { kind: "upsert", payment: { ...pay, id: "in_tui1", amountMinor: 1999, at: "2026-02-01T00:00:00.000Z" } });
196 expect(kid()).toContain("last payment paid 1999 usd (minor units)");
197 recordPayment(app.db, { kind: "refund", invoice: "in_tui1" });
198 expect(kid()).toContain("last payment refunded 1999 usd (minor units)");
199 });
test/stripe.test.ts +1 −1
@@ -43,7 +43,7 @@ describe("stripe client", () => {
4343 expect(c.url).toBe("https://api.stripe.com/v1/webhook_endpoints");
4444 expect(c.headers).toMatchObject({ authorization: `Bearer ${KEY}`, "stripe-version": STRIPE_VERSION, "content-type": "application/x-www-form-urlencoded" });
4545 expect(decodeURIComponent(c.body)).toBe(
46 "url=https://f.test/hooks/stripe&enabled_events[0]=checkout.session.completed&enabled_events[1]=customer.subscription.updated&enabled_events[2]=customer.subscription.deleted&enabled_events[3]=invoice.paid&enabled_events[4]=invoice.payment_failed",
46 "url=https://f.test/hooks/stripe&enabled_events[0]=checkout.session.completed&enabled_events[1]=customer.subscription.updated&enabled_events[2]=customer.subscription.deleted&enabled_events[3]=invoice.paid&enabled_events[4]=invoice.payment_failed&enabled_events[5]=charge.refunded",
4747 );
4848 expect(calls[0]!.headers["idempotency-key"]).toBeTruthy();
4949 expect(calls[1]!.headers["idempotency-key"]).not.toBe(calls[0]!.headers["idempotency-key"]);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs