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

A client's forge link can be revoked and re-issued from the client list, each a receipted action #14743

Merged opened this

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

Merged

torque/forge:torque/14518-a-client-s-forge-link-can-be-revoked-and → main 5 commits fork 3 threads · 3 unresolved

  • Merged. torque/14518-a-client-s-forge-link-can-be-revoked-and was merged into main as 2829c4f.

Review

Sign in to review this change.
12 files changed +251 −42
src/http/server.ts +2 −1
@@ -330,7 +330,7 @@ import { forgeName } from "../web/pages/forge-name.ts";
330330 import { claimFragmentPage, claimOptions, claimRenew, claimSubmit, welcomePage, welcomeSubmit } from "../web/pages/claim.ts";
331331 import { firstAdminOptions, firstAdminPage, firstAdminSubmit } from "../web/pages/first-admin.ts";
332332 import { familyPage } from "../web/pages/family.ts";
333 import { forgeLinkForm, forgeLinkRevoke, forgeLinkSubmit, forgeLinkUndo, forgeArchiveConfirm, forgeArchiveSubmit, forgeRestoreSubmit, forgeRemoveConfirm, forgeRemoveSubmit, forgeStopSubmit,
333 import { forgeLinkForm, forgeRevokeConfirm, forgeLinkRevoke, forgeLinkSubmit, forgeLinkUndo, forgeArchiveConfirm, forgeArchiveSubmit, forgeRestoreSubmit, forgeRemoveConfirm, forgeRemoveSubmit, forgeStopSubmit,
334334 forgeOwnCodeSubmit, forgeSizeSubmit, forgeSandboxSubmit, forgesPage, forgesCsv } from "../web/pages/forges.ts";
335335 import { billDownload } from "./api/forge_bill.ts";
336336 import { forgeRecoveryForm, forgeRecoverySubmit } from "../web/pages/forges.ts";
@@ -989,6 +989,7 @@ export function buildRouter(): Router<Handler> {
989989 router.add("POST", "/forges/:name/recovery-link", forgeRecoverySubmit);
990990 router.add("GET", "/forges/:name/bill", billDownload);
991991 router.add("POST", "/forges/:name/claim-link", forgeLinkSubmit);
992 router.add("GET", "/forges/:name/revoke-link", forgeRevokeConfirm);
992993 router.add("POST", "/forges/:name/revoke-link", forgeLinkRevoke);
993994 router.add("POST", "/forges/:name/undo-link", forgeLinkUndo);
994995 router.add("POST", "/forges/:name/stop", forgeStopSubmit);
src/spawn/manage.ts +6
@@ -56,6 +56,12 @@ export async function removeForge(app: App, name: string): Promise<Managed> {
5656 return { ok: true, says: `${name} is removed, with its data` };
5757 }
5858
59 /**
60 * One line for what ending a forge's link does, shown before the confirm (page and MCP, #14518).
61 */
62 export const revokePreview = (name: string): string =>
63 `This ends the link sent for ${name} now: anyone who opens it is told it was turned off. You can undo it for a minute, or send a new link after.`;
64
5965 /**
6066 * Take a child's unclaimed link back, or undo that within the minute: the
6167 * site admin's (callers check), receipted; the link's secret is in no event.
src/tui/screens/forges.ts +16 −2
@@ -19,7 +19,7 @@ import { diskWords } from "../../spawn/disk_mount.ts";
1919 import { archiveForge, archivedForges, destinationWords, restoreForge } from "../../spawn/archive.ts";
2020 import { writeClientsCsv } from "../../spawn/clients_csv.ts";
2121 import { claimedWords, keepWords } from "../../spawn/keep_words.ts";
22 import { changeLink, ownCode, removeForge, resizeForge, stopForge } from "../../spawn/manage.ts";
22 import { changeLink, revokePreview, ownCode, removeForge, resizeForge, stopForge } from "../../spawn/manage.ts";
2323 import { moveToCell } from "../../spawn/move_cell.ts";
2424 import { readOwnCode } from "../../spawn/own_code.ts";
2525 import type { App } from "../../app.ts";
@@ -146,7 +146,21 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
146146 title: act === "revoke" ? "End which link?" : "Bring back which link?",
147147 items,
148148 onPick: (ids) => {
149 if (ids[0] !== undefined) void changeLink(session.app, user.id, ids[0], act).then((done) => ctx.toast(done.says, done.ok ? "success" : "danger"));
149 const name = ids[0];
150 if (name === undefined) return;
151 const run = (): void => void changeLink(session.app, user.id, name, act).then((done) => ctx.toast(done.says, done.ok ? "success" : "danger"));
152 // Ending a link is confirmed with the page's one line (#14518); bringing it back is not.
153 if (act === "undo") return run();
154 ctx.push(
155 confirmScreen(ctx, screen, {
156 title: `End the link for ${name}?`,
157 body: [revokePreview(name)],
158 actions: [{ label: "Revoke" }, { label: "Keep it" }],
159 onChoose: (i) => {
160 if (i === 0) run();
161 },
162 }),
163 );
150164 },
151165 }),
152166 );
src/web/pages/claim.ts +11 −8
@@ -13,8 +13,8 @@
1313 * The GET only shows the form — a link unfurled in a chat app must not
1414 * spend itself — and the POST, same-origin, makes the account and burns the
1515 * link in one step. A link that is used or expired says which in one
16 * sentence and names who sent it (410); one that is revoked says it was withdrawn (404); one made
17 * up is a plain 404; a forge that was not spawned has no claim page at all.
16 * sentence and names who sent it (410); one that is revoked says it was turned off (410, no sender
17 * named); one made up is a plain 404; a forge that was not spawned has no claim page at all.
1818 *
1919 * Who keeps access is never silent. By default the spawner's account leaves
2020 * the organisation's Owners when the forge is claimed (the new owner can
@@ -110,6 +110,9 @@ function sender(user: User | undefined): string | undefined {
110110 return user === undefined ? undefined : user.displayName || user.username;
111111 }
112112
113 /** What a revoked link says to whoever opens it: no sender, no forge detail (#14518). */
114 export const LINK_TURNED_OFF = "This link was turned off. Ask the person who sent it for a new one.";
115
113116 function dead(
114117 ctx: Ctx,
115118 state: Exclude<ClaimState["state"], "ok">,
@@ -144,9 +147,9 @@ function dead(
144147 text: `Ask ${ask} to send you a new one.`,
145148 },
146149 revoked: {
147 status: 404,
148 title: "This link was withdrawn",
149 text: `The sender withdrew this link. Ask ${ask} to send you a new one.`,
150 status: 410,
151 title: "This link was turned off",
152 text: LINK_TURNED_OFF,
150153 },
151154 owned: {
152155 status: 410,
@@ -158,7 +161,7 @@ function dead(
158161 const mine: Partial<Record<typeof state, string>> = {
159162 unknown: "This link does not work any more. Start the forge again from the home page.",
160163 expired: "Start the forge again from the home page.",
161 revoked: "You withdrew this link. Start the forge again from the home page.",
164 revoked: "You turned this link off. Start the forge again from the home page.",
162165 };
163166 if (own) says.text = mine[state] ?? says.text;
164167 return page(
@@ -467,7 +470,7 @@ const LINK_REFUSED: Record<Exclude<ClaimState["state"], "ok">, string> = {
467470 unknown: "This link does not work any more.",
468471 used: "This link was already used.",
469472 expired: "This link has expired.",
470 revoked: "The sender withdrew this link. Ask them to send you a new one.",
473 revoked: LINK_TURNED_OFF,
471474 owned: "This forge already has an owner.",
472475 };
473476
@@ -487,7 +490,7 @@ async function options(ctx: Ctx): Promise<Response> {
487490 const spawned = await spawnedOrg(ctx.app);
488491 if (spawned === undefined) return refuse(404, LINK_REFUSED.unknown);
489492 const state = readClaim(ctx.app.db, spawned.org.id, str(data.token)).state;
490 if (state !== "ok") return refuse(state === "used" || state === "owned" || state === "expired" ? 410 : 404, LINK_REFUSED[state]);
493 if (state !== "ok") return refuse(state === "unknown" ? 404 : 410, LINK_REFUSED[state]);
491494 const username = str(data.username).trim();
492495 const bad = problems(ctx, spawned, username, emailGiven(ctx, str(data.email)));
493496 const first = bad.username ?? bad.email;
src/web/pages/forges.ts +27 −1
@@ -28,6 +28,7 @@ import { readOwnCode } from "../../spawn/own_code.ts";
2828 import { moveToCell } from "../../spawn/move_cell.ts";
2929 import { sealedAt } from "../../spawn/sealed.ts";
3030 import { countRefusals, mayReadRefusals } from "../../core/first_ask_refusals.ts";
31 import { revokePreview } from "../../spawn/manage.ts";
3132 import { clientsCsv } from "../../spawn/clients_csv.ts";
3233 import { claimLinkBody } from "./new-forge.ts";
3334 import { whenWords } from "./claim.ts";
@@ -155,7 +156,7 @@ export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = f
155156 : null}${r.link === null
156157 ? null
157158 : html`<span data-link="${r.link.state}">${badge(LINK_WORDS[r.link.state], { variant: "outline" as const })}</span>${state === "no" && daysLeft !== null ? html`<span data-days-left class="muted">${daysLeft}</span>` : null}${r.link.state === "open"
158 ? html`<form method="post" action="/forges/${r.name}/revoke-link" class="inline">${btn("Revoke", { size: "sm", title: "End this link now; you can undo for a minute" })}</form>`
159 ? btn("Revoke", { size: "sm", href: `/forges/${r.name}/revoke-link`, title: "See what it does, then confirm; you can undo for a minute" })
159160 : undoable(r.link, now)
160161 ? html`<form method="post" action="/forges/${r.name}/undo-link" class="inline">${btn("Undo", { size: "sm", title: "Bring the link back; possible for a minute after it ended" })}</form>`
161162 : null}`}${r.where.movable
@@ -362,6 +363,31 @@ export async function forgeLinkForm(ctx: Ctx): Promise<Response> {
362363 return response;
363364 }
364365
366 // GET /forges/:name/revoke-link — what ending the link does in one line and the one button that
367 // does it; nothing changes until it is pressed (#14518).
368 export async function forgeRevokeConfirm(ctx: Ctx): Promise<Response> {
369 const user = ctx.auth.user;
370 if (!user?.isAdmin) return notFoundPage(ctx);
371 const name = ctx.params["name"] ?? "";
372 if (!CHILD_NAME.test(name)) return notFoundPage(ctx);
373 const response = page({
374 ctx,
375 title: "End this link",
376 body: html`<div class="narrow-wide" data-forges>
377 ${pageHead(`End the link for ${name}`)}
378 <section class="settings-block">
379 <p data-preview>${revokePreview(name)}</p>
380 <form method="post" action="/forges/${name}/revoke-link" class="form-actions">
381 ${btn("Revoke", { variant: "primary", title: "End the link now" })}
382 ${btn("Keep it", { href: "/forges", variant: "outline" })}
383 </form>
384 </section>
385 </div>`,
386 });
387 response.headers.set("cache-control", "no-store");
388 return response;
389 }
390
365391 /** One line each for what was archived: where the copy is, and the way back. */
366392 function archivedSection(ctx: Ctx, archived: readonly ArchiveRecord[]): Html | null {
367393 const said = ctx.url.searchParams.get("archive");
test/claim-revoke.test.ts +46 −12
@@ -32,6 +32,7 @@ describe("revoking a forge link", () => {
3232 let rwToken = "";
3333 let aliceCookie = "";
3434 let bobCookie = "";
35 let bobId = "";
3536 const state = (name: string) => linkOf(kids[name]!.app.db)?.state;
3637 const orgOf = async (name: string) => (await spawnedOrg(kids[name]!.app))!.org.id;
3738 /** The page's button, as a browser posts it. */
@@ -60,6 +61,7 @@ describe("revoking a forge link", () => {
6061 aliceCookie = `forge_session=${createSession(parent.db, alice.id).token}`;
6162 const bob = await createUser(parent.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-long-claim-passphrase" });
6263 if (!bob.ok) throw new Error("bob");
64 bobId = bob.value.id;
6365 bobCookie = `forge_session=${createSession(parent.db, bob.value.id).token}`;
6466 const rw = createToken(parent.db, alice.id, "rw", "rw").token;
6567 rwToken = rw;
@@ -95,13 +97,13 @@ describe("revoking a forge link", () => {
9597 await rm(dir, { recursive: true, force: true });
9698 });
9799
98 test("revoke-then-use answers 404 in plain words and sets no session", async () => {
100 test("revoke-then-use answers 410 in plain words and sets no session", async () => {
99101 expect(state("one")).toBe("open");
100102 const done = await revoke("one", "revoke");
101103 expect(done.ok).toBe(true);
102104 expect(state("one")).toBe("ended");
103105 const res = await claim("one");
104 expect(res.status).toBe(404);
106 expect(res.status).toBe(410);
105107 expect(res.headers.get("set-cookie")).toBeNull();
106108 const form = { token: kids["one"]!.token, username: "x", email: "[email protected]" };
107109 const post = await fetch(`${kids["one"]!.servers.url}/claim`, {
@@ -110,12 +112,12 @@ describe("revoking a forge link", () => {
110112 body: new URLSearchParams({ ...form, ...(await passkeyFields(kids["one"]!.servers.url, "/claim/options", form).catch(() => ({}))) }),
111113 redirect: "manual",
112114 });
113 expect(post.status).toBe(404);
115 expect(post.status).toBe(410);
114116 expect(post.headers.get("set-cookie")).toBeNull();
115 expect(await post.text()).toContain("The sender withdrew this link");
117 expect(await post.text()).toContain("This link was turned off. Ask the person who sent it for a new one.");
116118 });
117119
118 test("the starter's own page says 'You withdrew this link'; the recipient's never does, nor the reverse", async () => {
120 test("the starter's own page says 'You turned this link off'; the recipient's never does, nor the reverse", async () => {
119121 // "one" is still revoked by the test above; the next test undoes it.
120122 const url = kids["one"]!.servers.url;
121123 const send = (path: string) =>
@@ -127,14 +129,14 @@ describe("revoking a forge link", () => {
127129 });
128130 const own = await send("/welcome");
129131 const ownText = await own.text();
130 expect(own.status).toBe(404);
132 expect(own.status).toBe(410);
131133 expect(own.headers.get("set-cookie")).toBeNull();
132 expect(ownText).toContain("You withdrew this link");
133 expect(ownText).not.toContain("The sender withdrew this link");
134 expect(ownText).toContain("You turned this link off");
135 expect(ownText).not.toContain("This link was turned off. Ask the person who sent it for a new one.");
134136 const theirs = await send("/claim");
135137 const theirText = await theirs.text();
136 expect(theirText).toContain("The sender withdrew this link");
137 expect(theirText).not.toContain("You withdrew this link");
138 expect(theirText).toContain("This link was turned off. Ask the person who sent it for a new one.");
139 expect(theirText).not.toContain("You turned this link off");
138140 });
139141
140142 test("a revoke is receipted, and undone within the minute", async () => {
@@ -217,7 +219,7 @@ describe("revoking a forge link", () => {
217219 const list = await (await fetch(`${parentServers.url}${where}`, { headers: { cookie: aliceCookie } })).text();
218220 expect(list).toContain("has ended. Undo is beside it");
219221 expect(list).toContain('action="/forges/one/undo-link"');
220 expect(list).not.toContain('action="/forges/one/revoke-link"');
222 expect(list).not.toContain(`href="/forges/one/revoke-link"`);
221223 // Leaving the receipt behind, the row still offers Undo for the minute.
222224 const plain = await (await fetch(`${parentServers.url}/forges`, { headers: { cookie: aliceCookie } })).text();
223225 expect(plain).toContain('action="/forges/one/undo-link"');
@@ -226,7 +228,7 @@ describe("revoking a forge link", () => {
226228 expect(back.headers.get("location")).toBe("/forges?link=restored&forge=one");
227229 const after = await (await fetch(`${parentServers.url}/forges`, { headers: { cookie: aliceCookie } })).text();
228230 expect(after).not.toContain('action="/forges/one/undo-link"');
229 expect(after).toContain('action="/forges/one/revoke-link"');
231 expect(after).toContain(`href="/forges/one/revoke-link"`);
230232 });
231233
232234 test("a receipt names only a forge in the list, in fixed words", async () => {
@@ -254,6 +256,38 @@ describe("revoking a forge link", () => {
254256 expect(state("one")).toBe("open");
255257 });
256258
259 test("dryRun never writes: not for undo, reveal or a non-admin, and a missing forge is not found", async () => {
260 const call = async (args: Record<string, unknown>, token = rwToken) => {
261 const res = await fetch(`${parentServers.url}/mcp`, {
262 method: "POST",
263 headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
264 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "claim_link", arguments: args } }),
265 });
266 const r = ((await res.json()) as any).result;
267 return { error: r.isError === true, text: r.content[0].text as string };
268 };
269 expect((await call({ name: "one", action: "revoke" })).error).toBe(false);
270 expect(state("one")).toBe("ended");
271 const undo = await call({ name: "one", action: "undo", dryRun: true });
272 expect(undo.error).toBe(false);
273 expect(undo.text).toContain("Nothing changed yet");
274 expect(state("one")).toBe("ended");
275 expect((await call({ name: "one", action: "undo" })).error).toBe(false);
276 expect(state("one")).toBe("open");
277 const bobToken = createToken(parent.db, bobId, "rw", "rw").token;
278 const refused = await call({ name: "one", action: "revoke", dryRun: true }, bobToken);
279 expect(refused.error).toBe(true);
280 expect(refused.text).toContain("only a site admin");
281 expect((await call({ name: "one", action: "revoke", dryRun: true }, bobToken)).text).toBe((await call({ name: "one", action: "revoke" }, bobToken)).text);
282 expect((await call({ name: "one", action: "undo", dryRun: true }, bobToken)).error).toBe(true);
283 expect(state("one")).toBe("open");
284 const reveal = await call({ name: "one", reveal: true, dryRun: true });
285 expect(reveal.text).toContain("Nothing changed yet");
286 const missing = await call({ name: "nobody", action: "revoke", dryRun: true });
287 expect(missing.error).toBe(true);
288 expect(missing.text).toContain("no child forge named nobody");
289 });
290
257291 test("the terminal's action ends and restores a link through the same code, and names a missing forge", async () => {
258292 const ended = await changeLink(parent, alice.id, "one", "revoke");
259293 expect(ended.ok).toBe(true);
test/stranger-words.test.ts +1 −1
@@ -139,7 +139,7 @@ describe("a stranger's way to their own forge", () => {
139139 screens.push(["/claim passkey note, unknown", await note(404, { ...who, token: "nope" })]);
140140 screens.push(["/claim, a passkey that failed", await submit(422, { ...who, challenge: "x", clientDataJSON: "x", attestationObject: "x" })]);
141141 expect(revokeClaim(db, org)).toBe(true);
142 await both("revoked", 404);
142 await both("revoked", 410);
143143 expect(restoreClaim(db, org)).toBe(true);
144144 as({ e: "2000-01-01T00:00:00.000Z" });
145145 await both("expired", 410);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs