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

A form that fails validation keeps what was typed and puts the error beside its field #13194

Merged opened this

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

Merged

scout/forge:scout/13165-a-form-that-fails-validation-keeps-what → main 7 commits fork 2 threads · 2 unresolved

  • Merged. scout/13165-a-form-that-fails-validation-keeps-what was merged into main as fbe7393.

Review

Sign in to review this change.
5 files changed +263 −32
docs/features/README.md +1
@@ -246,6 +246,7 @@ Read with the guide page [Your apps](../guide-your-apps.md).
246246 - [An OpenAPI document opens as its operations](file-openapi.md)
247247 - [Calendar files (.ics) as a list of events](ics.md)
248248 - [Config files as a form](config-form.md)
249 - [A refused form keeps what was typed](form-keeps-input.md)
249250 - [Contacts files (.vcf) as a list of people](vcf-view.md)
250251 - [CSV and TSV as a table](csv-view.md)
251252 - [Video-edit timelines (.otio, .edl, .fcpxml) as a cut list](timeline-cut-list.md)
docs/features/form-keeps-input.md added +24
@@ -0,0 +1,24 @@
1 # A refused form keeps what was typed
2
3 When the server refuses a form POST (422), it draws the same form again with what the person typed
4 still in it, and the message sits beside the field it is about, linked with `aria-describedby`,
5 with focus on the first field that has a message. Nothing above the form moves.
6
7 - Text, textarea, select and checkbox fields come back as typed (escaped by the renderer).
8 - A password field, and any field named for a secret (`password`, `secret`, `token`, `credential`,
9 `api_key`, `otp`, `pin`, as whole words), is never sent back: the person types it again.
10 - A refusal with no field (for example a store failure) shows in the form's danger toast.
11
12 Where it lives: `refused` and `kept` in `src/web/form.ts`; a page builds one `Refused` from the form
13 and its messages and passes each field through `kept`. First users: the profile form (display
14 name, email, commit email) and the password change.
15
16 Try it: open `/settings/password`, type different new and confirm passwords, submit; the message
17 sits beside New password with focus and no password is echoed. Or give `/settings` an email of
18 `not an email`.
19
20 The terminal (both doors): it has no HTML forms and no profile or password screen. A refused write
21 there shows the reason as a danger toast (`ctx.toast(errorText(...), "danger")` in `src/tui`) and
22 leaves the screen as it was; nothing changes in the terminal.
23
24 Pinned by `test/form-keeps-input.test.ts`.
src/web/form.ts +47
@@ -12,6 +12,7 @@ import { CAME_FROM_ELSEWHERE, forbiddenPage, SENT_FROM_ELSEWHERE } from "./chrom
1212 import { BODY_MAX, readBounded, STRANGER_MAX } from "../http/limits.ts";
1313 import { scopeAllows, type TokenScope } from "../core/tokens.ts";
1414 import { isLocalPath } from "./flash.ts";
15 import type { FieldOptions } from "./ui.ts";
1516 import { crossOrigin, type Ctx } from "../http/context.ts";
1617
1718 export type Form = Awaited<ReturnType<Request["formData"]>>;
@@ -75,3 +76,49 @@ export function backTo(form: Form, fallback: string): string {
7576 export function prefersJson(ctx: Ctx): boolean {
7677 return (ctx.request.headers.get("accept") ?? "").includes("application/json");
7778 }
79
80 /**
81 * A refused POST: what was typed and what is wrong, by field name. Pages
82 * re-render the same form with each field passed through `kept`, so the
83 * owner's words survive a refusal and the message sits beside its field.
84 */
85 export interface Refused {
86 form: Form;
87 errors: Readonly<Record<string, string>>;
88 }
89
90 export function refused(form: Form, errors: Record<string, string>): Refused {
91 return { form, errors };
92 }
93

Too broad: key and pin$ match ordinary names (keywords, monkey). Anchor on whole words and test a kept name containing key.

94 /** Fields whose value is never sent back to the browser. */
95 const SECRET_NAME = /^(.*[_-])?(pass(word)?|secret|token|credential|api_?key|otp|pin)$/i;
96 /** The camelCase spelling of the same words: `newPassword`, `apiKey`. */
97 const SECRET_CAMEL = /[a-z](Pass(word)?|Secret|Token|Credential|ApiKey|Otp|Pin)$/;
98 const isSecret = (o: FieldOptions): boolean =>
99 o.type === "password" || SECRET_NAME.test(o.name) || SECRET_CAMEL.test(o.name);
100
101 /**
102 * A field's options with the refused submit applied: the typed value kept
103 * (escaped by the renderer; never for a secret), the message of this field,
104 * and focus on the first field that has one. With no refusal, unchanged.
105 */
106 export function kept(r: Refused | undefined, o: FieldOptions): FieldOptions {
107 if (r === undefined) return o;
108 const out: FieldOptions = { ...o };
109 const typed = r.form.get(o.name);
110 if (!isSecret(o)) {
111 if (o.type === "checkbox") out.checked = typed !== null;
112 else if (typeof typed === "string") {
113 if (o.type === "select" && o.options !== undefined)
114 out.options = o.options.map((c) => ({ ...c, selected: c.value === typed }));
115 else out.value = typed;
116 }
117 }
118 const message = r.errors[o.name];
119 if (message !== undefined) {
120 out.error = message;
121 if (Object.keys(r.errors)[0] === o.name) out.autofocus = true;
122 }
123 return out;
124 }
src/web/pages/account.ts +41 −32
@@ -60,7 +60,7 @@ import {
6060 notFoundPage,
6161 } from "../chrome.ts";
6262 import { accountSections } from "./origins.ts";
63 import { field, readForm } from "../form.ts";
63 import { field, kept, readForm, refused, type Form, type Refused } from "../form.ts";
6464 import { html, when, type Html } from "../html.ts";
6565 import { mailCappedBlocked, noMailBlocked } from "../../actions/blocked_words.ts";
6666 import { blockedFlash } from "../blocked.ts";
@@ -142,7 +142,8 @@ interface ProfileForm {
142142 displayName: string;
143143 email: string;
144144 commitEmail: CommitEmail;
145 errors?: { displayName?: string; email?: string; form?: string };
145 /** The refused submit: typed values kept, messages beside their fields (`form`: none). */
146 refused?: Refused;
146147 }
147148
148149 /** The profile form as the account stands now. */
@@ -247,7 +248,10 @@ function edgeLinkView(ctx: Ctx): Html {
247248 );
248249 }
249250
250 /** The parent forge: linked as its host, or not, with Link (a round trip through the parent) and Unlink. */
251 /**
252 * The parent forge: linked as its host, or not, with Link (a round trip through the parent) and
253 * Unlink.
254 */
251255 function parentLinkView(ctx: Ctx): Html {
252256 const issuer = parentIssuerOf(ctx.app.config);
253257 if (issuer === undefined) return html``;
@@ -339,7 +343,8 @@ export async function resendVerifyLink(ctx: Ctx): Promise<Response> {
339343 const form = await readForm(ctx);
340344 if (form instanceof Response) return form;
341345 const sent = await resendVerification(ctx.app, ctx.auth.user);
342 // No mail: said in the reader's terms, with the page that verifies when they are an admin, and who can when they are not (`kernel/blocked.ts`).
346 // No mail: said in the reader's terms, with the page that verifies when they are an admin, and
347 // who can when they are not (`kernel/blocked.ts`).
343348 if (!sent.ok && sent.error === "no_mail" && ctx.auth.user !== undefined) {
344349 return flashTo(ctx, "/settings", blockedFlash(noMailBlocked(ctx.app, ctx.auth.user), "success"));
345350 }
@@ -409,25 +414,22 @@ function profileView(ctx: Ctx, values: ProfileForm): Html {
409414 readonly
410415 />
411416 </div>
412 ${uiField({
417 ${uiField(kept(values.refused, {
413418 label: "Display name",
414419 name: "displayName",
415420 value: values.displayName,
416 ...(values.errors?.displayName
417 ? { error: values.errors.displayName }
418 : {}),
419 })}
420 ${uiField({
421 }))}
422 ${uiField(kept(values.refused, {
421423 label: "Email",
422424 name: "email",
423425 type: "email",
424426 value: values.email,
425427 autocomplete: "email",
426 ...(values.errors?.email ? { error: values.errors.email } : {}),
427 })}
428 ${selectField({
428 }))}
429 ${uiField(kept(values.refused, {
429430 label: "Commit email",
430431 name: "commitEmail",
432 type: "select",
431433 options: [
432434 {
433435 value: "noreply",
@@ -440,11 +442,11 @@ function profileView(ctx: Ctx, values: ProfileForm): Html {
440442 selected: values.commitEmail === "account",
441443 },
442444 ],
443 })}
445 }))}
444446 <div class="form-actions">
445447 ${btn("Save", { variant: "primary" })}
446448 </div>
447 ${refusal(values.errors?.form)}
449 ${refusal(values.refused?.errors.form)}
448450 </form>`,
449451 )}`;
450452 }
@@ -452,7 +454,10 @@ function profileView(ctx: Ctx, values: ProfileForm): Html {
452454 /** A reading the cell may not give: a dash, never a zero that says "idle". */
453455 const reading = (n: number | null, unit: string): string => (n === null ? "–" : `${n}${unit}`);
454456
455 /** The machine shells this person holds and last held (#10544). Read only; the live row says its few facts in a `dl`. */
457 /**
458 * The machine shells this person holds and last held (#10544). Read only; the live row says its few
459 * facts in a `dl`.
460 */
456461 export function shellsView(ctx: Ctx, user: User): Html {
457462 const shells = myShells(ctx.app, user.id);
458463 if (shells.length === 0) return html`<p class="muted" id="shells">You have opened no shell on a machine yet.</p>`;
@@ -489,7 +494,10 @@ export function shellsView(ctx: Ctx, user: User): Html {
489494 </ul>`;
490495 }
491496
492 /** The gallery's own rules, sent with its page only: every other page's stylesheet stays without them. */
497 /**
498 * The gallery's own rules, sent with its page only: every other page's stylesheet stays without
499 * them.
500 */
493501 const galleryCss = /* css */ `
494502 .theme-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-top: 12px; }
495503 @media (min-width: 720px) { .theme-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
@@ -521,7 +529,8 @@ function themeCard(value: string, label: string, kind: string, looks: readonly T
521529 </button>`;
522530 }
523531
524 // GET /settings/appearance — every theme, to pick by looking. A visitor's too: the choice is a cookie.
532 // GET /settings/appearance — every theme, to pick by looking. A visitor's too: the choice is a
533 // cookie.
525534 export function appearancePage(ctx: Ctx): Response {
526535 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
527536 const body = block(
@@ -638,7 +647,7 @@ export async function accountUpdate(ctx: Ctx): Promise<Response> {
638647 if (!updated.ok) {
639648 const words = PROFILE_REFUSALS[updated.error];
640649 const at = PROFILE_REFUSAL_FIELD[updated.error];
641 const errors: ProfileForm["errors"] =
650 const errors =
642651 words === undefined || at === undefined ? { form: PROFILE_FALLBACK } : { [at]: words };
643652 return accountShell(
644653 ctx,
@@ -651,7 +660,7 @@ export async function accountUpdate(ctx: Ctx): Promise<Response> {
651660 commitEmail === "noreply" || commitEmail === "account"
652661 ? commitEmail
653662 : ctx.auth.user.commitEmail,
654 errors,
663 refused: refused(form, errors),
655664 }),
outdated

Duplicates errors just above and is a very long line. Build one refusal and pass it, and the commitEmail select should go through kept too.

656665 422,
657666 );
@@ -664,19 +673,19 @@ export async function accountUpdate(ctx: Ctx): Promise<Response> {
664673 function passwordView(error?: {
665674 field: "current" | "next";
666675 text: string;
667 }): Html {
676 }, form?: Form): Html {
677 const r = error === undefined || form === undefined ? undefined : refused(form, { [error.field]: error.text });
668678 return html`${help([["New password", "A passphrase beats a puzzle: a few unrelated words are long and easy to remember."]])}${block(
669679 "Change password",
670680 html`<form method="post" action="/settings/password">
671 ${uiField({
681 ${uiField(kept(r, {
672682 label: "Current password",
673683 name: "current",
674684 type: "password",
675685 autocomplete: "current-password",
676686 required: true,
677 ...(error?.field === "current" ? { error: error.text } : {}),
678 })}
679 ${uiField({
687 }))}
688 ${uiField(kept(r, {
680689 label: "New password",
681690 name: "next",
682691 type: "password",
@@ -684,15 +693,14 @@ function passwordView(error?: {
684693 minlength: 10,
685694 required: true,
686695 hint: "At least 10 characters.",
687 ...(error?.field === "next" ? { error: error.text } : {}),
688 })}
689 ${uiField({
696 }))}
697 ${uiField(kept(r, {
690698 label: "Confirm new password",
691699 name: "confirm",
692700 type: "password",
693701 autocomplete: "new-password",
694702 required: true,
695 })}
703 }))}
696704 <div class="form-actions">
697705 ${btn("Change password", { variant: "primary" })}
698706 </div>
@@ -724,7 +732,7 @@ export async function passwordUpdate(ctx: Ctx): Promise<Response> {
724732 passwordView({
725733 field: "next",
726734 text: "The two new passwords don't match.",
727 }),
735 }, form),
728736 422,
729737 );
730738 }
@@ -739,7 +747,7 @@ export async function passwordUpdate(ctx: Ctx): Promise<Response> {
739747 field: changed.error === "weak_password" || changed.error === "password_too_long" ? ("next" as const) : ("current" as const),
740748 text: CHANGE_PASSWORD_WORDS[changed.error],
741749 };
742 return accountShell(ctx, "password", "Password", passwordView(error), 422);
750 return accountShell(ctx, "password", "Password", passwordView(error, form), 422);
743751 }
744752 return flashTo(ctx, "/settings/password", {
745753 message: PASSWORD_CHANGED_WORDS,
@@ -783,7 +791,8 @@ export function sessionsCard(
783791 export function connectCard(ctx: Ctx, token: string | undefined): Html {
784792 const url = publicOrigin(ctx.app.config.url, ctx.url.origin);
785793 const env = `FORGE_URL=${url} FORGE_TOKEN=${token ?? "<token>"}`;
786 // The plugin marketplace is the forge's configured source, offered only while anyone can clone it.
794 // The plugin marketplace is the forge's configured source, offered only while anyone can clone
795 // it.
787796 const repo = offeredPluginRepo(ctx.app.db, ctx.app.config.forgeRepo, UPSTREAM_REPO);
788797 const market = repo !== undefined;
789798 const clone = copyField("connect-claude", `${env} claude --plugin-dir plugins/claude-code`, "Terminal agent command", "Copy command");
test/form-keeps-input.test.ts added +150
@@ -0,0 +1,150 @@
1 /**
2 * A refused form keeps what was typed (#13165): the shared helper
3 * (`src/web/form.ts`) re-renders values escaped, puts the message beside its
4 * field with focus on the first, and never echoes a secret. Proven through
5 * two existing forms: the profile and the password change.
6 */
7 import { afterAll, beforeAll, describe, 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 { serve, type Servers } from "../src/http/server.ts";
14 import { kept, refused, type Form } from "../src/web/form.ts";
15 import { signUpProven } from "./helpers/verified.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 describe("kept (the helper)", () => {
21 const form = new FormData() as unknown as Form;
22 form.set("name", "<b>x</b>");
23 form.set("pw", "hunter2");
24 form.set("note", "n");
25 const r = refused(form, { name: "Too odd.", pw: "Too short." });
26
27 test("keeps a typed value, sets the message, focuses the first", () => {
28 const o = kept(r, { label: "Name", name: "name", value: "old" });
29 expect(o).toMatchObject({ value: "<b>x</b>", error: "Too odd.", autofocus: true });
30 expect(kept(r, { label: "Note", name: "note" }).autofocus).toBeUndefined();
31 });
32 test("never echoes a secret", () => {
33 const o = kept(r, { label: "Pw", name: "pw", type: "password" });
34 expect(o.value).toBeUndefined();
35 expect(o.error).toBe("Too short.");
36 expect(kept(refused(form, {}), { label: "T", name: "pw", type: "password" }).value).toBeUndefined();
37 });
38 test("a secret-named text field is not echoed either", () => {
39 const f = new FormData() as unknown as Form;
40 f.set("api_token", "tok-123");
41 expect(kept(refused(f, {}), { label: "T", name: "api_token" }).value).toBeUndefined();
42 });
43 test("a camelCase secret is not echoed", () => {
44 const f = new FormData() as unknown as Form;
45 f.set("newPassword", "x");
46 f.set("apiKey", "y");
47 expect(kept(refused(f, {}), { label: "N", name: "newPassword" }).value).toBeUndefined();
48 expect(kept(refused(f, {}), { label: "A", name: "apiKey" }).value).toBeUndefined();
49 });
50 test("a non-secret name containing key is kept", () => {
51 const f = new FormData() as unknown as Form;
52 f.set("keywords", "a, b");
53 f.set("monkey", "see");
54 expect(kept(refused(f, {}), { label: "K", name: "keywords" }).value).toBe("a, b");
55 expect(kept(refused(f, {}), { label: "M", name: "monkey" }).value).toBe("see");
56 });
57 test("a select keeps the chosen option, a checkbox its state", () => {
58 const f = new FormData() as unknown as Form;
59 f.set("mode", "b");
60 f.set("on", "1");
61 const options = [
62 { value: "a", label: "A", selected: true },
63 { value: "b", label: "B" },
64 ];
65 const s = kept(refused(f, {}), { label: "M", name: "mode", type: "select", options });
66 expect(s.options?.map((c) => c.selected)).toEqual([false, true]);
67 expect(kept(refused(f, {}), { label: "O", name: "on", type: "checkbox" }).checked).toBe(true);
68 expect(kept(refused(f, {}), { label: "X", name: "off", type: "checkbox", checked: true }).checked).toBe(false);
69 });
70 test("no refusal leaves the options alone", () => {
71 const o = { label: "A", name: "a", value: "v" };
72 expect(kept(undefined, o)).toBe(o);
73 });
74 });
75
76 describe("two forms keep what was typed", () => {
77 let dataDir: string;
78 let app: App;
79 let servers: Servers;
80 let base = "";
81 let origin = "";
82 let cookie = "";
83
84 const post = (path: string, fields: Record<string, string>): Promise<Response> =>
85 fetch(`${base}${path}`, {
86 method: "POST",
87 redirect: "manual",
88 headers: { origin, cookie },
89 body: new URLSearchParams(fields),
90 });
91
92 beforeAll(async () => {
93 dataDir = await mkdtemp(join(tmpdir(), "forge-keeps-input-"));
94 app = createApp({ dataDir, port: 0 });
95 servers = await serve(app);
96 base = servers.url;
97 origin = new URL(base).origin;
98 const made = await signUpProven(app, { username: "kit", email: "[email protected]", password: "a-long-keeps-passphrase" });
99 if (!made.ok) throw new Error("sign-up failed");
100 cookie = `forge_session=${createSession(app.db, made.value.id).token}`;
101 });
102 afterAll(async () => {
103 servers.stop();
104 app.close();
105 await rm(dataDir, { recursive: true, force: true });
106 });
107
108 test("a refused profile keeps both values, escaped, message beside the field", async () => {
109 const res = await post("/settings", {
110 displayName: "<script>alert(1)</script>",
111 email: "not an email",
112 commitEmail: "noreply",
113 });
114 expect(res.status).toBe(422);
115 const html = await res.text();
116 expect(html).not.toContain("<script>alert(1)</script>");
117 expect(html).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
118 expect(html).toContain("not an email");
119 expect(html).toMatch(/id="f-email"[^>]*autofocus|autofocus[^>]*id="f-email"/);
120 expect(html).toMatch(/class="error" id="f-email-err"/);
121 // The commit-email choice survives the refusal rather than resetting.
122 expect(html).toMatch(/<option value="noreply"[^>]*selected/);
123 });
124
125 test("a refused profile keeps a commit-email choice that is not the stored one", async () => {
126 const res = await post("/settings", {
127 displayName: "Kit",
128 email: "not an email",
129 commitEmail: "account",
130 });
131 expect(res.status).toBe(422);
132 const html = await res.text();
133 expect(html).toMatch(/<option value="account"[^>]*selected/);
134 expect(html).not.toMatch(/<option value="noreply"[^>]*selected/);
135 });
136
137 test("a refused password change echoes no password", async () => {
138 const res = await post("/settings/password", {
139 current: "secret-current-1",
140 next: "secret-next-pass-22",
141 confirm: "secret-other-pass-33",
142 });
143 expect(res.status).toBe(422);
144 const html = await res.text();
145 expect(html).toContain("match");
146 for (const typed of ["secret-current-1", "secret-next-pass-22", "secret-other-pass-33"])
147 expect(html).not.toContain(typed);
148 expect(html).toMatch(/id="f-next"[^>]*autofocus|autofocus[^>]*id="f-next"/);
149 });
150 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs