Public: anyone can read this; the crew can change it.
A forge made for a client can be sent again: a fresh link replaces the old one and the old one stops working #13181
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/13166-a-forge-made-for-a-client-can-be-sent-ag → main 9 commits fork
12 files
changed +423
−81
docs/features/forge-link-states.md +6 −2
| @@ -18,12 +18,16 @@ words for each forge sent, read from what is already kept: | ||
| 18 | 18 | |
| 19 | 19 | ## Resend |
| 20 | 20 | |
| 21 | The button on every unclaimed row says **Send a new link**: it opens a preview (who it is for, what stops working), and only its confirm issues the link and ends the old one; each issue writes a `forge.claim_reissued` event naming the forge and whom it was for. The API takes `{ "dryRun": true }` on the same route, and MCP `claim_link` without `reveal` returns the same preview. | |
| 22 | ||
| 21 | 23 | A link unopened for three days reads "Not opened in 3 days", and the page's |
| 22 | button says **Resend** (it posts to `/forges/<name>/claim-link`, the same as | |
| 23 | "Send a fresh link": a new link, the old one stops working). In MCP, the row's | |
| 24 | button says **Resend** (it opens `/forges/<name>/claim-link`, the same preview as | |
| 25 | "Send a new link"; its confirm issues the new link and the old one stops working). In MCP, the row's | |
| 24 | 26 | `stage.resend` is true; the action is MCP tool `claim_link` with the forge's |
| 25 | 27 | name. A claimed forge is never marked. |
| 26 | 28 | |
| 29 | In the terminal, **Forges you sent** has `n` (an admin's): pick an unclaimed forge, read the same preview, and choose "Send a new link" to confirm; the palette's "A fresh claim link for a forge I sent" asks the name and shows the same preview. Both go through `previewDoor` and `reissueDoor`, so who may is the page's rule. Tested in `test/forge-link-reissue.test.ts`. | |
| 30 | ||
| 27 | 31 | ## Left out |
| 28 | 32 | |
| 29 | 33 | - The first tell's time: the heartbeat carries only the latest tell. |
src/actions/spawn.ts +38 −7
| @@ -774,18 +774,49 @@ export async function reissueClaim( | ||
| 774 | 774 | deps: { readonly request: Request; readonly url: URL }, |
| 775 | 775 | ): Promise<Result<{ readonly name: string; readonly claimUrl: string }, SpawnError | { readonly kind: "not_found" }>> { |
| 776 | 776 | if (crossOrigin(deps.request, deps.url, app.log)) return err({ kind: "cross_origin" }); |
| 777 | const allowed = await mayReissue(app, actor, name); | |
| 778 | if (!allowed.ok) return allowed; | |
| 779 | const { user, child } = allowed.value; | |
| 780 | const made = await reissueClaimFor(app, name); | |
| 781 | if (made.ok) | |
| 782 | app.bus.append({ kind: "forge.claim_reissued", actorId: user.id, payload: { name, for: child?.for ?? null } }); | |
| 783 | return made; | |
| 784 | } | |
| 785 | ||
| 786 | /** Who may send a forge's link again: the account that made it, or a site admin. */ | |
| 787 | async function mayReissue(app: App, actor: User | undefined, name: string): Promise<Result<{ readonly user: User; readonly child: Child | undefined }, SpawnError>> { | |
| 777 | 788 | const user = requireUser(actor); |
| 778 | 789 | if (!user.ok) return err({ kind: "unauthorized" }); |
| 779 | 790 | // The account that spawned the child may reveal its link again until it is |
| 780 | 791 | // claimed (#12105), agent or person; so may a site admin. |
| 781 | if (!user.value.isAdmin) { | |
| 782 | const ledger = /^[a-z0-9-]{1,39}$/.test(name) ? await readLedger(app, name) : undefined; | |
| 783 | if (ledger === undefined || ledger.ownerId === undefined || ledger.ownerId !== user.value.id) | |
| 784 | return err({ kind: "forbidden" }); | |
| 792 | const child = /^[a-z0-9-]{1,39}$/.test(name) ? await childNamed(app, name) : undefined; | |
| 793 | if (!user.value.isAdmin && (child === undefined || child.ownerId === undefined || child.ownerId !== user.value.id)) | |
| 794 | return err({ kind: "forbidden" }); | |
| 795 | return ok({ user: user.value, child }); | |
| 796 | } | |
| 797 | ||
| 798 | /** What sending a new link would do, changing nothing: who it is for and what stops working. */ | |
| 799 | export async function previewReissue( | |
| 800 | app: App, | |
| 801 | actor: User | undefined, | |
| 802 | name: string, | |
| 803 | ): Promise<Result<{ readonly name: string; readonly for: string | null; readonly says: string }, SpawnError | { readonly kind: "not_found" }>> { | |
| 804 | const allowed = await mayReissue(app, actor, name); | |
| 805 | if (!allowed.ok) return allowed; | |
| 806 | const child = allowed.value.child; | |
| 807 | if (child === undefined || !child.done) return err({ kind: "not_found" }); | |
| 808 | const kid = createApp({ dataDir: childDirOf(app, child.bodyId) }); | |
| 809 | try { | |
| 810 | if (hasAdmin(kid.db)) | |
| 811 | return err({ kind: "refused", reason: "claimed", message: `${name} is already claimed; ask its owner to invite you` }); | |
| 812 | } finally { | |
| 813 | kid.close(); | |
| 785 | 814 | } |
| 786 | const made = await reissueClaimFor(app, name); | |
| 787 | if (made.ok) app.bus.append({ kind: "forge.claim_reissued", actorId: user.value.id, payload: { name } }); | |
| 788 | return made; | |
| 815 | return ok({ | |
| 816 | name, | |
| 817 | for: child.for, | |
| 818 | says: `A new link for ${child.for ?? name}. The link sent earlier stops working at once; the new one is shown once and works once.`, | |
| 819 | }); | |
| 789 | 820 | } |
| 790 | 821 | |
| 791 | 822 | /** |
src/http/api/forges.ts +16 −5
| @@ -12,7 +12,7 @@ import { usdWords } from "../../spawn/credit.ts"; | ||
| 12 | 12 | import { fundingOf, fundingWords, refreshFunding } from "../../spawn/funding.ts"; |
| 13 | 13 | import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts"; |
| 14 | 14 | import { clientRows, listed } from "../../spawn/clients.ts"; |
| 15 | import { reissueDoor, spawnDoor } from "../../spawn/door.ts"; | |
| 15 | import { previewDoor, reissueDoor, spawnDoor } from "../../spawn/door.ts"; | |
| 16 | 16 | import { checkMove } from "../../spawn/move_check.ts"; |
| 17 | 17 | import { moveToCell } from "../../spawn/move_cell.ts"; |
| 18 | 18 | import { sizesView } from "../../spawn/sizes.ts"; |
| @@ -23,7 +23,10 @@ import { holds, weakEtag } from "../etag.ts"; | ||
| 23 | 23 | import { apiError, body, forbidden, json, requireScope } from "../respond.ts"; |
| 24 | 24 | import type { Router } from "../router.ts"; |
| 25 | 25 | |
| 26 | /** A table any page or agent may read: the same JSON for everyone, so an ETag and five minutes' cache. */ | |
| 26 | /** | |
| 27 | * A table any page or agent may read: the same JSON for everyone, so an ETag and five minutes' | |
| 28 | * cache. | |
| 29 | */ | |
| 27 | 30 | function publicTable(ctx: Ctx, phase: string, view: () => unknown): Response { |
| 28 | 31 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 29 | 32 | const text = timePhase(ctx.request, phase, () => JSON.stringify(view())); |
| @@ -63,7 +66,8 @@ export function forgeRoutes(router: Router<Handler>): void { | ||
| 63 | 66 | if (denied) return denied; |
| 64 | 67 | if (!ctx.auth.user?.isAdmin) return forbidden(); |
| 65 | 68 | const items = await timePhaseAsync(ctx.request, "read", async () => { |
| 66 | // The row, and beside it what the list always carried: which template a child came from, where it is placed. | |
| 69 | // The row, and beside it what the list always carried: which template a child came from, | |
| 70 | // where it is placed. | |
| 67 | 71 | const [rows, children] = await Promise.all([clientRows(ctx.app), listChildren(ctx.app)]); |
| 68 | 72 | const kept = new Map(children.map((c) => [c.name, c])); |
| 69 | 73 | return rows.map((row) => { |
| @@ -93,7 +97,8 @@ export function forgeRoutes(router: Router<Handler>): void { | ||
| 93 | 97 | return json(door.body, door.status); |
| 94 | 98 | }); |
| 95 | 99 | |
| 96 | // The dollars this forge lends a child on its own model credential (#10484): a site admin sets the cap. | |
| 100 | // The dollars this forge lends a child on its own model credential (#10484): a site admin sets | |
| 101 | // the cap. | |
| 97 | 102 | router.add("PUT", "/api/v1/forges/:name/credit", async (ctx) => { |
| 98 | 103 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return forbidden(); |
| 99 | 104 | const denied = requireScope(ctx, "rw"); |
| @@ -153,7 +158,13 @@ export function forgeRoutes(router: Router<Handler>): void { | ||
| 153 | 158 | router.add("POST", "/api/v1/forges/:name/claim-link", async (ctx) => { |
| 154 | 159 | const denied = requireScope(ctx, "rw"); |
| 155 | 160 | if (denied) return denied; |
| 156 | const door = await reissueDoor(ctx, ctx.auth.user!, ctx.params["name"] ?? ""); | |
| 161 | const name = ctx.params["name"] ?? ""; | |
| 162 | // `dryRun: true` says who it is for and what stops working, and changes nothing. | |
| 163 | if ((await body(ctx.request))["dryRun"] === true) { | |
| 164 | const seen = await previewDoor(ctx, ctx.auth.user!, name); | |
| 165 | return json(seen.body, seen.status); | |
| 166 | } | |
| 167 | const door = await reissueDoor(ctx, ctx.auth.user!, name); | |
| 157 | 168 | return json(door.body, door.status); |
| 158 | 169 | }); |
| 159 | 170 | } |
src/http/mcp/tools/claim_link.ts +6 −3
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import { childNamed } from "../../../actions/spawn.ts"; |
| 2 | 2 | import { firstScreenLine } from "../../../core/next-steps.ts"; |
| 3 | import { changeDoor, reissueDoor } from "../../../spawn/door.ts"; | |
| 3 | import { changeDoor, previewDoor, reissueDoor } from "../../../spawn/door.ts"; | |
| 4 | 4 | import { good, bad, type Tool, str, REVEAL_ARG, LINK_KEPT, LINK_REVEALED } from "../shared.ts"; |
| 5 | 5 | |
| 6 | 6 | export const tool: Tool = { |
| @@ -23,8 +23,11 @@ export const tool: Tool = { | ||
| 23 | 23 | const done = await changeDoor(ctx, user, str(args["name"]), action); |
| 24 | 24 | return done.status >= 400 ? bad(String(done.body["error"]), String(done.body["message"])) : good(done.body); |
| 25 | 25 | } |
| 26 | if (args["reveal"] !== true) | |
| 27 | return good({ says: `Nothing changed. ${LINK_KEPT}`, reissued: false }); | |
| 26 | if (args["reveal"] !== true) { | |
| 27 | const seen = await previewDoor(ctx, user, str(args["name"])); | |
| 28 | if (seen.status < 400) return good({ ...seen.body, says: `${String(seen.body["says"])} Nothing changed yet. ${LINK_KEPT}`, reissued: false }); | |
| 29 | return bad(String(seen.body["error"]), String(seen.body["message"])); | |
| 30 | } | |
| 28 | 31 | const door = await reissueDoor(ctx, user, str(args["name"])); |
| 29 | 32 | if (door.status >= 400) |
| 30 | 33 | return bad(String(door.body["error"]), String(door.body["message"])); |
src/spawn/door.ts +18 −1
| @@ -12,7 +12,15 @@ import { nameShapeVerdict } from "./name_verdict.ts"; | ||
| 12 | 12 | import { linkRequestVisitor } from "../perf/visitor_link.ts"; |
| 13 | 13 | import { startWatch, probeOf, type Probe } from "./live.ts"; |
| 14 | 14 | import { firstProof, reachWords, settleChild } from "./reach.ts"; |
| 15 | import { forgeNameVerdict, founderClash, reissueClaim, spawnForge, takenReason, type SpawnError } from "../actions/spawn.ts"; | |
| 15 | import { | |
| 16 | forgeNameVerdict, | |
| 17 | founderClash, | |
| 18 | previewReissue, | |
| 19 | reissueClaim, | |
| 20 | spawnForge, | |
| 21 | takenReason, | |
| 22 | type SpawnError, | |
| 23 | } from "../actions/spawn.ts"; | |
| 16 | 24 | import type { App } from "../app.ts"; |
| 17 | 25 | import { maxChildren } from "../core/capacity.ts"; |
| 18 | 26 | import { getAgentByName } from "../core/agents.ts"; |
| @@ -446,6 +454,15 @@ export async function reissueDoor(ctx: Ctx, user: User, name: string): Promise<D | ||
| 446 | 454 | return spawnWords(made.error); |
| 447 | 455 | } |
| 448 | 456 | |
| 457 | /** What a new claim link would do (who for, what stops working), changing nothing. */ | |
| 458 | export async function previewDoor(ctx: Ctx, user: User, name: string): Promise<Door> { | |
| 459 | const seen = await previewReissue(ctx.app, user, name); | |
| 460 | if (seen.ok) return { status: 200, body: { dryRun: true, ...seen.value } }; | |
| 461 | if (seen.error.kind === "not_found") | |
| 462 | return { status: 404, body: { error: "not_found", message: `no child forge named ${name}` } }; | |
| 463 | return spawnWords(seen.error); | |
| 464 | } | |
| 465 | ||
| 449 | 466 | /** Take a child's unclaimed link back, or undo that within the minute: an admin's, same-origin. */ |
| 450 | 467 | export async function changeDoor(ctx: Ctx, user: User, name: string, act: "revoke" | "undo"): Promise<Door> { |
| 451 | 468 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return spawnWords({ kind: "cross_origin" }); |
src/tui/screens/claim_link.ts +51 −27
| @@ -1,41 +1,65 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * A fresh claim link for a forge you sent and nobody has claimed yet (#12105), in the |
| 3 | * terminal: what the page's "Send a fresh link" does. The name is asked, the door is the | |
| 4 | * page's (`reissueDoor`: the account that spawned it, or an admin; the old link stops), | |
| 5 | * and the new link is shown once. | |
| 3 | * terminal: what the page's "Send a new link" does. The name is asked, the preview is the | |
| 4 | * page's (`previewDoor`), and only its confirm calls `reissueDoor` (the account that spawned it, | |
| 5 | * or an admin; the old link stops); the new link is shown once. | |
| 6 | 6 | */ |
| 7 | import { reissueDoor } from "../../spawn/door.ts"; | |
| 7 | import { previewDoor, reissueDoor } from "../../spawn/door.ts"; | |
| 8 | 8 | import type { Ctx, Screen } from "../app/app.ts"; |
| 9 | 9 | import type { Session } from "../session.ts"; |
| 10 | import { blank, linkScreen, promptScreen, runAsync } from "./common.ts"; | |
| 10 | import { blank, confirmScreen, linkScreen, promptScreen, runAsync } from "./common.ts"; | |
| 11 | 11 | import type { PaletteEntry } from "./entries.ts"; |
| 12 | 12 | |
| 13 | 13 | const NAME = /^[a-z0-9-]{1,39}$/; |
| 14 | 14 | |
| 15 | export function claimLinkScreen(f: Session, ctx: Ctx): Screen { | |
| 16 | return promptScreen(ctx, blank("A fresh claim link"), { | |
| 17 | title: "A fresh claim link", | |
| 18 | label: "the forge's name", | |
| 19 | hint: "the old link stops working", | |
| 20 | onSubmit: (typed) => { | |
| 21 | const name = typed.trim().toLowerCase(); | |
| 22 | const user = f.user; | |
| 23 | if (user === undefined || !NAME.test(name)) return "a forge name is letters, digits and dashes"; | |
| 24 | return Promise.resolve().then(() => | |
| 25 | runAsync(ctx, async () => { | |
| 26 | const url = new URL(f.app.config.url ?? `http://${f.app.config.host ?? "localhost"}`); | |
| 27 | const made = await reissueDoor( | |
| 28 | { app: f.app, request: new Request(url.href, { method: "POST" }), url, params: {}, auth: { user, scope: undefined, via: "none" as const }, theme: undefined }, | |
| 29 | user, | |
| 30 | name, | |
| 31 | ); | |
| 32 | const link = made.body["claimUrl"]; | |
| 33 | if (typeof link !== "string") return ctx.toast(String(made.body["message"] ?? "no fresh link"), "danger"); | |
| 34 | ctx.replace(linkScreen(ctx, link, undefined, { qr: true })); | |
| 35 | }), | |
| 36 | ); | |
| 15 | /** The page's request context for the door: the terminal is same-origin with itself. */ | |
| 16 | function doorCtx(f: Session, user: NonNullable<Session["user"]>) { | |
| 17 | const url = new URL(f.app.config.url ?? `http://${f.app.config.host ?? "localhost"}`); | |
| 18 | return { app: f.app, request: new Request(url.href, { method: "POST" }), url, params: {}, auth: { user, scope: undefined, via: "none" as const }, theme: undefined }; | |
| 19 | } | |
| 20 | ||
| 21 | /** | |
| 22 | * The page's preview then confirm: says who the new link is for and what stops working (the door | |
| 23 | * decides who may see it), and only "Send a new link" issues it and ends the old one. `replace` | |
| 24 | * puts the question over a prompt that asked the name. | |
| 25 | */ | |
| 26 | export async function offerNewLink(ctx: Ctx, f: Session, name: string, back: Screen, replace = false): Promise<void> { | |
| 27 | const user = f.user; | |
| 28 | if (user === undefined) return; | |
| 29 | const seen = await previewDoor(doorCtx(f, user), user, name); | |
| 30 | const says = String(seen.body["says"] ?? seen.body["message"] ?? "no new link"); | |
| 31 | if (seen.status >= 400) return ctx.toast(says, "danger"); | |
| 32 | const ask = confirmScreen(ctx, back, { | |
| 33 | title: `A new link for ${name}?`, | |
| 34 | body: says.split(/(?<=\.) /), | |
| 35 | actions: [{ label: "Send a new link" }, { label: "Keep the old one" }], | |
| 36 | width: 96, | |
| 37 | onChoose: (i) => { | |
| 38 | if (i !== 0) return; | |
| 39 | runAsync(ctx, async () => { | |
| 40 | const made = await reissueDoor(doorCtx(f, user), user, name); | |
| 41 | const link = made.body["claimUrl"]; | |
| 42 | if (typeof link !== "string") return ctx.toast(String(made.body["message"] ?? "no fresh link"), "danger"); | |
| 43 | ctx.push(linkScreen(ctx, link, undefined, { qr: true })); | |
| 44 | }); | |
| 37 | 45 | }, |
| 38 | 46 | }); |
| 47 | if (replace) ctx.replace(ask); | |
| 48 | else ctx.push(ask); | |
| 49 | } | |
| 50 | ||
| 51 | export function claimLinkScreen(f: Session, ctx: Ctx): Screen { | |
| 52 | const screen: Screen = promptScreen(ctx, blank("A fresh claim link"), { | |
| 53 | title: "A fresh claim link", | |
| 54 | label: "the forge's name", | |
| 55 | hint: "you see what stops working before anything changes", | |
| 56 | onSubmit: (typed) => { | |
| 57 | const name = typed.trim().toLowerCase(); | |
| 58 | if (f.user === undefined || !NAME.test(name)) return "a forge name is letters, digits and dashes"; | |
| 59 | return Promise.resolve().then(() => runAsync(ctx, () => offerNewLink(ctx, f, name, blank("A fresh claim link"), true))); | |
| 60 | }, | |
| 61 | }); | |
| 62 | return screen; | |
| 39 | 63 | } |
| 40 | 64 | |
| 41 | 65 | /** Offered to a person: the door refuses anyone who did not send the forge, and is no admin. */ |
src/tui/screens/forges.ts +29 −7
| @@ -23,9 +23,12 @@ import type { App } from "../../app.ts"; | ||
| 23 | 23 | import { undoable, type LinkInfo } from "../../spawn/claim.ts"; |
| 24 | 24 | import { confirmScreen, pickerScreen } from "./common.ts"; |
| 25 | 25 | import type { Session } from "../session.ts"; |
| 26 | import { offerNewLink } from "./claim_link.ts"; | |
| 26 | 27 | import { appLinkSummary, appLinkWords } from "../../spawn/app_links.ts"; |
| 27 | 28 | |
| 28 | /** [name, "Not reporting · for Maria · Claimed · 3 apps running"] per row; an empty line when none. */ | |
| 29 | /** | |
| 30 | * [name, "Not reporting · for Maria · Claimed · 3 apps running"] per row; an empty line when none. | |
| 31 | */ | |
| 29 | 32 | export function forgeLines(rows: readonly ClientRow[], sender = false): [string, string][] { |
| 30 | 33 | if (rows.length === 0) return [["", "You have not sent a forge yet"]]; |
| 31 | 34 | return rows.flatMap((r): [string, string][] => [[ |
| @@ -42,7 +45,10 @@ function seenLine(r: ClientRow, sender: boolean): string | null { | ||
| 42 | 45 | return seen === null ? null : seenParts(seen).map((p) => (p.at === null ? p.words : `${p.words} ${timeAgo(p.at)}`)).join(" · "); |
| 43 | 46 | } |
| 44 | 47 | |
| 45 | /** "link open", "link ended (undo with u)": what the sender can do about the link, as /forges shows it. */ | |
| 48 | /** | |
| 49 | * "link open", "link ended (undo with u)": what the sender can do about the link, as /forges shows | |
| 50 | * it. | |
| 51 | */ | |
| 46 | 52 | function linkWords(link: LinkInfo | null): string | null { |
| 47 | 53 | if (link === null || link.state === "used") return null; |
| 48 | 54 | return link.state === "open" ? "link open" : undoable(link) ? "link ended, undo with u" : "link ended"; |
| @@ -60,7 +66,10 @@ function appLinkLines(r: ClientRow): [string, string][] { | ||
| 60 | 66 | return [...(head === null ? [] : [["", ` ${head}`] as [string, string]]), ...(r.appLinks ?? []).map((l): [string, string] => ["", ` ${appLinkWords(l)}`])]; |
| 61 | 67 | } |
| 62 | 68 | |
| 63 | /** Under a forge that is running, not reachable: each public address and what it answered (#7959), as /forges lists them. */ | |
| 69 | /** | |
| 70 | * Under a forge that is running, not reachable: each public address and what it answered (#7959), | |
| 71 | * as /forges lists them. | |
| 72 | */ | |
| 64 | 73 | function addressLines(r: ClientRow): [string, string][] { |
| 65 | 74 | if (r.reach === null || r.reach.ok) return []; |
| 66 | 75 | return r.reach.proofs.map((p): [string, string] => ["", ` ${p.ok ? "reachable" : "NOT REACHABLE"} ${p.url.replace(/^https?:\/\//, "")}: ${p.says}`]); |
| @@ -74,7 +83,10 @@ export function fitLines(lines: [string, string][], room: number): [string, stri | ||
| 74 | 83 | return kept; |
| 75 | 84 | } |
| 76 | 85 | |
| 77 | /** The `o` picker's rows, as /forges's Forge code rows say them: whose code each runs, and its last rollback. */ | |
| 86 | /** | |
| 87 | * The `o` picker's rows, as /forges's Forge code rows say them: whose code each runs, and its last | |
| 88 | * rollback. | |
| 89 | */ | |
| 78 | 90 | export function ownCodePicks(app: App, rows: readonly ClientRow[]): { id: string; label: string; hint: string }[] { |
| 79 | 91 | return rows |
| 80 | 92 | .filter((r) => r.made) |
| @@ -94,7 +106,8 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses | ||
| 94 | 106 | if (items.length === 0 || session === undefined) return; |
| 95 | 107 | ctx.push(pickerScreen(ctx, screen, { title, items, onPick: (ids) => { if (ids[0] !== undefined) act(ids[0]); } })); |
| 96 | 108 | }; |
| 97 | // Revoke and Undo are the page's buttons, through the same action (`changeLink`): an admin's, for the rows that allow it. | |
| 109 | // Revoke and Undo are the page's buttons, through the same action (`changeLink`): an admin's, for | |
| 110 | // the rows that allow it. | |
| 98 | 111 | const changeOne = (act: "revoke" | "undo"): void => { |
| 99 | 112 | const user = session?.user; |
| 100 | 113 | if (session === undefined || user?.isAdmin !== true) return; |
| @@ -112,7 +125,8 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses | ||
| 112 | 125 | }), |
| 113 | 126 | ); |
| 114 | 127 | }; |
| 115 | // "Use its own code" and back: the page's switch, through the same action (`ownCode`), an admin's. | |
| 128 | // "Use its own code" and back: the page's switch, through the same action (`ownCode`), an | |
| 129 | // admin's. | |
| 116 | 130 | const switchCode = (): void => { |
| 117 | 131 | const user = session?.user; |
| 118 | 132 | if (session === undefined || user?.isAdmin !== true) return; |
| @@ -151,9 +165,16 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses | ||
| 151 | 165 | }), |
| 152 | 166 | ); |
| 153 | 167 | }; |
| 168 | // "Send a new link" on a row not yet claimed: the page's preview and confirm (`offerNewLink`). | |
| 169 | const newLink = (): void => { | |
| 170 | if (session === undefined || session.user?.isAdmin !== true) return; | |
| 171 | const items = rows.filter((r) => r.made && claimState(r) !== "yes").map((r) => ({ id: r.name, label: r.name, hint: r.for === null ? "not claimed" : `for ${r.for}` })); | |
| 172 | if (items.length === 0) return ctx.toast("No forge is waiting to be claimed"); | |
| 173 | ctx.push(pickerScreen(ctx, screen, { title: "A new link for which forge?", items, onPick: (ids) => { if (ids[0] !== undefined) runAsync(ctx, () => offerNewLink(ctx, session, ids[0]!, screen)); } })); | |
| 174 | }; | |
| 154 | 175 | const screen: Screen = { |
| 155 | 176 | title: "Forges you sent", |
| 156 | keys: [binding(["s"], "stop one (sleep now)"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove one"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move into a sandbox"), binding(["esc"], "close")], | |
| 177 | keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["esc"], "close")], | |
| 157 | 178 | render(area, s) { |
| 158 | 179 | const c = ctx.theme.c; |
| 159 | 180 | const w = Math.min(100, Math.max(30, area.w - 6)); |
| @@ -167,6 +188,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses | ||
| 167 | 188 | if (e.key === "esc" || e.key === "q") ctx.pop(); |
| 168 | 189 | else if (e.key === "s" && session !== undefined) |
| 169 | 190 | choose("Stop which forge?", (name) => void stopForge(session.app, name).then((done) => ctx.toast(done.says, done.ok ? "success" : "danger"))); |
| 191 | else if (e.key === "n") newLink(); | |
| 170 | 192 | else if (e.key === "l") changeOne("revoke"); |
| 171 | 193 | else if (e.key === "u") changeOne("undo"); |
| 172 | 194 | else if (e.key === "o") switchCode(); |
src/web/pages/forges.ts +36 −19
| @@ -15,7 +15,7 @@ import { notFoundPage, pageHead } from "../chrome.ts"; | ||
| 15 | 15 | import { html, type Html } from "../html.ts"; |
| 16 | 16 | import { page, redirect } from "../layout.ts"; |
| 17 | 17 | import { undoable } from "../../spawn/claim.ts"; |
| 18 | import { changeDoor, reissueDoor } from "../../spawn/door.ts"; | |
| 18 | import { changeDoor, previewDoor, reissueDoor } from "../../spawn/door.ts"; | |
| 19 | 19 | import { readForm } from "../form.ts"; |
| 20 | 20 | import { badge, btn, row, time } from "../ui.ts"; |
| 21 | 21 | import { noRoom } from "../../spawn/door.ts"; |
| @@ -137,9 +137,7 @@ export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = f | ||
| 137 | 137 | : html`<span data-attention="${r.attention}">${badge(ATTENTION_WORDS[r.attention], { tone: "attn" })}</span>`}${badge(CLAIM_WORDS[state], { |
| 138 | 138 | ...(state === "yes" ? { tone: "success" as const } : { variant: "outline" as const }), |
| 139 | 139 | })}${state === "no" |
| 140 | ? html`<form method="post" action="/forges/${r.name}/claim-link"> | |
| 141 | ${btn(r.stage?.resend === true ? "Resend" : "Send a fresh link", { size: "sm", title: "A new claim link; the old one stops working" })} | |
| 142 | </form>` | |
| 140 | ? 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" }) | |
| 143 | 141 | : null}${r.link === null |
| 144 | 142 | ? null |
| 145 | 143 | : html`<span data-link="${r.link.state}">${badge(LINK_WORDS[r.link.state], { variant: "outline" as const })}</span>${r.link.state === "open" |
| @@ -210,7 +208,10 @@ function sealedLine(ctx: Ctx): Html | null { | ||
| 210 | 208 | return html`<p class="muted small" data-sealed>Every forge here runs in its own sandbox, and this forge opens none in its own process${at === 0 ? "" : html` (since ${new Date(at).toISOString().slice(0, 10)})`}.</p>`; |
| 211 | 209 | } |
| 212 | 210 | |
| 213 | /** The link to the refused first asks, only when there are any, with their count; it shares the paragraph of the other link so the page gains no block. */ | |
| 211 | /** | |
| 212 | * The link to the refused first asks, only when there are any, with their count; it shares the | |
| 213 | * paragraph of the other link so the page gains no block. | |
| 214 | */ | |
| 214 | 215 | function refusedLink(ctx: Ctx): Html | null { |
| 215 | 216 | if (!mayReadRefusals(ctx.auth.user)) return null; |
| 216 | 217 | const n = countRefusals(ctx.app.db, Date.now()); |
| @@ -279,20 +280,28 @@ export async function forgesPage(ctx: Ctx): Promise<Response> { | ||
| 279 | 280 | // GET /forges/:name/claim-link — the button for the account that sent the forge, who |
| 280 | 281 | // has no /forges list (#12105). Nothing is minted until it is pressed; whether this |
| 281 | 282 | // account may is the door's answer, not this page's. |
| 282 | export function forgeLinkForm(ctx: Ctx): Response { | |
| 283 | if (ctx.auth.user === undefined) return notFoundPage(ctx); | |
| 283 | export async function forgeLinkForm(ctx: Ctx): Promise<Response> { | |
| 284 | const user = ctx.auth.user; | |
| 285 | if (user === undefined) return notFoundPage(ctx); | |
| 284 | 286 | const name = ctx.params["name"] ?? ""; |
| 285 | const response = page({ | |
| 286 | ctx, | |
| 287 | title: "A fresh link", | |
| 288 | body: html`<div class="narrow-wide" data-forges> | |
| 289 | ${pageHead(`A fresh link for ${name}`)} | |
| 287 | const seen = await previewDoor(ctx, user, name); | |
| 288 | const says = String(seen.body["says"] ?? seen.body["message"]); | |
| 289 | const response = page( | |
| 290 | { | |
| 291 | ctx, | |
| 292 | title: "A new link", | |
| 293 | body: html`<div class="narrow-wide" data-forges> | |
| 294 | ${pageHead(`A new link for ${name}`)} | |
| 290 | 295 | <section class="settings-block"> |
| 291 | <p>The link you have stops working; the new one is shown once.</p> | |
| 292 | <form method="post" action="/forges/${name}/claim-link">${btn("Send a fresh link", { title: "A new claim link; the old one stops working" })}</form> | |
| 296 | <p data-preview>${says}</p> | |
| 297 | ${seen.status < 400 | |
| 298 | ? html`<form method="post" action="/forges/${name}/claim-link">${btn("Send a new link", { title: "Issue the new link and end the old one" })}</form>` | |
| 299 | : btn("Forges you sent", { href: "/forges", size: "sm" })} | |
| 293 | 300 | </section> |
| 294 | 301 | </div>`, |
| 295 | }); | |
| 302 | }, | |
| 303 | seen.status, | |
| 304 | ); | |
| 296 | 305 | response.headers.set("cache-control", "no-store"); |
| 297 | 306 | return response; |
| 298 | 307 | } |
| @@ -415,7 +424,10 @@ export async function forgeLinkSubmit(ctx: Ctx): Promise<Response> { | ||
| 415 | 424 | |
| 416 | 425 | const LINK_WORDS = { open: "Link open", used: "Link used", ended: "Link ended" } as const; |
| 417 | 426 | |
| 418 | /** What `/forges?link=…&forge=…` says after a revoke or undo: fixed words, and only for a forge in the list. */ | |
| 427 | /** | |
| 428 | * What `/forges?link=…&forge=…` says after a revoke or undo: fixed words, and only for a forge in | |
| 429 | * the list. | |
| 430 | */ | |
| 419 | 431 | function receipt(ctx: Ctx, rows: readonly ClientRow[]): Html | null { |
| 420 | 432 | const name = ctx.url.searchParams.get("forge") ?? ""; |
| 421 | 433 | if (!rows.some((r) => r.name === name)) return null; |
| @@ -427,7 +439,8 @@ function receipt(ctx: Ctx, rows: readonly ClientRow[]): Html | null { | ||
| 427 | 439 | return says === undefined ? null : html`<p role="status" class="muted" data-receipt>${says}</p>`; |
| 428 | 440 | } |
| 429 | 441 | |
| 430 | // POST /forges/:name/revoke-link and /undo-link — take the link back, or bring it back for a minute; then the row, with a receipt. | |
| 442 | // POST /forges/:name/revoke-link and /undo-link — take the link back, or bring it back for a | |
| 443 | // minute; then the row, with a receipt. | |
| 431 | 444 | function linkChange(act: "revoke" | "undo") { |
| 432 | 445 | return async (ctx: Ctx): Promise<Response> => { |
| 433 | 446 | const user = ctx.auth.user; |
| @@ -533,7 +546,10 @@ const CODE_WORDS = { | ||
| 533 | 546 | refused: "stays on this forge's code: only a forge in its own cell, with a forge repository, can run its own.", |
| 534 | 547 | } as const; |
| 535 | 548 | |
| 536 | /** What `/forges?code=…&forge=…` says after the switch: fixed words, and only for a forge in the list. */ | |
| 549 | /** | |
| 550 | * What `/forges?code=…&forge=…` says after the switch: fixed words, and only for a forge in the | |
| 551 | * list. | |
| 552 | */ | |
| 537 | 553 | function codeReceipt(ctx: Ctx, names: readonly string[]): Html | null { |
| 538 | 554 | const name = ctx.url.searchParams.get("forge") ?? ""; |
| 539 | 555 | const code = ctx.url.searchParams.get("code") ?? ""; |
| @@ -572,7 +588,8 @@ async function ownCodeSection(ctx: Ctx): Promise<Html | null> { | ||
| 572 | 588 | </section>`; |
| 573 | 589 | } |
| 574 | 590 | |
| 575 | // POST /forges/:name/own-code — the owner's switch: `on` is "on" or "off"; then back to the list, with a receipt. | |
| 591 | // POST /forges/:name/own-code — the owner's switch: `on` is "on" or "off"; then back to the list, | |
| 592 | // with a receipt. | |
| 576 | 593 | export async function forgeOwnCodeSubmit(ctx: Ctx): Promise<Response> { |
| 577 | 594 | const user = ctx.auth.user; |
| 578 | 595 | if (!user?.isAdmin) return notFoundPage(ctx); |
test/client-list.test.ts +2 −2
| @@ -216,7 +216,7 @@ describe("the client list", () => { | ||
| 216 | 216 | expect(lou).toMatch(/data-claimed="unknown"/); |
| 217 | 217 | expect(html).not.toContain("claim-link-box"); |
| 218 | 218 | expect(maria).toContain('class="row"'); |
| 219 | expect(maria).toContain("Send a fresh link"); | |
| 219 | expect(maria).toContain("Send a new link"); | |
| 220 | 220 | expect(lou).toContain("it did not answer just now"); |
| 221 | 221 | // It did not answer, so it carries the one attention badge and leads the list. |
| 222 | 222 | expect(lou).toContain('data-attention="silent"'); |
| @@ -246,7 +246,7 @@ describe("the client list", () => { | ||
| 246 | 246 | test("an unclaimed row offers a fresh link: it replaces the old one, shown once; only an admin may ask", async () => { |
| 247 | 247 | const html = (await (await list(admin)).text()).replace(/\s+/g, " "); |
| 248 | 248 | const maria = html.slice(html.indexOf('data-forge="maria"'), html.indexOf("</li>", html.indexOf('data-forge="maria"'))); |
| 249 | expect(maria).toContain('action="/forges/maria/claim-link"'); | |
| 249 | expect(maria).toContain('href="/forges/maria/claim-link"'); | |
| 250 | 250 | const lou = html.slice(html.indexOf('data-forge="lou"'), html.indexOf("</li>", html.indexOf('data-forge="lou"'))); |
| 251 | 251 | // Whether lou was claimed is unknown, so it offers nothing to send. |
| 252 | 252 | expect(lou).not.toContain("claim-link"); |
test/client-states.test.ts +3
| @@ -75,6 +75,9 @@ describe("client states", () => { | ||
| 75 | 75 | expect(stale).toContain(STALE_WORDS); |
| 76 | 76 | expect(stale).toContain("Resend"); |
| 77 | 77 | expect(stale).toContain("/forges/acme/claim-link"); |
| 78 | // The row's button opens the preview (a link), not a form that issues at once (#13166). | |
| 79 | expect(stale).not.toContain('method="post" action="/forges/acme/claim-link"'); | |
| 80 | expect(String(forgeRow(stage(), NOW))).toContain("Send a new link"); | |
| 78 | 81 | }); |
| 79 | 82 | |
| 80 | 83 | test("the terminal line carries the same words, and resend", () => { |
test/forge-link-reissue.test.ts added +190
| @@ -0,0 +1,190 @@ | ||
| 1 | /** | |
| 2 | * Send a forge's link again (#13166): a row on the client list previews who the new link is for and | |
| 3 | * what stops working, then on confirm issues it and the old one dies; the same through the API and | |
| 4 | * the `claim_link` MCP tool; the event is the receipt. | |
| 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 { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createSession } from "../src/core/sessions.ts"; | |
| 13 | import { createToken } from "../src/core/tokens.ts"; | |
| 14 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 15 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 16 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 17 | import { settleApp } from "./helpers/tui.ts"; | |
| 18 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 19 | import { firstBoot } from "../src/spawn/first-boot.ts"; | |
| 20 | import { quietLogs } from "./helpers/globals.ts"; | |
| 21 | ||
| 22 | quietLogs(); | |
| 23 | ||
| 24 | describe("sending a forge's link again", () => { | |
| 25 | let dir = ""; | |
| 26 | let parent: App; | |
| 27 | let servers: Servers; | |
| 28 | let child: App; | |
| 29 | let kid: Servers; | |
| 30 | let token = ""; | |
| 31 | let cookie = ""; | |
| 32 | let first = ""; | |
| 33 | const tokenOf = (url: string) => url.split("#")[1] ?? ""; | |
| 34 | const api = (body: unknown) => | |
| 35 | fetch(`${servers.url}/api/v1/forges/maria/claim-link`, { | |
| 36 | method: "POST", | |
| 37 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 38 | body: JSON.stringify(body), | |
| 39 | }); | |
| 40 | let strangerToken = ""; | |
| 41 | let strangerCookie = ""; | |
| 42 | const asStranger = (body: unknown) => | |
| 43 | fetch(`${servers.url}/api/v1/forges/maria/claim-link`, { | |
| 44 | method: "POST", | |
| 45 | headers: { authorization: `Bearer ${strangerToken}`, "content-type": "application/json" }, | |
| 46 | body: JSON.stringify(body), | |
| 47 | }); | |
| 48 | const claim = (t: string) => | |
| 49 | fetch(`${kid.url}/claim`, { | |
| 50 | method: "POST", | |
| 51 | headers: { origin: kid.url }, | |
| 52 | body: new URLSearchParams({ token: t, username: "someone", email: "[email protected]" }), | |
| 53 | }); | |
| 54 | const mcp = async (args: Record<string, unknown>) => { | |
| 55 | const res = await fetch(`${servers.url}/mcp`, { | |
| 56 | method: "POST", | |
| 57 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, | |
| 58 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "claim_link", arguments: { name: "maria", ...args } } }), | |
| 59 | }); | |
| 60 | const j = (await res.json()) as { result: { content: { text: string }[] } }; | |
| 61 | return j.result.content[0]!.text; | |
| 62 | }; | |
| 63 | ||
| 64 | beforeAll(async () => { | |
| 65 | dir = await mkdtemp(join(tmpdir(), "forge-link-reissue-")); | |
| 66 | parent = createApp({ dataDir: dir, url: "https://forge.test", port: 0 }); | |
| 67 | const made = await createUser(parent.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-claim-passphrase", isAdmin: true }); | |
| 68 | if (!made.ok) throw new Error("user"); | |
| 69 | token = createToken(parent.db, made.value.id, "rw", "rw").token; | |
| 70 | cookie = `forge_session=${createSession(parent.db, made.value.id).token}`; | |
| 71 | const bob = await createUser(parent.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-long-claim-passphrase" }); | |
| 72 | if (!bob.ok) throw new Error("bob"); | |
| 73 | strangerToken = createToken(parent.db, bob.value.id, "rw", "rw").token; | |
| 74 | strangerCookie = `forge_session=${createSession(parent.db, bob.value.id).token}`; | |
| 75 | servers = await serve(parent); | |
| 76 | const res = await fetch(`${servers.url}/api/v1/forges`, { | |
| 77 | method: "POST", | |
| 78 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 79 | body: JSON.stringify({ name: "maria", for: "Maria at the bakery", dryRun: false }), | |
| 80 | }); | |
| 81 | if (res.status !== 201) throw new Error(`spawn ${res.status} ${await res.text()}`); | |
| 82 | const body = (await res.json()) as { claimUrl: string; bodyId: string }; | |
| 83 | first = body.claimUrl; | |
| 84 | child = createApp({ dataDir: childDirOf(parent, body.bodyId), port: 0 }); | |
| 85 | await firstBoot(child); | |
| 86 | kid = await serve(child); | |
| 87 | }, 60_000); | |
| 88 | ||
| 89 | afterAll(async () => { | |
| 90 | kid.stop(); | |
| 91 | child.close(); | |
| 92 | servers.stop(); | |
| 93 | parent.close(); | |
| 94 | await rm(dir, { recursive: true, force: true }); | |
| 95 | }); | |
| 96 | ||
| 97 | test("the preview says who it is for and what stops, and changes nothing", async () => { | |
| 98 | const page = await (await fetch(`${servers.url}/forges/maria/claim-link`, { headers: { cookie } })).text(); | |
| 99 | expect(page).toContain("Maria at the bakery"); | |
| 100 | expect(page).toContain("stops working"); | |
| 101 | expect(page).toContain('action="/forges/maria/claim-link"'); | |
| 102 | const seen = (await (await api({ dryRun: true })).json()) as { dryRun: boolean; for: string; says: string; claimUrl?: string }; | |
| 103 | expect(seen.dryRun).toBe(true); | |
| 104 | expect(seen.for).toBe("Maria at the bakery"); | |
| 105 | expect(seen.claimUrl).toBeUndefined(); | |
| 106 | expect(JSON.parse(await mcp({})).reissued).toBe(false); | |
| 107 | // the first link still works: a refused username is not a dead link | |
| 108 | expect((await claim(tokenOf(first))).status).not.toBe(404); | |
| 109 | }); | |
| 110 | ||
| 111 | test("on confirm the new link is issued, the old answers the dead-link sentence, and the event is the receipt", async () => { | |
| 112 | const res = await fetch(`${servers.url}/forges/maria/claim-link`, { method: "POST", headers: { cookie, origin: "https://forge.test" } }); | |
| 113 | expect(res.status).toBe(201); | |
| 114 | const html = await res.text(); | |
| 115 | expect(html).toContain("/claim#"); | |
| 116 | const old = await claim(tokenOf(first)); | |
| 117 | expect(old.status).toBe(404); | |
| 118 | expect(await old.text()).toContain("this link does not work any more"); | |
| 119 | const rows = parent.db.query("SELECT payload FROM event WHERE kind = 'forge.claim_reissued'").all() as { payload: string }[]; | |
| 120 | expect(rows.length).toBe(1); | |
| 121 | expect(JSON.parse(rows[0]!.payload)).toMatchObject({ name: "maria", for: "Maria at the bakery" }); | |
| 122 | }); | |
| 123 | ||
| 124 | test("the API and MCP issue a newer one in the same way, and a cross-origin post is refused", async () => { | |
| 125 | const res = await api({}); | |
| 126 | expect(res.status).toBe(201); | |
| 127 | const second = ((await res.json()) as { claimUrl: string }).claimUrl; | |
| 128 | const viaMcp = JSON.parse(await mcp({ reveal: true })) as { claimUrl: string }; | |
| 129 | expect(tokenOf(viaMcp.claimUrl)).not.toBe(tokenOf(second)); | |
| 130 | expect((await claim(tokenOf(second))).status).toBe(404); | |
| 131 | const evil = await fetch(`${servers.url}/forges/maria/claim-link`, { method: "POST", headers: { cookie, origin: "https://evil.test" } }); | |
| 132 | expect(evil.status).toBeGreaterThanOrEqual(400); | |
| 133 | const n = (parent.db.query("SELECT count(*) AS n FROM event WHERE kind = 'forge.claim_reissued'").get() as { n: number }).n; | |
| 134 | expect(n).toBe(3); | |
| 135 | }); | |
| 136 | ||
| 137 | test("in the terminal an admin picks the forge, reads the preview, confirms, and the old link dies", async () => { | |
| 138 | const before = tokenOf(((await (await api({})).json()) as { claimUrl: string }).claimUrl); | |
| 139 | const { app } = createForgeApp(parent, { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(parent.db, "alice")! }, { terminal: headlessTerminal(140, 32), exitHooks: false }); | |
| 140 | app.start(); | |
| 141 | const k = (key: string) => app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false }); | |
| 142 | app.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false }); | |
| 143 | for (const ch of "Forges you sent") k(ch); | |
| 144 | k("enter"); | |
| 145 | await settleApp(app); | |
| 146 | k("n"); | |
| 147 | await settleApp(app); | |
| 148 | k("enter"); | |
| 149 | await settleApp(app); | |
| 150 | const seen = app.screen.toText(); | |
| 151 | expect(seen).toContain("Maria at the bakery"); | |
| 152 | expect(seen).toContain("stops working"); | |
| 153 | // nothing changed yet: the link just issued still works | |
| 154 | expect((await claim(before)).status).not.toBe(404); | |
| 155 | k("enter"); | |
| 156 | await settleApp(app); | |
| 157 | await Bun.sleep(200); // real-timer: the terminal app settles on its own render loop | |
| 158 | await settleApp(app); | |
| 159 | expect(app.screen.toText()).toContain("/claim#"); | |
| 160 | expect((await claim(before)).status).toBe(404); | |
| 161 | }); | |
| 162 | ||
| 163 | test("a person who is neither admin nor the sender is refused the preview everywhere, and learns no name", async () => { | |
| 164 | const page = await fetch(`${servers.url}/forges/maria/claim-link`, { headers: { cookie: strangerCookie } }); | |
| 165 | expect(page.status).toBe(403); | |
| 166 | expect(await page.text()).not.toContain("Maria at the bakery"); | |
| 167 | const res = await asStranger({ dryRun: true }); | |
| 168 | expect(res.status).toBe(403); | |
| 169 | expect(await res.text()).not.toContain("Maria at the bakery"); | |
| 170 | const text = await fetch(`${servers.url}/mcp`, { | |
| 171 | method: "POST", | |
| 172 | headers: { authorization: `Bearer ${strangerToken}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, | |
| 173 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "claim_link", arguments: { name: "maria" } } }), | |
| 174 | }).then((r) => r.text()); | |
| 175 | expect(text).not.toContain("Maria at the bakery"); | |
| 176 | expect(text).toContain("forbidden"); | |
| 177 | }); | |
| 178 | ||
| 179 | test("a claimed forge is refused with the claimed message on the preview and on the send", async () => { | |
| 180 | const made = await createUser(child.db, { origin: "seed", trusted: true, username: "claimer", email: "[email protected]", password: "a-long-claim-passphrase", isAdmin: true }); | |
| 181 | if (!made.ok) throw new Error(`claim ${made.error}`); | |
| 182 | const res = await api({ dryRun: true }); | |
| 183 | expect(res.status).toBeGreaterThanOrEqual(400); | |
| 184 | expect(await res.text()).toContain("already claimed"); | |
| 185 | const page = await fetch(`${servers.url}/forges/maria/claim-link`, { headers: { cookie } }); | |
| 186 | expect(page.status).toBeGreaterThanOrEqual(400); | |
| 187 | expect(await page.text()).toContain("already claimed"); | |
| 188 | expect((await api({})).status).toBeGreaterThanOrEqual(400); | |
| 189 | }); | |
| 190 | }); |
new above
offline