Public: anyone can read this; the crew can change it.
A stranger cut off during a one-click start can resume it with the resumeKey #14910 issues #15139
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/15126-a-stranger-cut-off-during-a-one-click-st → main 9 commits fork 3 threads · 3 unresolved
8 files
changed +294
−10
docs/features/spawner-claim-link.md +7 −3
| @@ -34,9 +34,13 @@ someone else; only the person who started it can resume it". | ||
| 34 | 34 | - The ledger keeps only the key's hash, and the check compares in constant time. Nobody can tell you a lost key: |
| 35 | 35 | start again under another name. |
| 36 | 36 | |
| 37 | No door: a signed-out start from the home page or the terminal's **Start my forge** shows no `resumeKey`, so a | |
| 38 | stranger cut off there cannot resume; they start again under another name. A finished forge is answered as before. | |
| 39 | Pinned by `test/spawn-resume.test.ts` and `test/spawn-resume-door.test.ts`. | |
| 37 | The one-click doors keep the key for the stranger and never show it (#15126). The home page's **Start my forge** | |
| 38 | sends a key it chose and keeps it in an HttpOnly, SameSite=Lax cookie named for the forge (`forge_resume_<name>`, | |
| 39 | `Path=/forges/start`, a day), set on every refusal, a start that stops part way included, and cleared once the forge | |
| 40 | is made (`src/web/resume_cookie.ts`). The terminal's guest **Start my forge** keeps it for the SSH session, for the last 8 names typed. Pressing | |
| 41 | it again from the same browser or session resumes; any other gets `not_yours` in plain words: "Someone else is making | |
| 42 | a forge by that name. Pick another name and press Start my forge again." A finished forge is answered as before. Pinned by | |
| 43 | `test/spawn-resume.test.ts`, `test/spawn-resume-door.test.ts` and `test/start-forge-resume.test.ts`. | |
| 40 | 44 | |
| 41 | 45 | A spawn through the API or MCP holds its reply at most `HOME_WAIT_MS` (20 s, one budget for the cell's start and the |
| 42 | 46 | home's first answer). A home that answers in time gets "Ready: send the link"; otherwise "It will answer in about a |
src/tui/screens/startforge.ts +41 −1
| @@ -6,9 +6,14 @@ | ||
| 6 | 6 | * one of the fixed sentences the home page shows (`web/start_refusal.ts`); a |
| 7 | 7 | * made forge's claim link is shown once and kept nowhere. Signed in, "New |
| 8 | 8 | * forge" is the fuller form, so this command is a guest's. |
| 9 | * Each name is sent with a resume key this SSH session keeps (#15126), so a | |
| 10 | * start cut off before the forge is made is finished by pressing Enter again | |
| 11 | * in the same session, and by nobody else. The key is never shown; a session | |
| 12 | * holds keys for its last `RESUME_NAMES` names. | |
| 9 | 13 | */ |
| 10 | 14 | |
| 11 | 15 | import { notePeer } from "../../http/peer.ts"; |
| 16 | import { secret } from "../../kernel/id.ts"; | |
| 12 | 17 | import { spawnDoor } from "../../spawn/door.ts"; |
| 13 | 18 | import { START_REFUSALS, startRefusalOf, startRefusalWords, startWaitOf } from "../../web/start_refusal.ts"; |
| 14 | 19 | import type { Ctx, Screen } from "../app/app.ts"; |
| @@ -21,6 +26,37 @@ import { linkScreen, runAsync } from "./common.ts"; | ||
| 21 | 26 | |
| 22 | 27 | const HINT = "Lowercase letters, digits and dashes. Enter starts it."; |
| 23 | 28 | |
| 29 | /** The most names one session holds a resume key for; past it the oldest is dropped. */ | |
| 30 | export const RESUME_NAMES = 8; | |
| 31 | ||
| 32 | /** | |
| 33 | * Each session's resume keys, by forge name: kept until that forge is made, gone with the session. | |
| 34 | */ | |
| 35 | const resumeKeys = new WeakMap<Session, Map<string, string>>(); | |
| 36 | ||
| 37 | /** | |
| 38 | * The key `keys` holds for `name`, or a fresh one from `make` it keeps. Insertion order is age, so | |
| 39 | * a new name past `RESUME_NAMES` drops the oldest and the map stays bounded. | |
| 40 | */ | |
| 41 | export function keptResumeKey(keys: Map<string, string>, name: string, make: () => string): string { | |
| 42 | const held = keys.get(name); | |
| 43 | if (held !== undefined) return held; | |
| 44 | const key = make(); | |
| 45 | keys.set(name, key); | |
| 46 | for (const old of keys.keys()) { | |
| 47 | if (keys.size <= RESUME_NAMES) break; | |
| 48 | keys.delete(old); | |
| 49 | } | |
| 50 | return key; | |
| 51 | } | |
| 52 | ||
| 53 | /** The key this session sends for `name`: the one it already holds, or a fresh one it keeps. */ | |
| 54 | function resumeKeyOf(f: Session, name: string): string { | |
| 55 | let keys = resumeKeys.get(f); | |
| 56 | if (keys === undefined) resumeKeys.set(f, (keys = new Map())); | |
| 57 | return keptResumeKey(keys, name, secret); | |
| 58 | } | |
| 59 | ||
| 24 | 60 | export function startForgeScreen(f: Session, ctx: Ctx): Screen { |
| 25 | 61 | let name = ""; |
| 26 | 62 | let error: string | undefined; |
| @@ -36,7 +72,11 @@ export function startForgeScreen(f: Session, ctx: Ctx): Screen { | ||
| 36 | 72 | const request = new Request(new URL("/forges/start", url).href, { method: "POST" }); |
| 37 | 73 | notePeer(request, f.identity.remoteAddress); |
| 38 | 74 | const hctx = { app: f.app, request, url, params: {}, auth: { user: undefined, scope: undefined, via: "none" as const }, theme: undefined }; |
| 39 | const made = await spawnDoor(hctx, undefined, { name: name.trim().toLowerCase(), dryRun: false }); | |
| 75 | const asked = name.trim().toLowerCase(); | |
| 76 | // Held before the door is asked: a start that stops part way leaves the key here for Enter | |
| 77 | // again. | |
| 78 | const made = await spawnDoor(hctx, undefined, { name: asked, dryRun: false, resumeKey: resumeKeyOf(f, asked) }); | |
| 79 | if (made.status < 400) resumeKeys.get(f)?.delete(asked); | |
| 40 | 80 | const link = made.body["claimUrl"]; |
| 41 | 81 | if (made.status >= 400 || typeof link !== "string") { |
| 42 | 82 | error = made.status >= 400 ? startRefusalWords(startRefusalOf(made), startWaitOf(made)) : START_REFUSALS.taken; |
src/web/pages/start-forge.ts +31 −5
| @@ -6,16 +6,19 @@ | ||
| 6 | 6 | * answers (`web/forge_made.ts`), in a no-store body. The answer does not wait |
| 7 | 7 | * on the first reach proof: the page shows the start itself. |
| 8 | 8 | * A signed-in person is sent to the fuller `/forges/new`, which keeps its form. |
| 9 | * The door is sent a resume key this browser keeps (`web/resume_cookie.ts`, #15126), so a start | |
| 10 | * cut off before the forge is made is finished by pressing it again here, and by nobody else. | |
| 9 | 11 | */ |
| 10 | 12 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 11 | 13 | import type { Ctx } from "../../http/context.ts"; |
| 12 | import { spawnDoor } from "../../spawn/door.ts"; | |
| 14 | import { spawnDoor, type Door } from "../../spawn/door.ts"; | |
| 13 | 15 | import { noteForgeMade } from "../funnel_door.ts"; |
| 14 | 16 | import { field, readForm, refused } from "../form.ts"; |
| 15 | 17 | import { agentsPage } from "./agents.ts"; |
| 16 | 18 | import { madeBody, madeJs } from "../forge_made.ts"; |
| 17 | 19 | import { page, redirect } from "../layout.ts"; |
| 18 | 20 | import { notFoundPage } from "../chrome.ts"; |
| 21 | import { dropResumeKey, keepResumeKey, resumeKeyFor } from "../resume_cookie.ts"; | |
| 19 | 22 | import { startRefusalHref, startRefusalOf, startRefusalWords, startWaitOf } from "../start_refusal.ts"; |
| 20 | 23 | |
| 21 | 24 | /** The home's live name check: asks `GET /forges/name/<name>` and says free, taken, or the route's own reason; a 429 or a failure says nothing. */ |
| @@ -44,21 +47,44 @@ export async function startForgeSubmit(ctx: Ctx): Promise<Response> { | ||
| 44 | 47 | const typed = field(form, "name").trim(); |
| 45 | 48 | const name = typed.toLowerCase(); |
| 46 | 49 | if (user !== undefined) return redirect(SLUG.test(name) ? `/forges/new?name=${encodeURIComponent(name)}` : "/forges/new"); |
| 47 | const door = await spawnDoor(ctx, undefined, { name, dryRun: false }, { page: true }); | |
| 50 | const resumeKey = resumeKeyFor(ctx.request, name); | |
| 51 | const door = await startDoor(ctx, name, resumeKey); | |
| 48 | 52 | if (door.status >= 400) { |
| 49 | 53 | const why = startRefusalOf(door); |
| 50 | 54 | const wait = startWaitOf(door); |
| 55 | // Kept on every refusal: a start that stopped part way is this browser's to finish. | |
| 56 | const kept = keepResumeKey(name, resumeKey, ctx.url, ctx.app.config.url); | |
| 51 | 57 | // The /agents form is answered on /agents, the name kept and the reason beside it. |
| 52 | if (field(form, "from") === "agents") return agentsPage(ctx, refused(form, { name: startRefusalWords(why, wait) })); | |
| 58 | if (field(form, "from") === "agents") return withCookie(await agentsPage(ctx, refused(form, { name: startRefusalWords(why, wait) })), kept); | |
| 53 | 59 | // Said on the home page, with the name kept (#11238). |
| 54 | return redirect(startRefusalHref(why, typed, wait)); | |
| 60 | return withCookie(redirect(startRefusalHref(why, typed, wait)), kept); | |
| 55 | 61 | } |
| 62 | const done = dropResumeKey(name, ctx.url, ctx.app.config.url); | |
| 56 | 63 | const link = door.body["claimUrl"]; |
| 57 | if (typeof link !== "string") return redirect(startRefusalHref("taken", name)); | |
| 64 | if (typeof link !== "string") return withCookie(redirect(startRefusalHref("taken", name)), done); | |
| 58 | 65 | noteForgeMade(ctx); |
| 59 | 66 | // Made for themselves: its own account screen, never the one for a link someone sent. |
| 60 | 67 | const body = madeBody({ name, link: link.replace(/\/claim#/, "/welcome#"), own: true }); |
| 61 | 68 | const response = page({ ctx, title: "Your new forge", body, scriptJs: madeJs }); |
| 62 | 69 | response.headers.set("cache-control", "no-store"); |
| 70 | return withCookie(response, done); | |
| 71 | } | |
| 72 | ||
| 73 | /** | |
| 74 | * The door, as a stranger holding `resumeKey`. A start that throws part way may leave its forge | |
| 75 | * unfinished: it is answered as a failed start, so the browser still gets the key that resumes it. | |
| 76 | */ | |
| 77 | async function startDoor(ctx: Ctx, name: string, resumeKey: string): Promise<Door> { | |
| 78 | try { | |
| 79 | return await spawnDoor(ctx, undefined, { name, dryRun: false, resumeKey }, { page: true }); | |
| 80 | } catch (error) { | |
| 81 | ctx.app.log.error("a home page start failed part way", { name, error: String(error) }); | |
| 82 | return { status: 500, body: { error: "failed", message: "the forge could not be made" } }; | |
| 83 | } | |
| 84 | } | |
| 85 | ||
| 86 | /** `response` with the resume key's cookie line (`web/resume_cookie.ts`), when there is one. */ | |
| 87 | function withCookie(response: Response, resumeLine: string | undefined): Response { | |
| 88 | if (resumeLine !== undefined) response.headers.append("set-cookie", resumeLine); | |
| 63 | 89 | return response; |
| 64 | 90 | } |
src/web/resume_cookie.ts added +43
| @@ -0,0 +1,43 @@ | ||
| 1 | /** | |
| 2 | * The home page's resume key (#15126): a stranger's **Start my forge** sends `spawnDoor` a key it | |
| 3 | * chose (`RESUME_KEY`, #14910), and the browser keeps it in an HttpOnly cookie named for that forge | |
| 4 | * and scoped to `Path=/forges/start`, the one route that reads it. A start cut off before the forge | |
| 5 | * is made is resumed by the same browser pressing it again; anyone else is refused as `not_yours`. | |
| 6 | * The key is never shown, logged or put in an address. | |
| 7 | */ | |
| 8 | ||
| 9 | import { RESUME_KEY } from "../actions/spawn.ts"; | |
| 10 | import { expireCookie, setCookie } from "../auth/cookies.ts"; | |
| 11 | import { cookieValue } from "../http/context.ts"; | |
| 12 | import { secureFor } from "../http/cookie_secure.ts"; | |
| 13 | import { secret } from "../kernel/id.ts"; | |
| 14 | ||
| 15 | /** A day: long enough to come back to a start that was cut off, short enough to be forgotten. */ | |
| 16 | const MAX_AGE_S = 86_400; | |
| 17 | /** A forge name, as the start form takes it: 1 to 39 lowercase letters, digits and inner dashes. */ | |
| 18 | const FORGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/; | |
| 19 | ||
| 20 | /** The cookie that holds the key for `name`, or undefined for a name no forge could have. */ | |
| 21 | export const resumeCookieName = (name: string): string | undefined => (FORGE_NAME.test(name) ? `forge_resume_${name}` : undefined); | |
| 22 | ||
| 23 | /** The key this browser holds for `name`, or a fresh one when it holds none of the right shape. */ | |
| 24 | export function resumeKeyFor(request: Request, name: string): string { | |
| 25 | const cookie = resumeCookieName(name); | |
| 26 | const held = cookie === undefined ? undefined : cookieValue(request, cookie); | |
| 27 | return held !== undefined && RESUME_KEY.test(held) ? held : secret(); | |
| 28 | } | |
| 29 | ||
| 30 | /** | |
| 31 | * The `Set-Cookie` line that keeps `key` for `name`, or undefined for a name no forge could have. | |
| 32 | */ | |
| 33 | export function keepResumeKey(name: string, key: string, url: URL, forgeUrl?: string): string | undefined { | |
| 34 | const cookie = resumeCookieName(name); | |
| 35 | if (cookie === undefined || !RESUME_KEY.test(key)) return undefined; | |
| 36 | return setCookie(cookie, key, { path: "/forges/start", maxAge: MAX_AGE_S, secure: secureFor(url, forgeUrl) }); | |
| 37 | } | |
| 38 | ||
| 39 | /** Sent once the forge is made: nothing is left to resume. */ | |
| 40 | export function dropResumeKey(name: string, url: URL, forgeUrl?: string): string | undefined { | |
| 41 | const cookie = resumeCookieName(name); | |
| 42 | return cookie === undefined ? undefined : expireCookie(cookie, { path: "/forges/start", secure: secureFor(url, forgeUrl) }); | |
| 43 | } |
src/web/start_refusal.ts +7 −1
| @@ -6,7 +6,9 @@ | ||
| 6 | 6 | * except the name, escaped, back in its field. |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | export type StartRefusal = "rate" | "taken" | "name" | "full" | "queued" | "other"; | |
| 9 | import { NOT_YOURS } from "../actions/spawn.ts"; | |
| 10 | ||
| 11 | export type StartRefusal = "rate" | "taken" | "not_yours" | "name" | "full" | "queued" | "other"; | |
| 10 | 12 | |
| 11 | 13 | /** A queued spawn's place in line and the seconds to wait before pressing again. */ |
| 12 | 14 | export interface StartWait { |
| @@ -17,6 +19,7 @@ export interface StartWait { | ||
| 17 | 19 | export const START_REFUSALS: Readonly<Record<StartRefusal, string>> = { |
| 18 | 20 | rate: "Too many forges have been started from your connection lately. Wait a few minutes, or try again tomorrow, and press Start my forge again.", |
outdated
Principles 1 and 8: this says it twice. Make it one plain sentence, e.g. "Someone else is making a forge by that name. Pick another name and press Start my forge again." |
||
| 19 | 21 | taken: "That name is already taken. Change it a little, for example add your own name or a number, and press Start my forge again.", |
| 22 | not_yours: "Someone else is making a forge by that name. Pick another name and press Start my forge again.", | |
| 20 | 23 | name: "That name can't be used. Use 1 to 39 lowercase letters, digits or dashes, not starting or ending with a dash, and press Start my forge again.", |
| 21 | 24 | queued: "Many forges are being made right now. Wait a minute, then press Start my forge again.", |
| 22 | 25 | full: "This forge has no room for another forge right now. Try again later, or come back tomorrow.", |
| @@ -29,6 +32,9 @@ export function startRefusalOf(door: { readonly status: number; readonly body: R | ||
| 29 | 32 | const message = String(door.body["message"] ?? ""); |
| 30 | 33 | if (door.status === 429 || error === "rate_limited") return "rate"; |
| 31 | 34 | if (error === "queued") return "queued"; |
| 35 | // #14910's `not_yours`: an unfinished forge this caller did not start. Matched on the door's own | |
outdated
Fragile: this matches on the wording of the door's message. Use a stable code or the shared NOT_YOURS constant instead, so a reword cannot silently turn this into "other". |
||
| 36 | // `NOT_YOURS` sentence, after its name, so a reword there moves both. | |
| 37 | if (error === "refused" && message.endsWith(NOT_YOURS(""))) return "not_yours"; | |
| 32 | 38 | if (error === "exists" || (error === "refused" && /already exists|being made/.test(message))) return "taken"; |
| 33 | 39 | if (error === "invalid" && /^name: /.test(message)) return "name"; |
| 34 | 40 | if (error === "refused" && /forges sent|room|quota|deep|capacity|limit/i.test(message)) return "full"; |
test/cookie-flags.test.ts +9
| @@ -67,6 +67,12 @@ const COOKIES: Record<string, Spelled> = { | ||
| 67 | 67 | "src/apps/feedback.ts VISITOR_COOKIE": { name: "forge_visitor", lines: 1, door: "app note" }, |
| 68 | 68 | "src/perf/visitor_id.ts COOKIE": { name: "forge_visitor", lines: 1, door: "page-view beacon" }, |
| 69 | 69 | "src/web/gift_cookie.ts NAME": { name: "forge_gift", lines: 2, door: "gift link" }, |
| 70 | "src/web/resume_cookie.ts cookie": { | |
| 71 | name: /^forge_resume_[a-z0-9-]{1,39}$/, | |
| 72 | lines: 2, | |
| 73 | why: "set when a stranger's home page start is refused or stops part way, cleared once made; tested in test/start-forge-resume.test.ts", | |
| 74 | path: { path: "/forges/start", why: "the resume key is read only by the start form's POST /forges/start; no other page should carry it" }, | |
| 75 | }, | |
| 70 | 76 | "src/web/pages/map.ts name": { name: /^rm_[\w-]+$/, lines: 1, door: "roadmap" }, |
| 71 | 77 | "src/web/pages/home_flow.ts VIEW_COOKIE": { |
| 72 | 78 | name: "forge_home_view", |
| @@ -126,6 +132,8 @@ const UNREACHED: Record<string, { sites: number; why: string }> = { | ||
| 126 | 132 | "src/release/journey.ts": { sites: 1, why: "reads the Set-Cookie of the sign-in response to carry the session through the walk; sets none; covered by test/release-journey.test.ts" }, |
| 127 | 133 | "src/web/pages/home_flow.ts": { sites: 1, why: "the home's remembered view (lanes or table); HttpOnly, Lax, Secure over https, spelled once and checked in the source walk" }, |
| 128 | 134 | "src/spawn/origin_broker.ts": { sites: 2, why: "the connect ticket, set and cleared; needs a parent's OAuth application, so no door above reaches it; checked in the source walk" }, |
| 135 | "src/web/resume_cookie.ts": { sites: 1, why: "the doc comment of keepResumeKey, whose line the home page's start sends; tested in test/start-forge-resume.test.ts" }, | |
| 136 | "src/web/pages/start-forge.ts": { sites: 1, why: "appends the resume key's line from src/web/resume_cookie.ts; tested in test/start-forge-resume.test.ts" }, | |
| 129 | 137 | "src/core/idempotency.ts": { sites: 1, why: "names set-cookie only to drop it: a replayed answer never carries the first answer's cookie; sets none; covered by test/idempotency-replay-headers.test.ts" }, |
| 130 | 138 | "src/web/pages/new-forge.ts": { sites: 1, why: "appends dropGift(), the gift cookie's clearing line from src/web/gift_cookie.ts, once a forge is made with a gift code" }, |
| 131 | 139 | }; |
| @@ -486,6 +494,7 @@ const BUILDERS: Record<string, string> = { | ||
| 486 | 494 | cookie: "src/http/measure.ts, the line `trackVisitor` returns, built by `cookieLine` in src/perf/visitor_id.ts", |
| 487 | 495 | "clearCookie(": "src/spawn/origin_broker.ts, the connect ticket cleared with Max-Age 0", |
| 488 | 496 | "dropGift(": "src/web/gift_cookie.ts, the gift cookie cleared with Max-Age 0", |
| 497 | resumeLine: "src/web/pages/start-forge.ts, the resume key's line from keepResumeKey or dropResumeKey in src/web/resume_cookie.ts", | |
| 489 | 498 | "o.cookie": "src/web/layout.ts, a page's cookie (the theme, from setCookie in src/web/pages/site.ts)", |
| 490 | 499 | }; |
| 491 | 500 |
test/cookie-floor.test.ts +1
| @@ -26,6 +26,7 @@ const SCRIPT_READABLE: Record<string, string> = {}; | ||
| 26 | 26 | */ |
| 27 | 27 | const PASSED_IN: Record<string, string> = { |
| 28 | 28 | "src/web/layout.ts o.cookie": "a page's `cookie` option; each caller passes a line from setCookie (the theme in src/web/pages/site.ts)", |
| 29 | "src/web/pages/start-forge.ts resumeLine": "withCookie's line; each caller passes keepResumeKey or dropResumeKey from src/web/resume_cookie.ts, which call setCookie and expireCookie", | |
| 29 | 30 | }; |
| 30 | 31 | |
| 31 | 32 | const HELPERS = new Set(["setCookie", "expireCookie"]); |
test/start-forge-resume.test.ts added +155
| @@ -0,0 +1,155 @@ | ||
| 1 | /** | |
| 2 | * A stranger cut off during a one-click start resumes it, and nobody else does (#15126): the home | |
| 3 | * page's **Start my forge** keeps #14910's resume key in an HttpOnly cookie named for the forge, | |
| 4 | * the terminal's keeps it for the SSH session, and each sends it back on the retry. A retry with no | |
| 5 | * key or the wrong one is told #14910's `not_yours`, in plain words. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { NOT_YOURS } from "../src/actions/spawn.ts"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | import { usePlacement, useProbe } from "../src/spawn/door.ts"; | |
| 15 | import { hostedPlacement } from "../src/spawn/placement.ts"; | |
| 16 | import { resetAnonSpawns } from "../src/spawn/rate.ts"; | |
| 17 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 18 | import { RESUME_NAMES, keptResumeKey, startForgeScreen } from "../src/tui/screens/startforge.ts"; | |
| 19 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 20 | import { START_REFUSALS, startRefusalOf } from "../src/web/start_refusal.ts"; | |
| 21 | import { quietLogs } from "./helpers/globals.ts"; | |
| 22 | import { settleApp } from "./helpers/tui.ts"; | |
| 23 | ||
| 24 | quietLogs(); | |
| 25 | ||
| 26 | let dir: string; | |
| 27 | let app: App; | |
| 28 | let servers: Servers; | |
| 29 | beforeAll(async () => { | |
| 30 | dir = await mkdtemp(join(tmpdir(), "forge-start-resume-")); | |
| 31 | app = createApp({ dataDir: dir, port: 0 }); | |
| 32 | servers = await serve(app); | |
| 33 | useProbe(app, () => async () => true); | |
| 34 | usePlacement(app, hostedPlacement({ host: "forge.test" })); | |
| 35 | }); | |
| 36 | afterAll(async () => { | |
| 37 | await servers.stop?.(); | |
| 38 | app.close(); | |
| 39 | await rm(dir, { recursive: true, force: true }); | |
| 40 | }); | |
| 41 | ||
| 42 | /** The next start of `name` stops right after its ledger is written, as a process cut off would. */ | |
| 43 | function cutOffOnce(): void { | |
| 44 | const append = app.bus.append.bind(app.bus); | |
| 45 | const cut: typeof app.bus.append = (...args) => { | |
| 46 | if (args[0].kind !== "forge.spawn.started") return append(...args); | |
| 47 | app.bus.append = append; | |
| 48 | throw new Error("cut off"); | |
| 49 | }; | |
| 50 | app.bus.append = cut; | |
| 51 | } | |
| 52 | ||
| 53 | const ledger = async (name: string) => JSON.parse(await Bun.file(join(dir, "spawn", `${name}.json`)).text()) as { done: boolean }; | |
| 54 | ||
| 55 | const start = (name: string, cookie?: string) => | |
| 56 | fetch(`${servers.url}/forges/start`, { | |
| 57 | method: "POST", | |
| 58 | headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url, ...(cookie === undefined ? {} : { cookie }) }, | |
| 59 | body: new URLSearchParams({ name }), | |
| 60 | redirect: "manual", | |
| 61 | }); | |
| 62 | ||
| 63 | test("the home page: a cut-off start leaves its key in a cookie, which resumes it; no key or another is not_yours", async () => { | |
| 64 | resetAnonSpawns(app.db); | |
| 65 | cutOffOnce(); | |
| 66 | const first = await start("cut-web"); | |
| 67 | expect(first.status).toBe(303); | |
| 68 | expect(first.headers.get("location")).toStartWith("/?start=other"); | |
| 69 | expect((await ledger("cut-web")).done).toBe(false); | |
| 70 | const line = first.headers.getSetCookie().find((c) => c.startsWith("forge_resume_cut-web=")) ?? ""; | |
| 71 | const flags = line.split(";").map((f) => f.trim()); | |
| 72 | expect(flags).toContain("HttpOnly"); | |
| 73 | expect(flags).toContain("SameSite=Lax"); | |
| 74 | expect(flags).toContain("Path=/forges/start"); | |
| 75 | const cookie = flags[0]!; | |
| 76 | // The key is never in the address or the page. | |
| 77 | const key = cookie.split("=")[1]!; | |
| 78 | expect(key).toMatch(/^[A-Za-z0-9_-]{32,128}$/); | |
| 79 | expect(first.headers.get("location")).not.toContain(key); | |
| 80 | ||
| 81 | for (const other of [undefined, `forge_resume_cut-web=${"x".repeat(43)}`]) { | |
| 82 | const refused = await start("cut-web", other); | |
| 83 | expect(refused.status).toBe(303); | |
| 84 | expect(refused.headers.get("location")).toStartWith("/?start=not_yours&name=cut-web"); | |
| 85 | const home = await (await fetch(`${servers.url}${refused.headers.get("location")}`)).text(); | |
| 86 | expect(home.replaceAll("'", "'")).toContain(START_REFUSALS.not_yours); | |
| 87 | expect(home).not.toContain(key); | |
| 88 | } | |
| 89 | ||
| 90 | const resumed = await start("cut-web", cookie); | |
| 91 | const body = await resumed.text(); | |
| 92 | expect(resumed.status).toBe(200); | |
| 93 | expect(body).toMatch(/href="[^"]*cut-web--[^"]*\/welcome#[A-Za-z0-9_-]{43}"/); | |
| 94 | expect(body).not.toContain(key); | |
| 95 | expect((await ledger("cut-web")).done).toBe(true); | |
| 96 | // Made: the browser forgets the key. | |
| 97 | expect(resumed.headers.getSetCookie().find((c) => c.startsWith("forge_resume_cut-web="))).toContain("Max-Age=0"); | |
| 98 | }); | |
| 99 | ||
| 100 | test("the terminal: Enter again in the same session resumes a cut-off start; another session is not_yours", async () => { | |
| 101 | resetAnonSpawns(app.db); | |
| 102 | const identity = (remoteAddress: string) => ({ sshUsername: "git", remoteAddress, fingerprint: "SHA256:test", user: undefined }); | |
| 103 | const open = async (remoteAddress: string) => { | |
| 104 | const terminal = headlessTerminal(120, 30); | |
| 105 | const { app: tui, session } = createForgeApp(app, identity(remoteAddress), { terminal, exitHooks: false }); | |
| 106 | tui.start(); | |
| 107 | tui.ctx.push(startForgeScreen(session, tui.ctx)); | |
| 108 | await settleApp(tui); | |
| 109 | return { tui, terminal }; | |
| 110 | }; | |
| 111 | const mine = await open("203.0.113.10"); | |
| 112 | const theirs = await open("203.0.113.11"); | |
| 113 | try { | |
| 114 | cutOffOnce(); | |
| 115 | mine.terminal.feed("cut-tty\r"); | |
| 116 | await settleApp(mine.tui); | |
| 117 | expect((await ledger("cut-tty")).done).toBe(false); | |
| 118 | ||
| 119 | theirs.terminal.feed("cut-tty\r"); | |
| 120 | await settleApp(theirs.tui); | |
| 121 | expect(theirs.tui.screen.toText().replace(/\s+/g, " ")).toContain(START_REFUSALS.not_yours.slice(0, 60)); | |
| 122 | expect((await ledger("cut-tty")).done).toBe(false); | |
| 123 | ||
| 124 | // The same session, the name still in its field: Enter again finishes it and shows its link. | |
| 125 | mine.terminal.feed("\r"); | |
| 126 | await settleApp(mine.tui); | |
| 127 | expect(mine.tui.screen.toText()).toMatch(/https?:\/\/cut-tty--[^/\s]*\/claim#/); | |
| 128 | expect((await ledger("cut-tty")).done).toBe(true); | |
| 129 | } finally { | |
| 130 | mine.tui.stop?.(); | |
| 131 | theirs.tui.stop?.(); | |
| 132 | } | |
| 133 | }); | |
| 134 | ||
| 135 | test("the door's not_yours is its own plain sentence, not 'taken'", () => { | |
| 136 | const door = { status: 409, body: { error: "refused", message: NOT_YOURS("kid") } }; | |
| 137 | expect(startRefusalOf(door)).toBe("not_yours"); | |
| 138 | expect(START_REFUSALS.not_yours).toBe("Someone else is making a forge by that name. Pick another name and press Start my forge again."); | |
| 139 | // Another refusal that merely mentions a start is not not_yours. | |
| 140 | expect(startRefusalOf({ status: 409, body: { error: "refused", message: "kid is being made" } })).toBe("taken"); | |
| 141 | }); | |
| 142 | ||
| 143 | test("a terminal session holds resume keys for its last 8 names, dropping the oldest", () => { | |
| 144 | const keys = new Map<string, string>(); | |
| 145 | let n = 0; | |
| 146 | const make = (): string => `key-${n++}`; | |
| 147 | const first = keptResumeKey(keys, "name-0", make); | |
| 148 | expect(keptResumeKey(keys, "name-0", make)).toBe(first); | |
| 149 | for (let i = 1; i <= RESUME_NAMES; i++) keptResumeKey(keys, `name-${i}`, make); | |
| 150 | expect(RESUME_NAMES).toBe(8); | |
| 151 | expect(keys.size).toBe(RESUME_NAMES); | |
| 152 | expect(keys.has("name-0")).toBe(false); | |
| 153 | expect(keys.get("name-1")).toBe("key-1"); | |
| 154 | expect(keys.get(`name-${RESUME_NAMES}`)).toBe(`key-${RESUME_NAMES}`); | |
| 155 | }); |
new above
offline
This Map is unbounded per session: every name a guest types adds a key. Cap its size and drop the oldest, with a test.