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

An order's receipt page lists the plan, the amount, the date and the forge it paid for, and downloads as printable HTML #16075

Merged opened this

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

Merged

torque/forge:torque/16046-an-order-s-receipt-page-lists-the-plan-t → main 0 commits fork 5 threads · 5 unresolved

  • Merged. torque/16046-an-order-s-receipt-page-lists-the-plan-t was merged into main as 7cd5710.

Review

Sign in to review this change.
16 files changed +353 −16
docs/features/pricing.md +1
@@ -12,6 +12,7 @@ Open `/pricing` with no account. Each plan shows its size, price, monthly crew c
1212 - **Operator:** connect Stripe under Settings → Billing. A paid order whose forge could not be made shows under "Paid, not made" with Retry and a link to the provider's dashboard to refund; a flow alarm names it.
1313 - **Limits:** one client address may have 3 orders waiting at once (counted by socket address, never a header); a name is held 35 minutes and the provider's checkout stops being payable at 31, so a late payer never finds the name given away; a claim link is mailed again at most once a day per order.
1414 - **Terminal:** palette → "Get a forge (plans)" (`src/tui/screens/pricing.ts`): up/down picks a paid plan, Tab switches name/email, Enter places the order (the per-address cap counts the SSH client's bucket). The checkout address is printed as text to open anywhere; after paying press r, and the claim link appears once, by the ticket the order was placed with. Free is not sold there: use Start my forge. Test: `bun test test/tui-pricing.test.ts`.
15 - **Receipt (#16046):** the page after payment links to `/pricing/orders/<id>`: the plan, the amount, the day the payment arrived (UTC) and the forge, with a download of the same as printable HTML (`/pricing/orders/<id>/receipt.html?download=1`). Only the buyer (the order's cookie, two days) or an admin who is a person can open it; anyone else, and an order not yet paid, gets a missing page. The amount is the price stored on the order when it was made (orders from before that show "not recorded"). The page after payment links to it whichever way the link is shown. The terminal prints the same four facts when the order is ready, claimed or not, but has no way to the printable HTML: that file is the buyer's browser's (the cookie), so open the receipt page there. Code: `src/billing/receipt.ts`. Test: `bun test test/billing-order-receipt.test.ts`.
1516 - **Code:** `src/actions/order.ts` (rules), `src/billing/orders.ts` (store), `src/web/pages/pricing.ts` (pages). The paid path is described in `docs/SPAWN.md`.
1617 - **Test:** `bun test test/pricing-order.test.ts`.
1718
src/actions/order.ts +1 −1
@@ -94,7 +94,7 @@ export async function placeOrder(app: App, input: { name: unknown; plan: unknown
9494 if (refused !== undefined) return err({ field: "name", message: refused });
9595 const id = newId();
9696 const ticket = newTicket();
97 if (!holdName(app.db, { id, name, plan: plan.key, email, ticket, address: input.address }, now)) return err({ field: "name", message: "That name is held for someone else; try another" });
97 if (!holdName(app.db, { id, name, plan: plan.key, priceUsd: plan.priceUsd, email, ticket, address: input.address }, now)) return err({ field: "name", message: "That name is held for someone else; try another" });
9898 const origin = publicOrigin(app.config.url, url.origin);
9999 const made = await provider.create({
100100 orderId: id, forge: name, plan: plan.key, planName: plan.name, priceUsd: plan.priceUsd, email,
src/billing/orders.ts +11 −6
@@ -30,6 +30,10 @@ export interface Order {
3030 readonly id: string;
3131 readonly name: string;
3232 readonly plan: string;
33 /** What the plan cost when the order was made, whole dollars a month; 0 when it was not kept. */
34 readonly priceUsd: number;
35 /** When the payment arrived (the move to `paid`), ms; 0 while pending. */
36 readonly paidAt: number;
3337 readonly email: string;
3438 readonly state: OrderState;
3539 readonly sessionId: string;
@@ -44,13 +48,13 @@ export interface Order {
4448 }
4549
4650 interface Row {
47 id: string; name: string; plan: string; email: string; state: OrderState; ticket_hash: string; session_id: string;
51 id: string; name: string; plan: string; price_usd: number; paid_at: number; email: string; state: OrderState; ticket_hash: string; session_id: string;
4852 customer_id: string; subscription_id: string; reason: string; created_at: number; hold_until: number; updated_at: number;
4953 shown_at: number | null; resent_at: number | null;
5054 }
5155
5256 const fromRow = (r: Row): Order => ({
53 id: r.id, name: r.name, plan: r.plan, email: r.email, state: r.state, sessionId: r.session_id, customerId: r.customer_id,
57 id: r.id, name: r.name, plan: r.plan, priceUsd: r.price_usd, paidAt: r.paid_at, email: r.email, state: r.state, sessionId: r.session_id, customerId: r.customer_id,
5458 subscriptionId: r.subscription_id, reason: r.reason, createdAt: r.created_at, holdUntil: r.hold_until, updatedAt: r.updated_at,
5559 shownAt: r.shown_at, resentAt: r.resent_at,
5660 });
@@ -94,13 +98,13 @@ export const pendingCount = (db: Database, now: number): number =>
9498 db.query<{ n: number }, [number]>("SELECT COUNT(*) AS n FROM forge_order WHERE state = 'pending' AND hold_until > ?1").get(now)?.n ?? 0;
9599
96100 /** Write a new pending order. The hold is checked and the row written in one transaction. False when the name is held. */
97 export function holdName(db: Database, o: { id: string; name: string; plan: string; email: string; ticket: string; address: string }, now: number): boolean {
101 export function holdName(db: Database, o: { id: string; name: string; plan: string; priceUsd: number; email: string; ticket: string; address: string }, now: number): boolean {
98102 return db.transaction(() => {
99103 if (nameHeld(db, o.name, now)) return false;
100104 db.query(
101 `INSERT INTO forge_order (id, name, plan, email, state, ticket_hash, created_at, hold_until, updated_at, address)
102 VALUES (?1, ?2, ?3, ?4, 'pending', ?5, ?6, ?7, ?6, ?8)`,
103 ).run(o.id, o.name, o.plan, o.email, sha256(o.ticket), now, now + HOLD_MS, o.address);
105 `INSERT INTO forge_order (id, name, plan, email, state, ticket_hash, created_at, hold_until, updated_at, address, price_usd)
106 VALUES (?1, ?2, ?3, ?4, 'pending', ?5, ?6, ?7, ?6, ?8, ?9)`,
107 ).run(o.id, o.name, o.plan, o.email, sha256(o.ticket), now, now + HOLD_MS, o.address, o.priceUsd);
104108 return true;
105109 })();
106110 }
@@ -120,6 +124,7 @@ export function move(db: Database, id: string, from: OrderState, to: OrderState,
120124 db
121125 .query(
122126 `UPDATE forge_order SET state = ?3, updated_at = ?4, reason = ?5,
127 paid_at = CASE WHEN ?3 = 'paid' THEN ?4 ELSE paid_at END,
123128 customer_id = CASE WHEN ?6 = '' THEN customer_id ELSE ?6 END,
124129 subscription_id = CASE WHEN ?7 = '' THEN subscription_id ELSE ?7 END
125130 WHERE id = ?1 AND state = ?2`,
src/billing/plan_words.ts +7 −1
@@ -35,12 +35,18 @@ export function creditWords(p: Pick<Plan, "priceUsd" | "creditUsd">, startUsd: n
3535 : "No crew credit: the crew runs on your own AI account key.";
3636 }
3737
38 /**
39 * A monthly price in words, "Free" or "$19 a month": the one formatter /pricing, the terminal and
40 * receipts share.
41 */
42 export const monthlyPrice = (usd: number): string => (usd === 0 ? "Free" : `$${usd} a month`);
43
3844 export function planWords(p: Plan, links: BillingLinks = {}, startUsd = 0): PlanWords {
3945 const free = p.priceUsd === 0;
4046 const buy = free ? undefined : links[p.size];
4147 return {
4248 name: p.name,
43 price: free ? "Free" : `$${p.priceUsd} a month`,
49 price: monthlyPrice(p.priceUsd),
4450 is: `${sizeWords(p.size)}. ${p.says} ${creditWords(p, startUsd)}`,
4551 buy,
4652 };
src/billing/receipt.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * An order's receipt (#16046): the plan, the amount, the date and the forge a payment bought, as
3 * one printable HTML document. Plain data in, a string out. The amount is the price stored on the
4 * order when it was made (`billing/orders.ts` `priceUsd`), worded by `monthlyPrice`, never read
5 * from today's plans. Every value is escaped; the document carries its own style and no script, so
6 * it prints and saves as is. The style hard-codes its colours and font stack on purpose: this is a
7 * standalone file that is saved and printed away from the app, so it cannot load the app's design
8 * tokens. The units sit in the labels (USD, UTC), so the document needs no note of its own.
9 */
10
11 import type { Order } from "./orders.ts";
12 import { monthlyPrice } from "./plan_words.ts";
13 import { escapeHtml } from "../web/html.ts";
14
15 /** An order that took money: a pending order has nothing to receipt. */
16 export const isReceiptable = (o: Pick<Order, "state">): boolean => o.state !== "pending";
17
18 /** The UTC day, `2026-11-23`. */
19 export const receiptDate = (ms: number): string => new Date(ms).toISOString().slice(0, 10);
20
21 /** The amount in words; an order from before the price was kept says so rather than guess. */
22 export const receiptAmount = (o: Pick<Order, "priceUsd">): string => (o.priceUsd > 0 ? monthlyPrice(o.priceUsd) : "not recorded for this order");
23
24 /**
outdated

createdAt is when the order was made, not when it was paid. A receipt's date should be the payment's. Use the paid transition's time, or say plainly it is the order date.

25 * The facts carry the day the payment arrived; an order with none recorded falls back to its
26 * making.
27 */
28 export interface ReceiptFacts {
29 readonly plan: string;
30 readonly amount: string;
31 readonly date: string;
32 readonly forge: string;
33 }
34

Hard-coded hex colours and font stack: say in the header comment that this is a standalone file that cannot load the app's tokens.

35 export function receiptFacts(o: Order, planName: string | undefined): ReceiptFacts {
36 return { plan: planName ?? o.plan, amount: receiptAmount(o), date: receiptDate(o.paidAt > 0 ? o.paidAt : o.createdAt), forge: o.name };
37 }
38
39 const STYLE = "body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:2rem auto;padding:0 1rem;color:#111}h1{font-size:1.4rem}dl{display:grid;grid-template-columns:8rem 1fr;gap:.4rem 1rem}dt{color:#555}dd{margin:0;overflow-wrap:anywhere}small{color:#555}@media print{body{margin:0}}";
40
41 /** The whole receipt document. `site` names the forge that sold it, for the header. */
42 export function receiptDocument(o: Order, planName: string | undefined, site: string): string {
43 const f = receiptFacts(o, planName);
44 const e = escapeHtml;
45 return `<!doctype html>
46 <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">
47 <title>Receipt ${e(o.id)}</title><style>${STYLE}</style></head>
48 <body><main data-receipt>
49 <h1>Receipt</h1>
50 <p><small>${e(site)} · order <code>${e(o.id)}</code></small></p>
51 <dl>
52 <dt>Plan</dt><dd data-fact="plan">${e(f.plan)}</dd>
53 <dt>Amount (USD)</dt><dd data-fact="amount">${e(f.amount)}</dd>
54 <dt>Paid on (UTC)</dt><dd data-fact="date">${e(f.date)}</dd>
55 <dt>Forge</dt><dd data-fact="forge">${e(f.forge)}</dd>
56 </dl>
57 </main></body></html>
58 `;
59 }
src/core/migration-pins/20261123130000-order-price.pin added +1
@@ -0,0 +1,1 @@
1 d1e3e496f9db3501ab5bf1e5988c9b30f39bf284ba71d09770cdc6d7e2f81c01
src/core/migrations/20261123130000-order-price.ts added +9
@@ -0,0 +1,9 @@
1 // An order keeps the price it was sold at and the moment it was paid (#16046), so its receipt
2 // states what was charged and when, and never reads today's plan table. Orders made before this
3 // read price 0 (the receipt says the amount was not kept); their paid_at is the time of their last
4 // change, the nearest record there is. Additive.
5 export default `
6 ALTER TABLE forge_order ADD COLUMN price_usd INTEGER NOT NULL DEFAULT 0;
7 ALTER TABLE forge_order ADD COLUMN paid_at INTEGER NOT NULL DEFAULT 0;
8 UPDATE forge_order SET paid_at = updated_at WHERE state != 'pending';
9 `;
src/http/server.ts +3 −1
@@ -334,7 +334,7 @@ import { forgeReachAllow, forgeReachLater, forgeReachRevoke } from "../web/pages
334334 import { askAdminLater, askAdminSubmit } from "../web/studio/ask_admin.ts";
335335 import { forgeItSubmit } from "../web/pages/forge-it.ts";
336336 import { funnelSubmit } from "./funnel.ts";
337 import { pricingDone, pricingOrder, pricingPage, resendPage, resendSubmit } from "../web/pages/pricing.ts";
337 import { pricingDone, pricingOrder, pricingPage, receiptHtml, receiptPage, resendPage, resendSubmit } from "../web/pages/pricing.ts";
338338 import { startForgeSubmit } from "../web/pages/start-forge.ts";
339339 import { redirect } from "../web/layout.ts";
340340 import { inventoryPage } from "../web/pages/inventory.ts";
@@ -1009,6 +1009,8 @@ export function buildRouter(): Router<Handler> {
10091009 router.add("GET", "/pricing", pricingPage);
10101010 router.add("POST", "/pricing/order", pricingOrder);
10111011 router.add("GET", "/pricing/done", pricingDone);
1012 router.add("GET", "/pricing/orders/:id", receiptPage);
1013 router.add("GET", "/pricing/orders/:id/receipt.html", receiptHtml);
10121014 router.add("GET", "/pricing/resend", resendPage);
10131015 router.add("POST", "/pricing/resend", resendSubmit);
10141016 router.add("GET", "/templates", templatesPage);
src/tui/screens/pricing.ts +6 −3
@@ -11,6 +11,7 @@
1111
1212 import { deliverLink, mayView, NO_PROVIDER, placeOrder, reconcileOrder } from "../../actions/order.ts";
1313 import { AFTER_PAYMENT_STEPS, priceLine } from "../../billing/plan_words.ts";
14 import { receiptFacts } from "../../billing/receipt.ts";
1415 import { lapseRule, lapseRuleWords } from "../../billing/lapse_rule.ts";
1516 import { checkoutOf } from "../../billing/checkout.ts";
1617 import { publicOrigin } from "../../core/public_origin.ts";
@@ -107,10 +108,12 @@ export function pricingScreen(f: Session, ctx: Ctx): Screen {
107108 else if (o.state === "paid" || o.state === "spawning") s.says = `Paid. Making ${o.name}; press r again in a moment.`;
108109 else if (o.state === "failed") stage = { kind: "done", name: o.name, says: `Paid, but the forge could not be made: ${o.reason}. The operator has been told; keep the order id ${o.id}.` };
109110 else {
111 const r = receiptFacts(o, getPlans(f.app.db).find((p) => p.key === o.plan)?.name);
112 const receipt = ` Receipt: ${r.plan}, ${r.amount}, ${r.date}, forge ${r.forge}.`;
110113 const given = await deliverLink(f.app, o);
111 if (given.kind === "link") stage = { kind: "done", name: o.name, says: `${o.name} is ready. Open this link to take it over; it is shown once.${given.mailed ? ` It was also sent to ${o.email}.` : ""}`, link: given.claimUrl };
112 else if (given.kind === "claimed") stage = { kind: "done", name: o.name, says: `${o.name} is taken over; sign in at its address.` };
113 else stage = { kind: "done", name: o.name, says: "The link was shown already, once. Ask for a new one by email at /pricing/resend." };
114 if (given.kind === "link") stage = { kind: "done", name: o.name, says: `${o.name} is ready. Open this link to take it over; it is shown once.${given.mailed ? ` It was also sent to ${o.email}.` : ""}${receipt}`, link: given.claimUrl };
115 else if (given.kind === "claimed") stage = { kind: "done", name: o.name, says: `${o.name} is taken over; sign in at its address.${receipt}` };
outdated

The receipt is missing when the order is already claimed, and no test covers the terminal text. Both doors need to match and be tested.

116 else stage = { kind: "done", name: o.name, says: `The link was shown already, once. Ask for a new one by email at /pricing/resend.${receipt}` };
114117 }
115118 });
116119 };
src/web/pages/pricing.ts +59 −2
@@ -17,7 +17,9 @@ import { cookieValue, type Ctx } from "../../http/context.ts";
1717 import { secureFor } from "../../http/cookie_secure.ts";
1818 import { clientBucket } from "../../http/peer.ts";
1919 import { takeDoor } from "../../http/strangers.ts";
20 import { FREE, type Plan } from "../../settings/plans.ts";
20 import { FREE, getPlan, type Plan } from "../../settings/plans.ts";
21 import { getOrder, type Order } from "../../billing/orders.ts";
22 import { isReceiptable, receiptDocument, receiptFacts } from "../../billing/receipt.ts";
2123 import { getDoorSettings } from "../../settings/door.ts";
2224 import { childHost } from "../../spawn/door.ts";
2325 import { notFoundPage, pageHead } from "../chrome.ts";
@@ -182,7 +184,7 @@ async function doneView(ctx: Ctx): Promise<Response> {
182184 const o = await reconcileOrder(ctx.app, id);
183185 if (o === undefined) return notFoundPage(ctx);
184186 const plain = (title: string, body: Html, status = 200): Response => {
185 const res = page({ ctx, title, body: html`<div class="narrow-wide" data-order="${o.state}">${pageHead(title)}<section class="settings-block">${body}</section>${o.state === "failed" ? null : html`<p class="muted small" data-lapse="sleep">${lapseRuleWords(lapseRule(ctx.app.db))}</p>`}</div>` }, status);
187 const res = page({ ctx, title, body: html`<div class="narrow-wide" data-order="${o.state}">${pageHead(title)}<section class="settings-block">${body}${o.state === "failed" ? null : html`<p class="mt small" data-receipt-link><a href="/pricing/orders/${o.id}">Receipt</a></p>`}</section>${o.state === "failed" ? null : html`<p class="muted small" data-lapse="sleep">${lapseRuleWords(lapseRule(ctx.app.db))}</p>`}</div>` }, status);
186188 res.headers.set("cache-control", "no-store");
187189 return res;
188190 };
@@ -236,3 +238,58 @@ export async function resendSubmit(ctx: Ctx): Promise<Response> {
236238 return res;
237239 }
238240
241 /**
242 * The order this request may read: the buyer, by the cookie's ticket, or an admin who is a person.
243 * Anything else, a pending order and a missing one answer the same missing page.
244 */
245 function receiptOrder(ctx: Ctx): Order | undefined {
246 const id = ctx.params["id"] ?? "";
247 if (!/^ord_[0-9a-f]{32}$/.test(id)) return undefined;
248 const admin = ctx.auth.user?.isAdmin === true && ctx.auth.user.kind !== "agent";
249 if (!admin) {
250 if (!isBuyer(ctx)) return undefined;
251 const [cid, ticket] = (cookieValue(ctx.request, COOKIE) ?? "").split(".");
252 if (cid !== id || ticket === undefined || !mayView(ctx.app, id, ticket)) return undefined;
253 }
254 const o = getOrder(ctx.app.db, id);
255 return o !== undefined && isReceiptable(o) ? o : undefined;
256 }
257
258 // GET /pricing/orders/:id — the receipt: plan, amount, date and forge, from the order as stored.
259 export function receiptPage(ctx: Ctx): Response {
260 const o = receiptOrder(ctx);
261 if (o === undefined) return notFoundPage(ctx);
262 const f = receiptFacts(o, getPlan(ctx.app.db, o.plan)?.name);
263 const base = `/pricing/orders/${o.id}/receipt.html`;
264 const res = page({
265 ctx,
266 title: "Receipt",
267 body: html`<div class="narrow-wide" data-receipt-page>
268 ${pageHead("Receipt", { sub: `Order ${o.id}` })}
269 <section class="settings-block"><dl class="stack">
270 <div><dt>Plan</dt><dd data-fact="plan">${f.plan}</dd></div>
outdated

Principle 1 and the one-accent rule: the note repeats what the download says, and there are two buttons for one document. Keep one button and one note.

271 <div><dt>Amount (USD)</dt><dd data-fact="amount">${f.amount}</dd></div>
272 <div><dt>Paid on (UTC)</dt><dd data-fact="date">${f.date}</dd></div>
273 <div><dt>Forge</dt><dd data-fact="forge">${f.forge}</dd></div>
274 </dl>
275 <p class="muted small">Prices are as charged when the order was made.</p>
276 <p class="mt">${btn("Download printable HTML", { href: `${base}?download=1`, size: "sm" })}</p></section>
277 </div>`,
278 });
279 res.headers.set("cache-control", "private, no-store");
280 return res;
281 }
282
283 // GET /pricing/orders/:id/receipt.html — the same facts as a standalone printable document;
284 // `?download=1` saves it as a file.
285 export function receiptHtml(ctx: Ctx): Response {
286 const o = receiptOrder(ctx);
287 if (o === undefined) return notFoundPage(ctx);
288 const headers: Record<string, string> = {
289 "content-type": "text/html; charset=utf-8",
290 "cache-control": "private, no-store",
291 "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'",
292 };
293 if (ctx.url.searchParams.get("download") === "1") headers["content-disposition"] = `attachment; filename="receipt-${o.id}.html"`;
294 return new Response(receiptDocument(o, getPlan(ctx.app.db, o.plan)?.name, ctx.url.host), { headers });
295 }
test/billing-order-receipt.test.ts added +139
@@ -0,0 +1,139 @@
1 /**
2 * An order's receipt (#16046): plan, amount, date and forge; the buyer's or an admin's; escaped;
3 * printable HTML.
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 { holdName, move, newId, newTicket } from "../src/billing/orders.ts";
11 import { receiptAmount, receiptDate } from "../src/billing/receipt.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { signInCookie } from "./helpers/studio-signin.ts";
15
16 let dir: string;
17 let app: App;
18 let servers: Servers;
19 let base: string;
20
21 const DAY = Date.UTC(2026, 10, 3, 23, 59);
22
23 function order(name: string, state: "pending" | "spawned", priceUsd = 19) {
24 const id = newId();
25 const ticket = newTicket();
26 expect(holdName(app.db, { id, name, plan: "small", priceUsd, email: "[email protected]", ticket, address: "t" }, DAY)).toBe(true);
27 if (state !== "pending") {
28 expect(move(app.db, id, "pending", "paid", DAY)).toBe(true);
29 expect(move(app.db, id, "paid", "spawning", DAY)).toBe(true);
30 expect(move(app.db, id, "spawning", "spawned", DAY)).toBe(true);
31 }
32 return { id, cookie: `forge_order=${id}.${ticket}` };
33 }
34
35 beforeAll(async () => {
36 dir = await mkdtemp(join(tmpdir(), "forge-receipt-"));
37 app = createApp({ dataDir: dir, port: 0 });
38 servers = await serve(app);
39 base = servers.url;
40 for (const [username, first] of [["alice", true], ["bob", false]] as const) {
41 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
42 if (!u.ok) throw new Error("user");
43 }
44 }, 30_000);
45
46 afterAll(async () => {
47 servers.stop();
48 app.close();
49 await rm(dir, { recursive: true, force: true });
50 });
51
52 describe("the receipt", () => {
53 test("words the amount and the date from the stored order", () => {
54 expect(receiptAmount({ priceUsd: 19 })).toBe("$19 a month");
55 expect(receiptAmount({ priceUsd: 0 })).toBe("not recorded for this order");
56 expect(receiptDate(DAY)).toBe("2026-11-03");
57 });
58
59 test("shows the plan, the amount, the date and the forge to the buyer", async () => {
60 const o = order("shopfront", "spawned");
61 const res = await fetch(`${base}/pricing/orders/${o.id}`, { headers: { cookie: o.cookie } });
62 expect(res.status).toBe(200);
63 const text = await res.text();
64 expect(text).toMatch(/data-fact="plan">[^<]*Small/i);
65 expect(text).toContain('data-fact="amount">$19 a month');
66 expect(text).toContain('data-fact="date">2026-11-03');
67 expect(text).toContain('data-fact="forge">shopfront');
68 });
69
70 test("the date is the day the payment arrived, not the day the order was made", async () => {
71 const o = order("paidlater", "spawned");
72 app.db.query("UPDATE forge_order SET created_at = ?2 WHERE id = ?1").run(o.id, Date.UTC(2026, 10, 1, 8, 0));
73 const page = await (await fetch(`${base}/pricing/orders/${o.id}`, { headers: { cookie: o.cookie } })).text();
74 expect(page).toContain('data-fact="date">2026-11-03');
75 expect(page).not.toContain("2026-11-01");
76 const file = await (await fetch(`${base}/pricing/orders/${o.id}/receipt.html`, { headers: { cookie: o.cookie } })).text();
77 expect(file).toContain("2026-11-03");
78 expect(file).toContain("Paid on (UTC)");
79 expect(page.match(/as charged/gi)?.length).toBe(1);
80 expect(page.match(/href="[^"]*receipt\.html/g)?.length).toBe(1);
81 });
82
83 test("the amount is the stored price, not today's plan", async () => {
84 const o = order("oldprice", "spawned", 7);
85 const text = await (await fetch(`${base}/pricing/orders/${o.id}`, { headers: { cookie: o.cookie } })).text();
86 expect(text).toContain("$7 a month");
87 expect(text).not.toContain("$19 a month");
88 });
89
90 test("only the buyer or an admin reads it; everyone else, a pending order and a bad id get 404", async () => {
91 const o = order("private1", "spawned");
92 expect((await fetch(`${base}/pricing/orders/${o.id}`)).status).toBe(404);
93 expect((await fetch(`${base}/pricing/orders/${o.id}/receipt.html`)).status).toBe(404);
94 const other = order("private2", "spawned");
95 expect((await fetch(`${base}/pricing/orders/${o.id}`, { headers: { cookie: other.cookie } })).status).toBe(404);
96 expect((await fetch(`${base}/pricing/orders/${o.id}`, { headers: { cookie: `forge_order=${o.id}.wrong` } })).status).toBe(404);
97 const bob = await signInCookie(base, "bob");
98 expect((await fetch(`${base}/pricing/orders/${o.id}`, { headers: { cookie: bob } })).status).toBe(404);
99 const alice = await signInCookie(base, "alice");
100 expect((await fetch(`${base}/pricing/orders/${o.id}`, { headers: { cookie: alice } })).status).toBe(200);
101 const waiting = order("waiting1", "pending");
102 expect((await fetch(`${base}/pricing/orders/${waiting.id}`, { headers: { cookie: waiting.cookie } })).status).toBe(404);
103 expect((await fetch(`${base}/pricing/orders/nope`)).status).toBe(404);
104 });
105
106 test("a hostile forge name is escaped on the page and in the download", async () => {
107 const o = order("hostile1", "spawned");
108 const evil = `<script>alert(1)</script><img src=x onerror=alert(2)>"&`;
109 app.db.query("UPDATE forge_order SET name = ?2 WHERE id = ?1").run(o.id, evil);
110 const page = await (await fetch(`${base}/pricing/orders/${o.id}`, { headers: { cookie: o.cookie } })).text();
111 expect(page).not.toContain("<script>alert(1)");
112 expect(page).not.toContain("<img src=x");
113 expect(page).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
114 const file = await fetch(`${base}/pricing/orders/${o.id}/receipt.html?download=1`, { headers: { cookie: o.cookie } });
115 const text = await file.text();
116 expect(text).not.toContain("<script>alert(1)");
117 expect(text).not.toContain("<img src=x");
118 expect(text).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
119 });
120
121 test("downloads as printable HTML with its own policy", async () => {
122 const o = order("download1", "spawned");
123 const res = await fetch(`${base}/pricing/orders/${o.id}/receipt.html?download=1`, { headers: { cookie: o.cookie } });
124 expect(res.status).toBe(200);
125 expect(res.headers.get("content-type")).toStartWith("text/html");
126 expect(res.headers.get("content-disposition")).toBe(`attachment; filename="receipt-${o.id}.html"`);
127 expect(res.headers.get("content-security-policy")).toContain("default-src 'none'");
128 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
129 const text = await res.text();
130 expect(text).toStartWith("<!doctype html>");
131 expect(text).toContain("@media print");
132 expect(text).toContain("$19 a month");
133 expect(text).toContain("2026-11-03");
134 expect(text).toContain("download1");
135 expect(text).not.toContain("<script");
136 const inline = await fetch(`${base}/pricing/orders/${o.id}/receipt.html`, { headers: { cookie: o.cookie } });
137 expect(inline.headers.get("content-disposition")).toBeNull();
138 });
139 });
test/no-polling.test.ts +2
@@ -327,6 +327,8 @@ const NOT_WALKED: Record<string, string> = {
327327 "/migrate/jobs/:job": "needs a migration job",
328328 "/now/:stage": "the stage word is one the seed cannot guess",
329329 "/offers/:id": "needs a fork offer receipt, which the seed has none of",
330 "/pricing/orders/:id": "needs an order the buyer's cookie names; the seed has no order (test/billing-order-receipt.test.ts)",
331 "/pricing/orders/:id/receipt.html": "needs an order the buyer's cookie names; the seed has no order (test/billing-order-receipt.test.ts)",
330332 "/resilience/nightly/:job": "needs a nightly job name",
331333 "/runs/:id": "the seed creates no run",
332334 "/signin/access/:token": "needs a one-time access link an admin minted",
test/pages-budget.test.ts +8
@@ -17,6 +17,7 @@
1717 * so no reading answers here while the pages are asked, and a page that waits
1818 * for one is over `AFTER_IDLE_MS` by construction, on any machine.
1919 */
20 import { holdName, move, newId, newTicket } from "../src/billing/orders.ts";
2021 import { fileReport } from "../src/actions/reports.ts";
2122 import { commitLog } from "../src/git/read.ts";
2223 import { repoDir } from "../src/git/repos.ts";
@@ -200,6 +201,13 @@ beforeAll(async () => {
200201 // An agent's start the claim page can show (`/claim/start/:token`): bob's, so no extra account
201202 // joins the walk.
202203 recordStart(app.db, bob.id, "claim_fixture", "127.0.0.1");
204 // A paid order for the receipt pages (#16046): alice, an admin, may read it.
205 const orderId = newId();
206 holdName(app.db, { id: orderId, name: "fixture-shop", plan: "small", priceUsd: 19, email: "[email protected]", ticket: newTicket(), address: "t" }, Date.now());
207 move(app.db, orderId, "pending", "paid", Date.now());
208 move(app.db, orderId, "paid", "spawned", Date.now());
209 FIXTURE["/pricing/orders/:id"] = `/pricing/orders/${orderId}`;
210 FIXTURE["/pricing/orders/:id/receipt.html"] = `/pricing/orders/${orderId}/receipt.html`;
203211 servers = await serve(app);
204212 const signin = await fetch(`${servers.url}/signin`, {
205213 method: "POST",
test/pricing-order.test.ts +8 −2
@@ -142,8 +142,12 @@ describe("/pricing", () => {
142142 const text = await done.text();
143143 expect(text).toContain("shop is ready");
144144 expect(text).toMatch(/claim|token=|#/i);
145 // The receipt is linked from the claim-link branch and the shown-already branch alike (#16046).
146 expect(text).toContain(`href="/pricing/orders/${order!.id}"`);
145147 const again = await fetch(`${base}/pricing/done?order=${order!.id}`, { headers: { cookie } });
146 expect(await again.text()).toContain("shown already");
148 const againText = await again.text();
149 expect(againText).toContain("shown already");
150 expect(againText).toContain(`href="/pricing/orders/${order!.id}"`);
147151 // Someone without the buyer's cookie sees nothing.
148152 expect((await fetch(`${base}/pricing/done?order=${order!.id}`)).status).toBe(404);
149153 });
@@ -175,7 +179,9 @@ describe("/pricing", () => {
175179 expect(alarm.fired).toBe(true);
176180 expect(alarm.says).toContain("nospace");
177181 const done = await fetch(`${base}/pricing/done?order=${order!.id}`, { headers: { cookie } });
178 expect(await done.text()).toContain("paid but not made yet");
182 const failedText = await done.text();
183 expect(failedText).toContain("paid but not made yet");
184 expect(failedText).not.toContain("data-receipt-link");
179185 expect(firedAlarms(app.db, new Date(), { dataDir: null } as any).some((f) => f.key === "paid_order")).toBe(true);
180186 // A non-admin cannot retry; an admin can once there is room.
181187 expect((await retryOrder(app, undefined, order!.id)).ok).toBe(false);
test/security-floor-routes.test.ts +2
@@ -76,6 +76,8 @@ const UNSEEDED: Record<string, string> = {
7676 "/claim/start/:token": "needs a one-time start claim token, which the seed does not mint (test/start.test.ts covers it)",
7777 "/signin/access/:token": "needs a one-time access link an admin minted",
7878 "/tell/share/:id": "needs a receipt for a share sent by the signed-in person, which the seed has none of",
79 "/pricing/orders/:id": "needs an order id the buyer's cookie names; the seed has no order (test/billing-order-receipt.test.ts covers it)",
80 "/pricing/orders/:id/receipt.html": "needs an order id the buyer's cookie names; the seed has no order (test/billing-order-receipt.test.ts covers it)",
7981 "/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
8082 "/api/v1/status/:token": "needs a status token an outsider was handed on filing, which the seed has none of",
8183 "/talk/:id": TALK,
test/tui-pricing.test.ts +37
@@ -319,3 +319,40 @@ test("with no provider the form shows none of the after-payment steps (#13262)",
319319 const text = flat(h);
320320 for (const step of AFTER_PAYMENT_STEPS) expect(text).not.toContain(step.split(" ").slice(0, 4).join(" "));
321321 });
322
323 test("the terminal prints the receipt's four facts on every ready branch, the claimed one too (#16046)", async () => {
324 const f = await fixture();
325 const small = getPlans(f.app.db).find((p) => p.priceUsd > 0)!;
326 const today = new Date().toISOString().slice(0, 10);
327 const facts = (name: string) => [small.name, `$${small.priceUsd} a month`, today, `forge ${name}`];
328 // The claim link branch.
329 const a = await ordered(f, "203.0.113.20", "receipt-link");
330 f.paid.add(a.session);
331 await f.press(a.h, "r");
332 expect(joined(a.h)).toMatch(/\/claim#/);
333 for (const t of facts("receipt-link")) expect(flat(a.h)).toContain(t);
334 // The shown-already branch.
335 const b = await ordered(f, "203.0.113.21", "receipt-shown");
336 f.paid.add(b.session);
337 const id = f.orderRow("receipt-shown")!.id;
338 await reconcileOrder(f.app, id);
339 await deliverLink(f.app, getOrder(f.app.db, id)!);
340 await f.press(b.h, "r");
341 expect(flat(b.h)).toContain("The link was shown already");
342 for (const t of facts("receipt-shown")) expect(flat(b.h)).toContain(t);
343 // The claimed branch: the third forge made has an admin.
344 const c = await ordered(f, "203.0.113.22", "receipt-claimed");
345 f.paid.add(c.session);
346 await reconcileOrder(f.app, f.orderRow("receipt-claimed")!.id);
347 const child = createApp({ dataDir: childDirOf(f.app, "fake-3") });
348 try {
349 const made = await createUser(child.db, { origin: "seed", trusted: true, username: "keeper", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
350 if (!made.ok) throw new Error(JSON.stringify(made.error));
351 child.db.query("UPDATE user SET is_admin = 1 WHERE username = 'keeper'").run();
352 } finally {
353 child.close();
354 }
355 await f.press(c.h, "r");
356 expect(flat(c.h)).toContain("is taken over");
357 for (const t of facts("receipt-claimed")) expect(flat(c.h)).toContain(t);
358 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs