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

A person who claimed with a passkey and loses the device has a way back in #13803

Merged opened this in answer to

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

Merged

torque/forge:torque/13796-a-person-who-claimed-with-a-passkey-and → main 10 commits fork 6 threads · 6 unresolved

  • Merged. torque/13796-a-person-who-claimed-with-a-passkey-and was merged into main as 5a1d7a4.

Review

Sign in to review this change.
19 files changed +489 −14
src/actions/forge_recovery.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * The way back for the owner of a forge this forge made, when the owner has lost their only
3 * passkey (#13796). A hosted forge sends no mail, so `/recover` on it cannot work; the account
4 * that sent the forge (or a site admin) mints a recovery link here and hands it over. The link is
5 * the way-back link of `core/edge_handover.ts`: a week, single use, stored as a hash, and opening
6 * it registers a new passkey and signs the owner in (`actions/verify.ts` `recoveryAccount`).
7 *
8 * Only a claimed forge has an owner to recover; an unclaimed one is sent a new claim link
9 * instead. The child records `account.way_back_minted` in its own events, so its owner can see
10 * that a link was made and by which forge's hand. Minting again replaces the link before it.
11 */
12
13 import { childDirOf, liveChildUrl, mayReissue, type SpawnError } from "./spawn.ts";
14 import type { App } from "../app.ts";
15 import { createApp } from "../app.ts";
16 import { HANDOVER_TTL_MS, issueHandover } from "../core/edge_handover.ts";
17 import { getUserById, isActive, type User } from "../core/users.ts";
18 import { RateLimiter } from "../core/ratelimit.ts";
19 import { err, ok, type Result } from "../kernel/result.ts";
20
21 export interface RecoveryPreview {
22 readonly name: string;
23 readonly owner: string;
24 readonly says: string;
25 }
26
27 export interface RecoveryLink extends RecoveryPreview {
28 readonly recoveryUrl: string;
29 readonly expiresAt: string;
30 }
31
32 type Refusal = SpawnError | { readonly kind: "not_found" };
33
34 /** The person who owns the forge: its first active human admin. */
35 function ownerOf(kid: App): User | undefined {
36 const rows = kid.db
37 .query<{ id: string }, []>(
38 "SELECT id FROM user WHERE is_admin = 1 AND is_agent = 0 AND kind = 'user' ORDER BY rowid",
39 )
40 .all();
41 for (const r of rows) {
42 const u = getUserById(kid.db, r.id);
43 if (u !== undefined && isActive(u)) return u;
44 }
45 return undefined;
46 }
47
48 const words = (name: string, owner: string): string =>
49 `A one-time link, good for 7 days, that signs in as ${owner}, the owner of ${name}; an earlier one stops working, and ${owner} can see it was made.`;
50
51 /** Links one account may make in an hour: it is a way into someone else's forge. */
52 export const RECOVERY_PER_HOUR = 5;
53 const limits = new WeakMap<App, RateLimiter>();
54 function tooMany(app: App, userId: string): boolean {
55 let limiter = limits.get(app);
56 if (limiter === undefined) {
57 limiter = new RateLimiter({ perMinute: RECOVERY_PER_HOUR, adminPerMinute: RECOVERY_PER_HOUR, enabled: true, windowMs: 3_600_000 });
58 limits.set(app, limiter);
59 }
60 return !limiter.take(userId, "rw").allowed;
61 }
62
63 async function withOwner<T>(
64 app: App,
65 actor: User | undefined,
66 name: string,
67 use: (kid: App, owner: User, by: User) => T,
68 ): Promise<Result<T, Refusal>> {
69 const allowed = await mayReissue(app, actor, name);
70 if (!allowed.ok) return allowed;
71 const child = allowed.value.child;
72 if (child === undefined || !child.done) return err({ kind: "not_found" });
73 const kid = createApp({ dataDir: childDirOf(app, child.bodyId) });
74 try {
75 const owner = ownerOf(kid);
76 if (owner === undefined)
77 return err({ kind: "refused", reason: "unclaimed", message: `${name} is not claimed yet: send a new claim link instead` });
78 return ok(use(kid, owner, allowed.value.user));
79 } finally {
80 kid.close();
81 }
82 }
83
84 /** What a recovery link would do, changing nothing. */
outdated

This records the event with actorId = the owner, though the sender made it. The audit trail attributes the action to the victim of the takeover. Use the sender as actor (payload already names them).

85 export async function previewRecovery(app: App, actor: User | undefined, name: string): Promise<Result<RecoveryPreview, Refusal>> {
86 return withOwner(app, actor, name, (_kid, owner) => ({ name, owner: owner.username, says: words(name, owner.username) }));
87 }
88
89 /** Mint (or replace) the owner's recovery link; shown once, by the caller. */
90 export async function mintRecovery(
91 app: App,
92 actor: User | undefined,
93 name: string,
94 now: number = Date.now(),
outdated

Non-null assertion on actor. Return the mayReissue user from withOwner and use its id; do not assert.

95 ): Promise<Result<RecoveryLink, Refusal>> {
96 const made = await withOwner(app, actor, name, (kid, owner, by) => {
97 if (tooMany(app, by.id))
98 return { limited: true as const };
99 const token = issueHandover(kid.db, owner.id, null, now);
100 // The sender is no account of the child's, so the event has no actor; the payload names them.
101 kid.bus.append({ kind: "account.way_back_minted", payload: { userId: owner.id, by: by.username, from: "parent" } });
102 app.bus.append({ kind: "forge.recovery_minted", actorId: by.id, payload: { name, owner: owner.username } });
103 return {
104 name,
105 owner: owner.username,
106 says: words(name, owner.username),
107 recoveryUrl: `${liveChildUrl(app, name).replace(/\/+$/, "")}/recover?token=${encodeURIComponent(token)}`,
108 expiresAt: new Date(now + HANDOVER_TTL_MS).toISOString(),
109 };
110 });
111 if (!made.ok) return made;
112 if ("limited" in made.value)
113 return err({ kind: "refused", reason: "rate_limited", message: "Too many recovery links just now; try again in an hour." });
114 return ok(made.value);
115 }
src/actions/spawn.ts +1 −1
@@ -850,7 +850,7 @@ export async function reissueClaim(
850850 }
851851
852852 /** Who may send a forge's link again: the account that made it, or a site admin. */
853 async function mayReissue(app: App, actor: User | undefined, name: string): Promise<Result<{ readonly user: User; readonly child: Child | undefined }, SpawnError>> {
853 export async function mayReissue(app: App, actor: User | undefined, name: string): Promise<Result<{ readonly user: User; readonly child: Child | undefined }, SpawnError>> {
854854 const user = requireUser(actor);
855855 if (!user.ok) return err({ kind: "unauthorized" });
856856 // The account that spawned the child may reveal its link again until it is
src/core/edge_handover.ts +1 −1
@@ -25,7 +25,7 @@ const secret = (): string =>
2525 export function issueHandover(
2626 db: Database,
2727 userId: string,
28 byId: string,
28 byId: string | null,
2929 now: number,
3030 ): string {
3131 const token = secret();
src/core/event_audience.ts +1
@@ -128,6 +128,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([
128128 "forge.own_code_off",
129129 "forge.rolled_back",
130130 "forge.claim_reissued",
131 "forge.recovery_minted",
131132 "forge.claim_revoked",
132133 "forge.claim_restored",
133134 "forge.claim_renewal_asked",
src/http/route_marks.ts +1
@@ -224,6 +224,7 @@ export const ROUTES: Readonly<Record<string, Mark>> = {
224224 "/forges/name/:name": "open",
225225 "/forges/:name/bill": "open",
226226 "/forges/:name/claim-link": "open",
227 "/forges/:name/recovery-link": "open",
227228 "/forges/:name/revoke-link": "admin",
228229 "/forges/:name/undo-link": "admin",
229230 "/forges/:name/stop": "admin",
src/http/server.ts +3
@@ -322,6 +322,7 @@ import { familyPage } from "../web/pages/family.ts";
322322 import { forgeLinkForm, forgeLinkRevoke, forgeLinkSubmit, forgeLinkUndo, forgeArchiveConfirm, forgeArchiveSubmit, forgeRestoreSubmit, forgeRemoveConfirm, forgeRemoveSubmit, forgeStopSubmit,
323323 forgeOwnCodeSubmit, forgeSandboxSubmit, forgesPage } from "../web/pages/forges.ts";
324324 import { billDownload } from "./api/forge_bill.ts";
325 import { forgeRecoveryForm, forgeRecoverySubmit } from "../web/pages/forges.ts";
325326 import { forgesRefusedPage } from "../web/pages/forges-refused.ts";
326327 import { forgeReachAllow, forgeReachLater, forgeReachRevoke } from "../web/pages/hosted-forges.ts";
327328 import { askAdminLater, askAdminSubmit } from "../web/studio/ask_admin.ts";
@@ -956,6 +957,8 @@ export function buildRouter(): Router<Handler> {
956957 router.add("GET", "/family", familyPage);
957958 router.add("GET", "/forges/name/:name", forgeName);
958959 router.add("GET", "/forges/:name/claim-link", forgeLinkForm);
960 router.add("GET", "/forges/:name/recovery-link", forgeRecoveryForm);
961 router.add("POST", "/forges/:name/recovery-link", forgeRecoverySubmit);
959962 router.add("GET", "/forges/:name/bill", billDownload);
960963 router.add("POST", "/forges/:name/claim-link", forgeLinkSubmit);
961964 router.add("POST", "/forges/:name/revoke-link", forgeLinkRevoke);
src/spawn/door.ts +20
@@ -6,6 +6,7 @@
66 * the caller says `false` — returns the plan and changes nothing.
77 */
88
9 import { mintRecovery, previewRecovery } from "../actions/forge_recovery.ts";
910 import { dropServed } from "./clients.ts";
1011 import { contributeAnswer, wantsToContribute } from "./contribute_words.ts";
1112 import { nameShapeVerdict } from "./name_verdict.ts";
@@ -533,3 +534,22 @@ export async function changeDoor(ctx: Ctx, user: User, name: string, act: "revok
533534 if (done.missing) return { status: 404, body: { error: "not_found", message: `no child forge named ${name}` } };
534535 return spawnWords({ kind: "refused", reason: "not_open", message: done.says });
535536 }
537
538 /** What a recovery link for a claimed forge's owner would do, changing nothing. */
539 export async function previewRecoveryDoor(ctx: Ctx, user: User, name: string): Promise<Door> {
540 const seen = await previewRecovery(ctx.app, user, name);
541 if (seen.ok) return { status: 200, body: { dryRun: true, ...seen.value } };
542 if (seen.error.kind === "not_found")
543 return { status: 404, body: { error: "not_found", message: `no child forge named ${name}` } };
544 return spawnWords(seen.error);
545 }
546
547 /** A recovery link for a claimed forge's owner who lost their passkey: same-origin, shown once. */
548 export async function recoveryDoor(ctx: Ctx, user: User, name: string): Promise<Door> {
549 if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return spawnWords({ kind: "cross_origin" });
550 const made = await mintRecovery(ctx.app, user, name);
551 if (made.ok) return { status: 201, body: { ...made.value } };
552 if (made.error.kind === "not_found")
553 return { status: 404, body: { error: "not_found", message: `no child forge named ${name}` } };
554 return spawnWords(made.error);
555 }
src/tui/screens/entries.ts +2 −1
@@ -56,7 +56,7 @@ import { entry as forgeReady } from "./forgeready.ts";
5656 import { entry as hostReach } from "./hostreach.ts";
5757 import { entry as homePins } from "./home_pins.ts";
5858 import { entry as claimStart } from "./claim_start.ts";
59 import { entry as claimLink } from "./claim_link.ts";
59 import { entry as claimLink, recoveryEntry as recoveryLink } from "./claim_link.ts";
6060 import { entry as invites } from "./invites.ts";
6161 import { entry as billingLinks } from "./billinglinks.ts";
6262 import { entry as planRow } from "./planrow.ts";
@@ -202,6 +202,7 @@ export const ENTRIES: readonly PaletteEntry[] = [
202202 cores,
203203 claimStart,
204204 claimLink,
205 recoveryLink,
205206 requests,
206207 bulk,
207208 subscriptions,
src/web/pages/claim.ts +3 −1
@@ -294,7 +294,9 @@ function accountForm(ctx: Ctx, action: "/claim" | "/welcome", values: Values, er
294294 hint: "Optional. It gets you back in if you lose your passkey.",
295295 ...(errors.email ? { error: errors.email } : {}),
296296 })
297 : null}
297 : ctx.app.config.parentUrl !== undefined
outdated

Principle 1: this repeats the /recover page's explanation on the first screen of the claim flow. One short clause is enough, and it needs a test.

298 ? html`<p class="muted small mb" data-no-mail>No email here: if you lose your passkey, whoever sent you this forge can make a recovery link.</p>`
299 : null}
298300 ${passkeyFields()}
299301 <div data-passkey="on" hidden>
300302 <p class="muted small mb">A passkey is your device's fingerprint, face or PIN. There is nothing to remember.</p>
src/web/pages/forges.ts +63 −1
@@ -15,7 +15,7 @@ import { notFoundPage, pageHead } from "../chrome.ts";
1515 import { html, type Html } from "../html.ts";
1616 import { page, redirect } from "../layout.ts";
1717 import { undoable } from "../../spawn/claim.ts";
18 import { changeDoor, previewDoor, reissueDoor } from "../../spawn/door.ts";
18 import { changeDoor, previewDoor, previewRecoveryDoor, recoveryDoor, reissueDoor } from "../../spawn/door.ts";
1919 import { readForm } from "../form.ts";
2020 import { badge, btn, row, time } from "../ui.ts";
2121 import { noRoom } from "../../spawn/door.ts";
@@ -138,6 +138,8 @@ export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = f
138138 ...(state === "yes" ? { tone: "success" as const } : { variant: "outline" as const }),
139139 })}${state === "no"
140140 ? btn(r.stage?.resend === true ? "Resend" : "Send a new link", { size: "sm", href: `/forges/${r.name}/claim-link`, title: "See who it is for and what stops working, then confirm" })
141 : null}${state === "yes" && r.made
142 ? btn("Recovery link", { size: "sm", href: `/forges/${r.name}/recovery-link`, title: "For an owner who lost their passkey: see what it does, then confirm" })
141143 : null}${r.link === null
142144 ? null
143145 : html`<span data-link="${r.link.state}">${badge(LINK_WORDS[r.link.state], { variant: "outline" as const })}</span>${r.link.state === "open"
@@ -602,3 +604,63 @@ export async function forgeOwnCodeSubmit(ctx: Ctx): Promise<Response> {
602604 dropServed(ctx.app);
603605 return redirect(`/forges?code=${done.ok ? want : "refused"}&forge=${encodeURIComponent(name)}#forge-code`);
604606 }
607
608 /* `/forges/:name/recovery-link`: the way back for a claimed owner who lost every passkey (#13796). A hosted
609 forge sends no mail, so the sender asks here: a preview first, and only the confirm mints the link, shown
610 once. Who may is the action's answer (`actions/forge_recovery.ts`). */
611 // GET — the preview; nothing is minted.
612 export async function forgeRecoveryForm(ctx: Ctx): Promise<Response> {
613 const user = ctx.auth.user;
614 if (user === undefined) return notFoundPage(ctx);
615 const name = ctx.params["name"] ?? "";
616 const seen = await previewRecoveryDoor(ctx, user, name);
617 const says = String(seen.body["says"] ?? seen.body["message"]);
618 const response = page(
619 {
620 ctx,
621 title: "A recovery link",
622 body: html`<div class="narrow-wide" data-forges>
623 ${pageHead(`A recovery link for ${name}`)}
624 <section class="settings-block">
625 <p data-preview>${says}</p>
626 ${seen.status < 400
627 ? html`<form method="post" action="/forges/${name}/recovery-link">${btn("Make the recovery link", { title: "Issue the link and end any earlier one" })}</form>`
628 : btn("Forges you sent", { href: "/forges", size: "sm" })}
629 </section>
630 </div>`,
631 },
632 seen.status,
633 );
634 response.headers.set("cache-control", "no-store");
635 return response;
636 }
637
638 // POST — mint it; the link is in this answer only.
639 export async function forgeRecoverySubmit(ctx: Ctx): Promise<Response> {
640 const user = ctx.auth.user;
641 if (user === undefined) return notFoundPage(ctx);
642 const form = await readForm(ctx, "rw");
643 if (form instanceof Response) return form;
644 const name = ctx.params["name"] ?? "";
645 const door = await recoveryDoor(ctx, user, name);
646 const link = door.body["recoveryUrl"];
647 const response = page(
648 {
649 ctx,
650 title: "A recovery link",
651 body: html`<div class="narrow-wide" data-forges>
652 ${pageHead(typeof link === "string" ? `A recovery link for ${name}` : `No recovery link for ${name}`)}
653 <section class="settings-block">
654 ${typeof link === "string"
655 ? html`<p>Hand this to ${String(door.body["owner"])} privately; it is not shown again.</p>
656 <p><code class="mono" id="recovery-link">${link}</code></p>`
657 : html`<p>${String(door.body["message"] ?? "")}</p>`}
658 <p class="mt">${btn("Forges you sent", { href: "/forges", size: "sm" })}</p>
659 </section>
660 </div>`,
661 },
662 door.status,
663 );
664 response.headers.set("cache-control", "no-store");
665 return response;
666 }
src/web/pages/passkeys.ts +21 −2
@@ -23,7 +23,7 @@ import { RateLimiter } from "../../core/ratelimit.ts";
2323 import { requestOf } from "../../core/requests.ts";
2424 import { rotateSession } from "../../auth/session_rotate.ts";
2525 import { LAST_WAY_IN, removeOwnPasskey } from "../../actions/passkeys.ts";
26 import { recoveryAccount, requestRecovery, spendRecoveryLink } from "../../actions/verify.ts";
26 import { mailConfigured, recoveryAccount, requestRecovery, spendRecoveryLink } from "../../actions/verify.ts";
2727 import { getUserById, isActive, MIN_PASSWORD } from "../../core/users.ts";
2828 import { accessLinkPerson, redeemAccessLink } from "../../actions/account_access.ts";
2929 import { CHANGE_PASSWORD_WORDS } from "../../actions/users.ts";
@@ -32,7 +32,7 @@ import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.t
3232 import { clientAddress, clientBucket } from "../../http/peer.ts";
3333 import { STRANGER_MAX } from "../../http/limits.ts";
3434 import { boundedBody, json, str } from "../../http/respond.ts";
35 import { CAME_FROM_ELSEWHERE, signInFirst } from "../chrome.ts";
35 import { CAME_FROM_ELSEWHERE, pageHead, signInFirst } from "../chrome.ts";
3636 import { field, readForm } from "../form.ts";
3737 import { html } from "../html.ts";
3838 import { flashTo, page, redirect } from "../layout.ts";
@@ -250,11 +250,29 @@ function recoverWait(ctx: Ctx, email: string): number | undefined {
250250
251251 const NOT_VALID = "This link has expired, been used, or is not valid. Ask for a new one.";
252252
253 /**
254 * What /recover says on a forge that sends no mail: the truth, never a form that cannot work
255 * (#13796). Only a forge another forge made has a sender to ask; a standalone one has its admins.
256 */
257 function noMailPage(ctx: Ctx, status = 200): Response {
258 const hosted = ctx.app.config.parentUrl !== undefined;
259 return page({
260 ctx,
261 title: "Recover your account",
262 body: html`${pageHead("Recover your account")}
outdated

This page shows whenever mail is unconfigured, including a standalone forge with no sender. There 'the person who sent you this forge' and 'their Forges page' are false, and the owner is told to ask someone who does not exist. Show the sender wording only on a hosted child; say what actually works otherwise. Also principle 1: the page explains the same thing in three paragraphs.

263 <p data-no-mail>This forge sends no mail, so it cannot email you a link.</p>
264 <p>${hosted
265 ? "Ask the person who sent you this forge for a recovery link, or add a passkey from a device that is still signed in."
266 : "Ask a site admin of this forge to help, or add a passkey from a device that is still signed in."}</p>`,
267 }, status);
268 }
269
253270 // GET /recover — the request form, or (with ?token=) the new-passkey step.
254271 export function recoverPage(ctx: Ctx): Response {
255272 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
256273 const render = (draw: () => Response): Response => timePhase(ctx.request, "render", draw);
257274 const token = ctx.url.searchParams.get("token");
275 if (token === null && !mailConfigured(ctx.app)) return render(() => noMailPage(ctx));
258276 if (token === null) {
259277 return render(() => page({
260278 ctx,
@@ -289,6 +307,7 @@ export function recoverPage(ctx: Ctx): Response {
289307 export async function recoverRequest(ctx: Ctx): Promise<Response> {
290308 const form = await readForm(ctx, undefined, STRANGER_MAX);
291309 if (form instanceof Response) return form;
310 if (!mailConfigured(ctx.app)) return noMailPage(ctx);
292311 const email = field(form, "email").trim().slice(0, 254);
293312 const wait = email === "" ? undefined : recoverWait(ctx, email);
294313 if (wait !== undefined) {
test/deadends.test.ts −4
@@ -93,10 +93,6 @@ const KNOWN: ReadonlySet<string> = new Set<string>([
9393 "wall /signin -> /signup (sign-in wall via /signup for a signed-in viewer)",
9494 "wall /signin -> /signup (403 for a signed-in viewer)",
9595 "anchor /signin -> /#yours",
96 // Product decision: the emailed recovery link is the only way back, and carries no return
97 // address; the form that asks for it cannot either.
98 'return-address /recover form "form" -> /recover drops the return address',
99 "return-address /recover form /recover drops the return address",
10096 ]);
10197
10298 const seen = new Map<string, string>();
test/forge-recovery.test.ts added +169
@@ -0,0 +1,169 @@
1 /**
2 * A claimed hosted forge whose owner lost their only passkey (#13796): /recover on a forge with
3 * no mail says so and shows no email form; the account that sent the forge mints a recovery link
4 * the owner can open; a stranger cannot; an unclaimed forge is refused.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { childDirOf } from "../src/actions/spawn.ts";
11 import { recoveryAccount, spendRecoveryLink } from "../src/actions/verify.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, getUserByName } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { headlessTerminal } from "../src/tui/term/terminal.ts";
19 import { firstBoot } from "../src/spawn/first-boot.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { settleApp } from "./helpers/tui.ts";
22
23 quietLogs();
24
25 describe("recovering a claimed forge without mail", () => {
26 let dir = "";
27 let parent: App;
28 let servers: Servers;
29 let child: App;
30 let kid: Servers;
31 let cookie = "";
32 let strangerCookie = "";
33 const asking = (path: string, who: string, post = false) =>
34 fetch(`${servers.url}${path}`, {
35 method: post ? "POST" : "GET",
36 headers: { cookie: who, origin: "https://forge.test" },
37 ...(post ? { body: new URLSearchParams({}) } : {}),
38 });
39
40 beforeAll(async () => {
41 dir = await mkdtemp(join(tmpdir(), "forge-recovery-"));
42 parent = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
43 const alice = await createUser(parent.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-claim-passphrase", isAdmin: true });
44 const bob = await createUser(parent.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-long-claim-passphrase" });
45 if (!alice.ok || !bob.ok) throw new Error("users");
46 cookie = `forge_session=${createSession(parent.db, alice.value.id).token}`;
47 strangerCookie = `forge_session=${createSession(parent.db, bob.value.id).token}`;
48 const token = createToken(parent.db, alice.value.id, "rw", "rw").token;
49 servers = await serve(parent);
50 for (const name of ["maria", "pending"]) {
51 const res = await fetch(`${servers.url}/api/v1/forges`, {
52 method: "POST",
53 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
54 body: JSON.stringify({ name, for: name, dryRun: false }),
55 });
56 if (res.status !== 201) throw new Error(`spawn ${res.status} ${await res.text()}`);
57 if (name === "maria") {
58 const body = (await res.json()) as { bodyId: string };
59 child = createApp({ dataDir: childDirOf(parent, body.bodyId), port: 0, parentUrl: "https://forge.test" });
60 await firstBoot(child);
61 kid = await serve(child);
62 const owner = await createUser(child.db, { origin: "seed", trusted: true, username: "claimer", email: "[email protected]", password: "a-long-claim-passphrase", isAdmin: true });
63 if (!owner.ok) throw new Error("owner");
64 }
65 }
66 }, 60_000);
67
68 afterAll(async () => {
69 kid.stop();
70 child.close();
71 servers.stop();
72 parent.close();
73 await rm(dir, { recursive: true, force: true });
74 });
75
76 test("a forge with no mail says so at /recover and asks for no email", async () => {
77 const res = await fetch(`${kid.url}/recover`);
78 const text = await res.text();
79 expect(res.status).toBe(200);
80 expect(text).toContain("sends no mail");
81 expect(text).not.toContain('name="email"');
82 const post = await fetch(`${kid.url}/recover`, { method: "POST", headers: { origin: kid.url }, body: new URLSearchParams({ email: "[email protected]" }) });
83 expect(await post.text()).toContain("sends no mail");
84 });
85
86 test("the preview changes nothing; a stranger and an unclaimed forge are refused", async () => {
87 const seen = await (await asking("/forges/maria/recovery-link", cookie)).text();
88 expect(seen).toContain("maria");
89 expect(seen).toContain("one-time link");
90 expect((await asking("/forges/maria/recovery-link", strangerCookie)).status).toBe(403);
91 expect((await fetch(`${servers.url}/forges/maria/recovery-link`)).status).toBeGreaterThanOrEqual(300);
92 expect(child.db.query("SELECT count(*) AS n FROM edge_handover").get()).toEqual({ n: 0 });
93 expect((await asking("/forges/maria/recovery-link", strangerCookie, true)).status).toBe(403);
94 const unclaimed = await asking("/forges/pending/recovery-link", cookie, true);
95 expect(unclaimed.status).toBe(409);
96 expect(await unclaimed.text()).toContain("not claimed yet");
97 });
98
99 test("the sender mints a link the owner can open, once", async () => {
100 const res = await asking("/forges/maria/recovery-link", cookie, true);
101 expect(res.status).toBe(201);
102 const text = await res.text();
103 const link = /id="recovery-link">([^<]+)</.exec(text)?.[1]?.replaceAll("&amp;", "&") ?? "";
104 expect(link).toContain("/recover?token=");
105 const token = new URL(link).searchParams.get("token") ?? "";
106 expect(recoveryAccount(child, token)?.username).toBe("claimer");
107 const page = await (await fetch(`${kid.url}/recover?token=${encodeURIComponent(token)}`)).text();
108 expect(page).toContain("Register a new passkey");
109 expect(spendRecoveryLink(child, token).ok).toBe(true);
110 expect(recoveryAccount(child, token)).toBeUndefined();
111 const n = (parent.db.query("SELECT count(*) AS n FROM event WHERE kind = 'forge.recovery_minted'").get() as { n: number }).n;
112 expect(n).toBe(1);
113 const actor = parent.db.query("SELECT actor_id FROM event WHERE kind = 'forge.recovery_minted'").get() as { actor_id: string };
114 expect(actor.actor_id).toBe(getUserByName(parent.db, "alice")!.id);
115 const said = child.db.query("SELECT payload FROM event WHERE kind = 'account.way_back_minted'").all() as { payload: string }[];
116 expect(said.length).toBe(1);
117 expect(JSON.parse(said[0]!.payload)).toMatchObject({ by: "alice", from: "parent" });
118 });
119
120 test("a hosted forge's no-mail page names the sender; a standalone one names an admin", async () => {
121 expect(await (await fetch(`${kid.url}/recover`)).text()).toContain("sent you this forge");
122 const alone = createApp({ dataDir: join(dir, "alone"), port: 0 });
123 const s = await serve(alone);
124 const text = await (await fetch(`${s.url}/recover`)).text();
125 s.stop();
126 alone.close();
127 expect(text).toContain("sends no mail");
128 expect(text).not.toContain("sent you this forge");
129 });
130
131 test("the terminal: a stranger mints nothing; the sender's confirm mints and shows the link once", async () => {
132 const drive = async (username: string, confirm: boolean) => {
133 const { app } = createForgeApp(parent, { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(parent.db, username)! }, { terminal: headlessTerminal(140, 32), exitHooks: false });
134 app.start();
135 const k = (key: string) => app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
136 app.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false });
137 for (const ch of "A recovery link") k(ch);
138 k("enter");
139 await settleApp(app);
140 for (const ch of "maria") k(ch);
141 k("enter");
142 await settleApp(app);
143 await Bun.sleep(200); // real-timer: the TUI action settles on a real worker
144 await settleApp(app);
145 const asked = app.screen.toText();
146 if (confirm && asked.includes("Make the recovery link")) {
147 k("enter");
148 await settleApp(app);
149 await Bun.sleep(200); // real-timer: the TUI action settles on a real worker
150 await settleApp(app);
151 }
152 return { asked, after: app.screen.toText() };
153 };
154 const before = (child.db.query("SELECT count(*) AS n FROM edge_handover").get() as { n: number }).n;
155 const stranger = await drive("bob", true);
156 expect(stranger.asked).not.toContain("Make the recovery link");
157 expect((child.db.query("SELECT count(*) AS n FROM edge_handover").get() as { n: number }).n).toBe(before);
158 const sender = await drive("alice", true);
159 expect(sender.asked).toContain("Make the recovery link");
160 expect(sender.after).toContain("/recover?token=");
161 expect((child.db.query("SELECT count(*) AS n FROM edge_handover").get() as { n: number }).n).toBeGreaterThan(before);
162 });
163
164 test("an account may make only a few links an hour", async () => {
165 let last = 0;
166 for (let i = 0; i < 6; i++) last = (await asking("/forges/maria/recovery-link", cookie, true)).status;
167 expect(last).toBe(409);
168 });
169 });
test/palette-roster.test.ts +2
@@ -186,6 +186,7 @@ test("a site-admin person is offered the whole roster", () => {
186186 ["subscriptions", "Crew subscriptions", "each account's budget and rest; wake one, set its budget, add or remove one"],
187187 ["crewkey", "Crew key", "what the crew runs on; add your own model key"],
188188 ["claim-link", "A fresh claim link for a forge I sent", "the old link stops; shown once"],
189 ["recovery-link", "A recovery link for a forge's owner who lost their passkey", "shown once; works once"],
189190 ["money", "Money", "this month's cost, revenue and gap, and the last 30 days"],
190191 ["app-templates", "App templates", "the repositories New app offers; mark or unmark one"],
191192 ["devices", "Devices", "LAN printers: model, state, supplies; declare or remove one"],
@@ -408,6 +409,7 @@ test("a member person is offered the signed-in roster without the admin entries"
408409 ["apps-crew", "What the crew is doing", "one plain sentence per app: who is on what"],
409410 ["claim-start", "Take an agent's work", "claim the repositories an agent started, from its one-time link"],
410411 ["claim-link", "A fresh claim link for a forge I sent", "the old link stops; shown once"],
412 ["recovery-link", "A recovery link for a forge's owner who lost their passkey", "shown once; works once"],
411413 ["bulk", "Bulk actions", "your last bulk actions; u undoes one inside its day"],
412414 ["bets", "Bets", "back, stop and finish a repository\'s bets"],
413415 ["origins", "Connected accounts", "the hosts your mirrors come from"],
test/passkey-recovery.test.ts +1 −1
@@ -173,7 +173,7 @@ describe("passkey recovery", () => {
173173 });
174174
175175 test("asking is limited per source, whatever the addresses", async () => {
176 const other = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-recover-src-")), port: 0 });
176 const other = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-recover-src-")), port: 0, mailer: async () => true });
177177 const more = await serve(other);
178178 try {
179179 const source: number[] = [];
test/refusals-lead-somewhere.test.ts +1
@@ -43,6 +43,7 @@ const TERMINAL: Readonly<Record<string, string>> = {
4343 "src/actions/migrate.ts\tThat address is inside the network, not a public": "It gives the reader's own way through in the same sentence: connect the host as an origin.",
4444 "src/actions/contribute_token.ts\tthis repository does not take outside contributions": "A door its owner chose to keep shut, said as a fact to a stranger with no account here.",
4545 "src/crew/bets.ts\tlower the share, or ask a site admin to raise your grant": "The way out itself, shared by the refusal and the card's note beside the share control; the grant is the owner's to raise.",
46 "src/web/pages/passkeys.ts\tAsk a site admin of this forge to help": "The reader is signed out and has no account to ask as; the sentence is the recovery page's only way through on a forge that sends no mail.",
4647 "src/actions/spawn.ts\t${name} is already claimed; ask its owner to": "The owner is of another forge (the hosted one), which this forge cannot ask on anyone's behalf.",
4748 };
4849

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs