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

The claim page holds up on a phone: a margin, a reload that keeps the code, a password for the asking #13786

Merged opened this

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

Merged

trevato/claim-journey-claim-page → main 1 commit

  • Merged. trevato/claim-journey-claim-page was merged into main as 40a2b7a.

Review

Sign in to review this change.
5 files changed +73 −13
src/web/pages/claim.ts +40 −10
@@ -216,7 +216,7 @@ function accessSentence(spawned: Spawned, spawner: User | undefined): string {
216216 function takeover(ctx: Ctx, spawned: Spawned, spawner: User | undefined): Html | null {
217217 if (spawner === undefined || founderToTake(ctx.app, spawned, spawner.username) === undefined)
218218 return null;
219 return html`<p class="mb" id="claim-takeover">Open it as ${spawner.username} and you will take over ${spawner.username}'s account on this forge, with everything already made under it.</p>`;
219 return html`<p class="mb" id="claim-takeover">Choose a username of your own. Choosing ${spawner.username} instead takes over the account ${spawner.username} set this forge up with, and everything already made under it.</p>`;
220220 }
221221
222222 function claimForm(
@@ -228,15 +228,16 @@ function claimForm(
228228 expiresAt?: string,
229229 own = false,
230230 ): Html {
231 // No bar surrounds this page, so the page column's own gutter keeps it off a phone's edge.
231232 if (own)
232 return html`<div class="narrow">
233 return html`<div class="shell"><div class="narrow">
233234 ${pageHead("Make your account")}
234235 <section class="settings-block">
235236 <p class="mb">Pick a username, then create your passkey. You will be the admin of this forge.</p>
236237 ${accountForm(ctx, "/welcome", values, errors)}
237238 </section>
238 </div>`;
239 return html`<div class="narrow">
239 </div></div>`;
240 return html`<div class="shell"><div class="narrow">
240241 ${pageHead("This forge is yours")}
241242 <section class="settings-block">
242243 <p class="mb">${spawner === undefined ? `${spawned.org.username} was made` : `${spawner.username} made ${spawned.org.username}`} for you. Your account will be its admin, so it can change everything here.</p>
@@ -250,7 +251,7 @@ function claimForm(
250251 ${takeover(ctx, spawned, spawner)}
251252 ${accountForm(ctx, "/claim", values, errors)}
252253 </section>
253 </div>`;
254 </div></div>`;
254255 }
255256
256257 /**
@@ -281,7 +282,7 @@ function accountForm(ctx: Ctx, action: "/claim" | "/welcome", values: Values, er
281282 required: true,
282283 autofocus: true,
283284 hint: "Letters, digits, dots and dashes.",
284 pattern: "[A-Za-z0-9][A-Za-z0-9._-]*",
285 pattern: "[A-Za-z0-9][A-Za-z0-9._\\-]*",
285286 ...(errors.username ? { error: errors.username } : {}),
286287 })}
287288 ${mailConfigured(ctx.app)
@@ -301,6 +302,7 @@ function accountForm(ctx: Ctx, action: "/claim" | "/welcome", values: Values, er
301302 ${passkeyNote("passkey-make-note", errors.passkey)}
302303 <div class="form-actions">
303304 <button type="button" id="passkey-make" class="btn" data-variant="primary" data-size="lg" data-options="${action}/options">Create your passkey</button>
305 <button type="button" id="passkey-skip" class="btn" data-variant="link">Use a password instead</button>
304306 </div>
305307 </div>
306308 <div data-passkey="off" ${errors.password ? html`data-keep` : null}>
@@ -331,10 +333,36 @@ const fragmentJs = /* js */ `
331333 (function () {
332334 var field = document.getElementById('claim-token');
333335 if (!field) return;
334 var code = location.hash.slice(1);
336 // The code leaves the address bar, so a reload (a phone does one whenever it brings the tab
337 // back) would lose it and the form would refuse a good link: this tab alone remembers it.
338 var kept = null;
339 try { kept = window.sessionStorage; } catch (e) {}
340 var code = location.hash.slice(1) || (kept && kept.getItem('claim-code')) || '';
335341 if (!code) return;
336342 field.value = code;
337 history.replaceState(null, '', location.pathname + location.search);
343 try { if (kept) kept.setItem('claim-code', code); } catch (e) {}
344 if (location.hash) history.replaceState(null, '', location.pathname + location.search);
345 })();
346 `;
347
348 /**
349 * "Use a password instead": the person who would rather not make a passkey (a borrowed laptop, a
350 * work phone) is not made to fail at one first. It brings out the same password field a browser
351 * without passkeys is shown.
352 */
353 const passwordInsteadJs = /* js */ `
354 (function () {
355 var skip = document.getElementById('passkey-skip');
356 if (!skip) return;
357 skip.addEventListener('click', function () {
358 var why = document.getElementById('password-why');
359 if (why) why.textContent = 'Choose a password. You can add a passkey later.';
360 var off = document.querySelectorAll('[data-passkey="off"]');
361 for (var i = 0; i < off.length; i++) { off[i].hidden = false; off[i].classList.add('mt'); }
362 skip.hidden = true;
363 var field = document.getElementById('f-password');
364 if (field) field.focus();
365 });
338366 })();
339367 `;
340368
@@ -353,6 +381,8 @@ async function fragmentPage(ctx: Ctx, own: boolean): Promise<Response> {
353381 // particular code: a stale or made-up code only ever meets "unknown" on the POST.
354382 const link = linkOf(ctx.app.db);
355383 if (!own && link?.state === "open" && isBrowserOpen(ctx.request)) noteOpened(ctx.app.db);
384 // Back, or the link opened again, after making the forge yours: you are already in.
385 if (link?.state === "used" && ctx.auth.user !== undefined) return redirect("/");
356386 if (link !== null && link.state !== "open")
357387 return dead(
358388 ctx,
@@ -365,7 +395,7 @@ async function fragmentPage(ctx: Ctx, own: boolean): Promise<Response> {
365395 ctx,
366396 title: own ? "Make your account" : "This forge is yours",
367397 body: claimForm(ctx, spawned, spawner, {}, {}, link?.expiresAt, own),
368 scriptJs: fragmentJs + passkeyJs,
398 scriptJs: fragmentJs + passkeyJs + passwordInsteadJs,
369399 bare: true,
370400 });
371401 notePhase(ctx.request, "render", performance.now() - rendering);
@@ -512,7 +542,7 @@ async function submit(ctx: Ctx, own: boolean): Promise<Response> {
512542 ctx,
513543 title: own ? "Make your account" : "This forge is yours",
514544 body: claimForm(ctx, spawned, spawner, values, e, linkOf(ctx.app.db)?.expiresAt, own),
515 scriptJs: fragmentJs + passkeyJs,
545 scriptJs: fragmentJs + passkeyJs + passwordInsteadJs,
516546 bare: true,
517547 },
518548 422,
src/web/pages/start_claim.ts +1 −1
@@ -53,7 +53,7 @@ export function startClaimPage(ctx: Ctx, errors: { username?: string; password?:
5353 </form>`
5454 : html`<p><a href="/signin?next=${encodeURIComponent(here)}">Sign in</a> to take it${mayMakeAccount(ctx) ? ", or make an account:" : "."}</p>
5555 ${!mayMakeAccount(ctx) ? null : html`<form method="post" action="${here}/account" class="stack">
56 ${formField({ label: "Username", name: "username", autocomplete: "username", required: true, pattern: "[A-Za-z0-9][A-Za-z0-9._-]*", ...(errors.username ? { error: errors.username } : {}) })}
56 ${formField({ label: "Username", name: "username", autocomplete: "username", required: true, pattern: "[A-Za-z0-9][A-Za-z0-9._\\-]*", ...(errors.username ? { error: errors.username } : {}) })}
5757 ${formField({ label: "Email", name: "email", type: "email", autocomplete: "email", hint: "Optional.", ...(errors.email ? { error: errors.email } : {}) })}
5858 ${formField({ label: "Password", name: "password", type: "password", autocomplete: "new-password", required: true, minlength: 12, hint: "At least 12 characters.", ...(errors.password ? { error: errors.password } : {}) })}
5959 ${btn("Make an account and take it", { variant: "primary", label: "Make an account and take it" })}
test/claim-access-sentence.test.ts +1 −1
@@ -135,7 +135,7 @@ describe("the claim page's access sentence", () => {
135135 // Asked for a new link by name, and offered their account here, by name, to take over.
136136 expect(text).toContain("ask founder to send you a new one");
137137 expect(text).toContain(
138 "Open it as founder and you will take over founder's account on this forge, with everything already made under it.",
138 "Choose a username of your own. Choosing founder instead takes over the account founder set this forge up with, and everything already made under it.",
139139 );
140140 });
141141 });
test/claim-page-words.test.ts +30
@@ -9,6 +9,7 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { childDirOf } from "../src/actions/spawn.ts";
1111 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
1213 import { createToken } from "../src/core/tokens.ts";
1314 import { createUser } from "../src/core/users.ts";
1415 import { serve, type Servers } from "../src/http/server.ts";
@@ -80,6 +81,22 @@ describe("the claim page in plain words", () => {
8081 expect(html).toContain("alice");
8182 });
8283
84 test("the form holds up on a phone: a username rule the browser can read, a reload that keeps the code, a password for the asking", async () => {
85 const html = await (await get()).text();
86 const pattern = /name="username"[^>]*pattern="([^"]+)"/s.exec(html)?.[1] ?? "";
87 // Browsers compile a pattern with the v flag, where a bare "-" in a class is an error.
88 const rule = new RegExp(`^(?:${pattern})$`, "v");
89 expect(rule.test("maria-b.2")).toBe(true);
90 expect(rule.test("Maria B!")).toBe(false);
91 const src = /<script src="(\/assets\/page-[^"]+)"/.exec(html)?.[1] ?? "";
92 const js = await (await fetch(`${childServers.url}${src}`)).text();
93 expect(js).toContain("sessionStorage");
94 expect(js).toContain("getItem('claim-code')");
95 expect(js).toContain("passkey-skip");
96 expect(html).toContain('id="passkey-skip"');
97 expect(html).toContain("Use a password instead");
98 });
99
83100 test("an expired link answers 410: one sentence, and who sent it", async () => {
84101 setStored({ e: new Date(Date.now() - 3_600_000).toISOString() });
85102 for (const res of [
@@ -106,6 +123,19 @@ describe("the claim page in plain words", () => {
106123 expect(text).not.toMatch(/token|\b4\d\d\b/i);
107124 });
108125
126 test("the person who used the link and is signed in is sent home, not told to sign in", async () => {
127 setStored({ e: new Date(Date.now() + 3_600_000).toISOString(), u: new Date().toISOString() });
128 const made = await createUser(child.db, {
129 origin: "seed", trusted: true, username: "maria-in", email: "[email protected]", password: "a-long-claim-passphrase",
130 });
131 if (!made.ok) throw new Error("user");
132 const cookie = `forge_session=${createSession(child.db, made.value.id).token}`;
133 const res = await fetch(`${childServers.url}/claim`, { headers: { cookie }, redirect: "manual" });
134 expect(res.status).toBe(303);
135 expect(res.headers.get("location")).toBe("/");
136 expect((await get()).status).toBe(410);
137 });
138
109139 test("a made-up code still only meets the not-a-forge-link answer", async () => {
110140 const res = await fetch(`${childServers.url}/claim`, {
111141 method: "POST", headers: { origin: childServers.url }, body: new URLSearchParams({ token: "x".repeat(43) }),
test/spawn-founder-name.test.ts +1 −1
@@ -204,7 +204,7 @@ describe("a child's founder holds the spawner's name", () => {
204204 const kid = await child("nia", false);
205205 const page = await (await fetch(`${kid.servers.url}/claim`)).text();
206206 expect(page).toContain('id="claim-takeover"');
207 expect(page).toContain("Open it as alice and you will take over alice's account on this forge");
207 expect(page).toContain("Choosing alice instead takes over the account alice set this forge up with");
208208 // Where it does not apply (the spawner keeps access), the page makes no such promise.
209209 const kept = await child("ona", true);
210210 expect(await (await fetch(`${kept.servers.url}/claim`)).text()).not.toContain('id="claim-takeover"');

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs