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

Billing and agents forms re-render through refused/kept with the failing field named #14005

Merged opened this

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

Merged

mason/forge:mason/14003-billing-and-agents-forms-re-render-throu → main 3 commits fork 2 threads · 2 unresolved

  • Merged. mason/14003-billing-and-agents-forms-re-render-throu was merged into main as 770e8ce.

Review

Sign in to review this change.
5 files changed +151 −30
src/web/pages/agents.ts +9 −3
@@ -11,6 +11,7 @@ import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.t
1111 import { pageHead } from "../chrome.ts";
1212 import { html, type Html } from "../html.ts";
1313 import { btn, disclosure, field as formField } from "../ui.ts";
14 import { kept, type Refused } from "../form.ts";
1415 import { page } from "../layout.ts";
1516 import { renderMarkdown } from "../markdown.ts";
1617 import { START_BUTTON } from "../site_line.ts";
@@ -66,7 +67,11 @@ export function guideHtml(body: string): Html {
6667 return renderMarkdown(linkAddresses(withoutTitle(body)));
6768 }
6869
69 export async function agentsPage(ctx: Ctx): Promise<Response> {
70 /**
71 * `refusal`: a refused start from this page's form, drawn with the name kept and the reason beside
72 * it.
73 */
74 export async function agentsPage(ctx: Ctx, refusal?: Refused): Promise<Response> {
7075 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
7176 await loadMcp();
7277 const { body } = llmsBody(ctx);
@@ -80,11 +85,12 @@ export async function agentsPage(ctx: Ctx): Promise<Response> {
8085 <section class="stack" aria-labelledby="agent-forge-h">
8186 <h2 id="agent-forge-h">Get a forge of your own</h2>
8287 <form method="post" action="/forges/start" class="stack" id="agent-forge">
83 ${formField({ label: "Name", name: "name", required: true })}
88 <input type="hidden" name="from" value="agents" />
89 ${formField(kept(refusal, { label: "Name", name: "name", required: true }))}
8490 ${btn(START_BUTTON, { variant: "primary" })}
8591 </form>
8692 </section>
8793 <div class="prose break"><ol id="agent-steps" aria-label="Build an app with no account">${firstSteps(body).map((step) => html`<li>${stepLine(step)}</li>`)}</ol></div>
8894 ${disclosure("? Full guide", html`<article class="prose prose-page" id="agents-guide">${guideHtml(body)}</article>`, { id: "agents-more" })}`,
89 }));
95 }, refusal === undefined ? 200 : 422));
9096 }
src/web/pages/billing.ts +33 −22
@@ -22,10 +22,11 @@ import { getPlans } from "../../settings/plans.ts";
2222 import { changeBillingLinks, changePortalUrl, readBillingLinks } from "../../actions/signup.ts";
2323 import { funnelReport, type FunnelReport } from "../../perf/funnel.ts";
2424 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
25 import { field, readForm } from "../form.ts";
25 import { field, kept, readForm, refused, type Refused } from "../form.ts";
2626 import { html, type Html } from "../html.ts";
2727 import { flashTo, page } from "../layout.ts";
2828 import { btn, copyField, field as formField, selectField } from "../ui.ts";
29 import type { FieldOptions } from "../ui.ts";
2930 import { accountSections } from "./origins.ts";
3031
3132 const PATH = "/settings/billing";
@@ -42,7 +43,7 @@ const isPerson = (ctx: Ctx): boolean => ctx.auth.user?.isAdmin === true && ctx.a
4243 const day = (iso: string): string => iso.slice(0, 10);
4344
4445 /** The Codes section: make one, copy it once, then one line per code with its one action. */
45 function codesSection(ctx: Ctx, shown: Shown | undefined, values: Record<string, string>, error: string | undefined): Html | null {
46 function codesSection(ctx: Ctx, shown: Shown | undefined, r: Refused | undefined): Html | null {
4647 const read = readCodes(ctx.app, ctx.auth.user);
4748 if (!read.ok) return null;
4849 const { codes, plans } = read.value;
@@ -67,7 +68,6 @@ function codesSection(ctx: Ctx, shown: Shown | undefined, values: Record<string,
6768 });
6869 return html`<section class="settings-block" id="codes">
6970 <h2>Codes</h2>
70 ${error === undefined ? null : html`<p class="error" role="alert">${error}</p>`}
7171 ${shown === undefined
7272 ? null
7373 : html`<div class="stack stack-tight" id="new-code" role="status">
@@ -76,20 +76,29 @@ function codesSection(ctx: Ctx, shown: Shown | undefined, values: Record<string,
7676 ${copyField("gift-link", shown.link, "The link to send", "Copy the link")}
7777 </div>`}
7878 <form class="row-fields" method="post" action="${PATH}/codes" id="make-code">
79 ${selectField({ label: "Plan it gives", name: "plan", options: plans.map((p) => ({ value: p, label: p, selected: p === (values["plan"] ?? plans[0]) })) })}
80 ${formField({ label: "Uses", name: "uses", type: "number", value: values["uses"] ?? "1" })}
81 ${formField({ label: "Note", name: "note", value: values["note"] ?? "", hint: "For Mark" })}
82 ${formField({ label: "Expires", name: "expires", type: "date", value: values["expires"] ?? "" })}
79 ${selectField(planChoice(kept(r, { label: "Plan it gives", name: "plan", type: "select", options: plans.map((p, i) => ({ value: p, label: p, selected: i === 0 })) })))}
80 ${formField(kept(r, { label: "Uses", name: "uses", type: "number", value: "1" }))}
81 ${formField(kept(r, { label: "Note", name: "note", value: "", hint: "For Mark" }))}
82 ${formField(kept(r, { label: "Expires", name: "expires", type: "date", value: "" }))}
8383 ${btn("Make a code", { variant: "primary" })}
8484 </form>
8585 ${lines.length === 0 ? html`<p class="muted small">No code yet.</p>` : html`<ul class="list setting-list">${lines}</ul>`}
8686 </section>`;
8787 }
8888
89 /**
90 * A select's options as `selectField` takes them (the kept options are optional on the shared
91 * type).
92 */
93 const planChoice = (o: FieldOptions) => ({ ...o, options: [...(o.options ?? [])] });
94
95 /** The field of the code form each refusal belongs beside. */
96 const CODE_FIELD: Record<Exclude<CodeError, "not_found">, string> = { bad_plan: "plan", bad_uses: "uses", bad_note: "note", bad_expiry: "expires", no_such_code: "plan" };
97
8998 const codeWords = (e: CodeError): string => (e === "not_found" ? "Not found" : CODE_ERRORS[e]);
9099
91100 /** The Payment links section: one https field per size a paid plan sits on, saved in one submit. */
92 function linksSection(ctx: Ctx, retry?: { values: Record<string, string>; error: string }): Html | null {
101 function linksSection(ctx: Ctx, r: Refused | undefined): Html | null {
93102 const links = readBillingLinks(ctx.app, ctx.auth.user);
94103 if (!links.ok) return null;
95104 const paid = getPlans(ctx.app.db).filter((p) => p.priceUsd > 0);
@@ -100,10 +109,9 @@ function linksSection(ctx: Ctx, retry?: { values: Record<string, string>; error:
100109 return html`<section class="settings-block" id="links">
101110 <h2>Payment links</h2>
102111 <p class="muted small">Where a buyer pays for each paid plan. With any set, the home page offers paid forges; empty clears one.</p>
103 ${retry === undefined ? null : html`<p class="error" role="alert">${retry.error}</p>`}
104112 <form class="stack" method="post" action="${PATH}/links">
105113 ${fields.map((f) =>
106 formField({ label: `${f.named === "" ? f.size : f.named} (${f.size})`, name: f.size, type: "url", value: retry?.values[f.size] ?? links.value[f.size] ?? "", hint: "https://" }),
114 formField(kept(r, { label: `${f.named === "" ? f.size : f.named} (${f.size})`, name: f.size, type: "url", value: links.value[f.size] ?? "", hint: "https://" })),
107115 )}
108116 ${btn("Save payment links", { variant: "primary" })}
109117 </form>
@@ -111,14 +119,13 @@ function linksSection(ctx: Ctx, retry?: { values: Record<string, string>; error:
111119 }
112120
113121 /** The one billing-portal address every paying forge's Plan row links to. */
114 function portalSection(ctx: Ctx, retry?: { value: string; error: string }): Html | null {
122 function portalSection(ctx: Ctx, r: Refused | undefined): Html | null {
115123 if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent") return null;
116124 return html`<section class="settings-block" id="portal">
117125 <h2>Billing portal</h2>
118126 <p class="muted small">Stripe's customer-portal sign-in. A forge that pays through Stripe links its owner here to change a card; empty shows no link.</p>
119 ${retry === undefined ? null : html`<p class="error" role="alert">${retry.error}</p>`}
120127 <form class="stack" method="post" action="${PATH}/portal">
121 ${formField({ label: "Portal sign-in address", name: "portal_url", type: "url", value: retry?.value ?? getPortalUrl(ctx.app.db), hint: "https://billing.stripe.com/p/login/…" })}
128 ${formField(kept(r, { label: "Portal sign-in address", name: "portal_url", type: "url", value: getPortalUrl(ctx.app.db), hint: "https://billing.stripe.com/p/login/…" }))}
122129 ${btn("Save portal address", { variant: "primary" })}
123130 </form>
124131 </section>`;
@@ -133,7 +140,7 @@ export async function billingSetPortal(ctx: Ctx): Promise<Response> {
133140 const changed = changePortalUrl(ctx.app, ctx.auth.user, value);
134141 if (!changed.ok && changed.error === "not_found") return notFoundPage(ctx);
135142 if (changed.ok) return flashTo(ctx, `${PATH}#portal`, { message: "Billing portal address saved." });
136 return billingView(ctx, undefined, {}, undefined, 422, undefined, { value, error: `${PORTAL_WORDS}. Nothing was saved.` });
143 return billingView(ctx, undefined, 422, refused(form, { portal_url: `${PORTAL_WORDS}. Nothing was saved.` }));
137144 }
138145
139146 // POST /settings/billing/links
@@ -149,9 +156,9 @@ export async function billingSetLinks(ctx: Ctx): Promise<Response> {
149156 if (!changed.ok && changed.error === "not_found") return notFoundPage(ctx);
150157 if (changed.ok) return flashTo(ctx, `${PATH}#links`, { message: "Payment links saved." });
151158 // Name the sizes refused, and show the form again with what was typed.
152 const refused = BILLING_SIZES.filter((z) => !parseBillingLinks({ [z]: next[z] }).ok);
153 const error = `${refused.join(" and ")}: each payment link is an https address with no spaces, or empty. Nothing was saved.`;
154 return billingView(ctx, undefined, {}, undefined, 422, { values: next, error });
159 const errors: Record<string, string> = {};
160 for (const z of BILLING_SIZES) if (!parseBillingLinks({ [z]: next[z] }).ok) errors[z] = "A payment link is an https address with no spaces, or empty. Nothing was saved.";

Same sentence on every refused size, with Nothing was saved. repeated. Say the size in the message or say the outcome once.

161 return billingView(ctx, undefined, 422, refused(form, errors));
155162 }
156163
157164 /**
@@ -185,7 +192,11 @@ export function billingPage(ctx: Ctx): Response {
185192 return billingView(ctx);
186193 }
187194
188 function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {}, error?: string, status = 200, links?: { values: Record<string, string>; error: string }, portal?: { value: string; error: string }): Response {
195 /**
196 * The page; a refused POST passes its `Refused` and each section keeps its own form's fields from
197 * it.
198 */
199 function billingView(ctx: Ctx, shown?: Shown, status = 200, refusal?: Refused): Response {
189200 const read = readBilling(ctx.app, ctx.auth.user);
190201 if (!read.ok) return notFoundPage(ctx);
191202 const b = read.value;
@@ -254,9 +265,9 @@ function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {
254265 </section>
255266 ${ledBlock(ctx)}
256267 ${funnelRow(funnelReport(ctx.app.db, 7))}
257 ${linksSection(ctx, links)}
258 ${portalSection(ctx, portal)}
259 ${codesSection(ctx, shown, values, error)}`;
268 ${linksSection(ctx, refusal)}
269 ${portalSection(ctx, refusal)}
270 ${codesSection(ctx, shown, refusal)}`;
260271 const response = page({
261272 ctx,
262273 title: "Billing",
@@ -276,7 +287,7 @@ export async function billingMakeCode(ctx: Ctx): Promise<Response> {
276287 if (form instanceof Response) return form;
277288 const values = { plan: field(form, "plan"), uses: field(form, "uses"), note: field(form, "note"), expires: field(form, "expires") };
278289 const made = makeCode(ctx.app, ctx.auth.user, values, publicOrigin(ctx.app.config.url, ctx.url.origin));
279 if (!made.ok) return made.error === "not_found" ? notFoundPage(ctx) : billingView(ctx, undefined, values, `${codeWords(made.error)}.`, 422);
290 if (!made.ok) return made.error === "not_found" ? notFoundPage(ctx) : billingView(ctx, undefined, 422, refused(form, { [CODE_FIELD[made.error]]: `${codeWords(made.error)}.` }));
280291 return billingView(ctx, { code: made.value.code, link: made.value.link });
281292 }
282293
src/web/pages/start-forge.ts +7 −3
@@ -11,11 +11,12 @@ import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1111 import type { Ctx } from "../../http/context.ts";
1212 import { spawnDoor } from "../../spawn/door.ts";
1313 import { noteForgeMade } from "../funnel_door.ts";
14 import { field, readForm } from "../form.ts";
14 import { field, readForm, refused } from "../form.ts";
15 import { agentsPage } from "./agents.ts";
1516 import { madeBody, madeJs } from "../forge_made.ts";
1617 import { page, redirect } from "../layout.ts";
1718 import { notFoundPage } from "../chrome.ts";
18 import { startRefusalHref, startRefusalOf } from "../start_refusal.ts";
19 import { START_REFUSALS, startRefusalHref, startRefusalOf } from "../start_refusal.ts";
1920
2021 /** The home's live name check: asks `GET /forges/name/<name>` and says free, taken, or the route's own reason; a 429 or a failure says nothing. */
2122 export const startNameJs = `(function(d){
@@ -45,8 +46,11 @@ export async function startForgeSubmit(ctx: Ctx): Promise<Response> {
4546 if (user !== undefined) return redirect(SLUG.test(name) ? `/forges/new?name=${encodeURIComponent(name)}` : "/forges/new");
4647 const door = await spawnDoor(ctx, undefined, { name, dryRun: false }, { page: true });
4748 if (door.status >= 400) {
49 const why = startRefusalOf(door);
50 // The /agents form is answered on /agents, the name kept and the reason beside it.
51 if (field(form, "from") === "agents") return agentsPage(ctx, refused(form, { name: START_REFUSALS[why] }));
4852 // Said on the home page, with the name kept (#11238).

A refused start returns the /agents page from the POST URL, so a reload re-posts the form. Fine for now; a redirect that keeps the name would avoid it.

49 return redirect(startRefusalHref(startRefusalOf(door), typed));
53 return redirect(startRefusalHref(why, typed));
5054 }
5155 const link = door.body["claimUrl"];
5256 if (typeof link !== "string") return redirect(startRefusalHref("taken", name));
test/billing-agents-keep.test.ts added +98
@@ -0,0 +1,98 @@
1 /**
2 * The billing forms (payment links, portal address, code) and the /agents
3 * start form re-render a refused POST through `refused`/`kept`: the typed
4 * value kept and escaped, the failing field marked `aria-invalid` and named,
5 * no bare error line above the form.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { promote } from "./helpers/members.ts";
17
18 quietLogs();
19
20 let dataDir: string;
21 let app: App;
22 let servers: Servers;
23 let cookie: string;
24
25 const post = (path: string, fields: Record<string, string>, as = cookie) =>
26 fetch(`${servers.url}${path}`, {
27 method: "POST",
28 redirect: "manual",
29 headers: { origin: new URL(servers.url).origin, cookie: as },
30 body: new URLSearchParams(fields),
31 });
32
33 const XSS = `"><script>alert(1)</script>`;
34 const ESCAPED = "&quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;";
35
36 beforeAll(async () => {
37 dataDir = await mkdtemp(join(tmpdir(), "forge-billing-keep-"));
38 app = createApp({ dataDir, port: 0 });
39 servers = await serve(app);
40 const made = await createUser(app.db, {
41 origin: "seed",
42 trusted: true,
43 username: "owner",
44 email: "[email protected]",
45 password: "a-good-passphrase",
46 allowReserved: true,
47 adminIfFirst: true,
48 });
49 if (!made.ok) throw new Error(made.error);
50 promote(app.db, made.value);
51 cookie = `forge_session=${createSession(app.db, made.value.id).token}`;
52 });
53 afterAll(async () => {
54 await servers.stop();
55 await rm(dataDir, { recursive: true, force: true });
56 });
57
58 test("a refused payment link keeps the value, escaped, on the failing field", async () => {
59 const res = await post("/settings/billing/links", { small: XSS });
60 expect(res.status).toBe(422);
61 const text = await res.text();
62 expect(text).not.toContain(XSS);
63 expect(text).toContain(`value="${ESCAPED}"`);
64 expect(text).toMatch(/<input[^>]*name="small"[^>]*aria-invalid="true"|<input[^>]*aria-invalid="true"[^>]*name="small"/);
65 expect(text).toContain('id="f-small-err"');
66 expect(text).not.toContain('<p class="error" role="alert">');
67 });
68
69 test("a refused portal address keeps the value, escaped, on its field", async () => {
70 const res = await post("/settings/billing/portal", { portal_url: XSS });
71 expect(res.status).toBe(422);
72 const text = await res.text();
73 expect(text).not.toContain(XSS);
74 expect(text).toContain(`value="${ESCAPED}"`);
75 expect(text).toMatch(/<input[^>]*name="portal_url"[^>]*aria-invalid="true"|<input[^>]*aria-invalid="true"[^>]*name="portal_url"/);
76 expect(text).toContain('id="f-portal_url-err"');
77 });
78
79 test("a refused code keeps the note, names the uses field", async () => {
80 const res = await post("/settings/billing/codes", { plan: "nope", uses: "0", note: XSS, expires: "" });
81 expect(res.status).toBe(422);
82 const text = await res.text();
83 expect(text).not.toContain(XSS);
84 expect(text).toContain(`value="${ESCAPED}"`);
85 expect(text).toMatch(/<select[^>]*aria-invalid="true"/);
86 expect(text).toContain('id="f-plan-err"');
87 expect(text).not.toContain('<p class="error" role="alert">');
88 });
89
90 test("a refused start on /agents comes back on /agents with the name kept", async () => {
91 const res = await post("/forges/start", { from: "agents", name: `-${XSS}` }, "");
92 expect(res.status).toBe(422);
93 const text = await res.text();
94 expect(text).not.toContain(XSS);
95 expect(text).toContain(ESCAPED);
96 expect(text).toMatch(/<input[^>]*name="name"[^>]*aria-invalid="true"|<input[^>]*aria-invalid="true"[^>]*name="name"/);
97 expect(text).toContain('id="f-name-err"');
98 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs