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

An agent makes its own forge unattended: account, token, spawn, first admin, by API and MCP #16652

Merged opened this

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

Merged

scout/forge:scout/2929-an-agent-makes-its-own-forge-unattended → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/2929-an-agent-makes-its-own-forge-unattended was merged into main as d7bffc3.

Review

Sign in to review this change.
12 files changed +506 −7
docs/MCP.md +1 −1
@@ -248,7 +248,7 @@ longer sentences:
248248 - `dryRun`: plans unless it is `false`; anything else changes nothing. `limb` applying takes an admin token.
249249 - `signup`: the terminal's Invite links screen does the same: `s` picks a mode, shows the plan (from → to) and changes it after a confirm, for a forge admin who is a person.
250250 - `tell.from`: a path on this forge the issue links to, like `/alice/notes/pulls/3`. `tell.context`: where this was told from, for the builder.
251 - `spawn.reveal`, `claim_link.reveal`: put the live claim link in the answer (default false); it is a secret, only when its person reads it. `spawn.fresh`: a fresh app beside the copied ones. `spawn.followMode`: `tell-me` (default) tells the owner in their inbox when this forge's code moves; `take-updates` opens a pull with the new code, and a person merges it. `spawn.size`: small, medium, large or xlarge; the child's cell is given that CPU, memory and disk (`sizes` lists them), and a spawn over the host's child quota is refused; a hosted child has no cell to hold it. `spawn.keepAccess`: stay an owner once claimed. `spawn.config` `{apps:[{repo, mode: fork|autonomous|migration}], budgetUsd?, admin?, domain?}` or `spawn.recipe` (a name saved on the New forge page or `PUT /api/v1/forges/recipes/<name>`) in place of `apps`; a budget applies only beside a model key, which never travels through an agent.
251 - `spawn.reveal`, `claim_link.reveal`: put the live claim link in the answer (default false); it is a secret, only when its person reads it. `spawn.fresh`: a fresh app beside the copied ones. `spawn.followMode`: `tell-me` (default) tells the owner in their inbox when this forge's code moves; `take-updates` opens a pull with the new code, and a person merges it. `spawn.size`: small, medium, large or xlarge; the child's cell is given that CPU, memory and disk (`sizes` lists them), and a spawn over the host's child quota is refused; a hosted child has no cell to hold it. `spawn.claim`: `"token"` has the parent claim the child and answer its first admin's expiring token once, with `claimUrl` spent and gone; the answer says the token is a live secret, as `reveal` does for the link (docs/features/spawn-claim-token.md). `spawn.keepAccess`: stay an owner once claimed. `spawn.config` `{apps:[{repo, mode: fork|autonomous|migration}], budgetUsd?, admin?, domain?}` or `spawn.recipe` (a name saved on the New forge page or `PUT /api/v1/forges/recipes/<name>`) in place of `apps`; a budget applies only beside a model key, which never travels through an agent.
252252 - `commits.ref`: branch, tag or commit; the default branch when absent. `report.page`: the http(s) address where the problem was seen. `plan.issues.pillar`: the pillar served, as `"P0"` or `"P0 Trust"`; `later: true` means no pillar and needs `why`.
253253 - `here.url`: none means the forge's own page. On `/` or `/settings` this forge's admin also gets `plan: { text, manage? }`, the Plan row's words and its manage-billing address; no plan notice or not an admin, no `plan` key.
254254 - `explore.q`: words, plus `kind:app|person|forge` and `sort:score|forks|ships|likes|use|fresh|name`, `updated:1d|7d|30d` (only what moved in that window), `owner:name` and `archived:yes`. `since` is another name for `updated`. `query` is the same argument; `q` wins when both are given. Each of `kind`, `sort`, `updated`, `owner`, `archived` is also its own argument (and a query parameter on `/explore` and `/api/v1/explore`); it wins over the same key in `q`.
docs/features/spawn-claim-token.md added +28
@@ -0,0 +1,28 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Make a forge and claim it with no browser
4 ---
5 # Make a forge and claim it with no browser
6
7 Three calls, over HTTP alone (`test/spawn-claim-token.test.ts`):
8
9 ```sh
10 # 1. The account, then an expiring token minted with its password.
11 curl -s $FORGE/api/v1/users -H 'content-type: application/json' -d '{"username":"grokbot","email":"[email protected]","password":"…"}'
12 curl -s $FORGE/api/v1/tokens -H 'content-type: application/json' -d '{"username":"grokbot","password":"…","scope":"rw"}'
13 # 2. Spawn and claim in one call: the parent redeems the child's claim link itself.
14 curl -s $FORGE/api/v1/forges -H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
15 -d '{"name":"maria","size":"small","apps":[],"dryRun":false,"claim":"token"}'
16 # 3. The answer's `token` works on the child.
17 curl -s https://maria--<host>/api/v1/user -H "authorization: Bearer $CHILD_TOKEN"
18 ```
19
20 `claim: "token"` is for a signed-in caller and a forge that runs inside this one. The child's first admin is `<you>-admin` (the child's founder account already holds your name; `keepAccess` keeps it an owner). The answer has `token`, `tokenExpiresAt`, `admin` and no `claimUrl`: the link is spent. The token is a live secret, shown once; it is never stored on the parent and the idempotency table keeps only "shown once, in the first answer" (a replay does not return it). It expires in a day (`POST /api/v1/first-admin` on the child mints one for a different lifetime from a claim link). If the child does not answer, `claimError` says why and the link stays unspent in `claimUrl`.
21
22 - API: `POST /api/v1/forges` with `claim: "token"`. MCP: the `spawn` tool's `claim: "token"`.
23 - Terminal: **New forge**, the field "Claim it here" (left and right choose `token`); after the spawn a dialog
24 shows the first admin's token to copy (`src/tui/screens/child_token.ts`), once and kept nowhere.
25 - The claim code goes only to the child this forge just made (its own `<name>--<host>` address, https); any other
26 address is refused and the link stays in `claimUrl`.
27
28 Pinned by `test/spawn-claim-token.test.ts` and `test/tui-child-token.test.ts`.
src/http/mcp/tools/spawn.ts +4 −2
@@ -1,11 +1,12 @@
11 import { WHERE_A_FORGE_LIVES } from "../../../spawn/contribute_words.ts";
22 import { spawnDoor } from "../../../spawn/door.ts";
33 import { FOLLOW_SHORT } from "../../../spawn/follow_words.ts";
4 import { TOKEN_SECRET_WORDS } from "../../../spawn/headless_claim.ts";
45 import { good, bad, type Tool, APP_ARG, REVEAL_ARG, LINK_KEPT, LINK_REVEALED } from "../shared.ts";
56
67 export const tool: Tool = {
78 name: "spawn",
8 doc: "`{ name, config? | recipe?, apps?, crew?, direction?, fresh?, purpose?, followMode?, size?, plan?, template?, keepAccess?, migration?, dryRun?, reveal? }`: a child forge to keep (`purpose: \"contribute\"` makes none: it answers the fork path), planned first; an admin's, and an `ro` token may plan but not make; `reveal: true` shows the claim link",
9 doc: "`{ name, config? | recipe?, apps?, crew?, direction?, fresh?, purpose?, followMode?, size?, plan?, template?, keepAccess?, migration?, dryRun?, reveal?, claim? }`: a child forge to keep (`purpose: \"contribute\"` makes none: it answers the fork path), planned first; an admin's, and an `ro` token may plan but not make; `reveal: true` shows the claim link; `claim: \"token\"` claims it and answers the first admin's live token once",
910 description:
1011 "Spawn a child forge. Plans first.",
1112 inputSchema: {
@@ -59,6 +60,7 @@ export const tool: Tool = {
5960 purpose: { type: "string", description: "\"contribute\" makes no forge." },
6061 dryRun: { type: "boolean" },
6162 reveal: REVEAL_ARG,
63 claim: { type: "string", enum: ["token"], description: "Claim it: answers its admin's token." },
6264 },
6365 required: ["name"],
6466 },
@@ -86,7 +88,7 @@ export const tool: Tool = {
8688 return good({
8789 says: !made
8890 ? `This is the plan; nothing was made. ${preview?.says ?? ""} Send dryRun: false to spawn.`
89 : `Spawned ${String(door.body["name"])} at ${String(door.body["url"])}. ${receipt?.says ?? ""}${again} ${reveal ? LINK_REVEALED : LINK_KEPT}${reached}`,
91 : `Spawned ${String(door.body["name"])} at ${String(door.body["url"])}. ${receipt?.says ?? ""}${again} ${typeof rest["token"] === "string" ? TOKEN_SECRET_WORDS : reveal ? LINK_REVEALED : LINK_KEPT}${reached}`,
9092 ...rest,
9193 ...(made ? {} : { where: WHERE_A_FORGE_LIVES }),
9294 ...(reveal ? { claimUrl } : {}),
src/spawn/door.ts +22 −1
@@ -13,6 +13,7 @@ import { nameShapeVerdict } from "./name_verdict.ts";
1313 import { linkRequestVisitor } from "../perf/visitor_link.ts";
1414 import { templateOfInput } from "../actions/template_timing.ts";
1515 import { startWatch, probeOf, type Probe } from "./live.ts";
16 import { claimByToken, claimOf, TOKEN_SECRET_WORDS } from "./headless_claim.ts";
1617 import { firstProof, homeBudgetOf, proves, reachWords, settleChild, type ChildReach } from "./reach.ts";
1718 import {
1819 forgeNameVerdict,
@@ -291,6 +292,12 @@ export async function spawnDoor(
291292 if (raw["dryRun"] !== undefined && typeof raw["dryRun"] !== "boolean")
292293 return invalid("dryRun", "must be true or false");
293294 const dry = raw["dryRun"] !== false;
295 // `claim: "token"`: the parent claims the child for the caller and answers the first admin's
296 // token.
297 const claiming = claimOf(raw["claim"]);
298 if (!claiming.ok) return invalid("claim", claiming.error);
299 const byToken = claiming.value;
300 if (byToken && user === undefined) return invalid("claim", "claiming by token is for a signed-in caller; a stranger opens the claim link");
294301 // A config (or a saved recipe) is the same four fields the request may carry at top level.
295302 let budgetWaits: number | undefined;
296303 if (raw["config"] !== undefined || raw["recipe"] !== undefined) {
@@ -441,6 +448,7 @@ export async function spawnDoor(
441448 const named = accountNamed(ctx.app, user, raw);
442449 if (named !== undefined && "status" in named) return named;
443450 const where = whereFor(ctx.app, planOf, named);
451 if (byToken && where.where === "cloud") return invalid("claim", "a forge on its own machine is claimed from its claim page; claim: \"token\" is for a forge that runs inside this one");
444452 const placeIn = raw["place"] ?? "";
445453 if (typeof placeIn !== "string" || placeIn.length > MAX_ID) return invalid("place", "must be a place id, provider:datacenter:size (GET /api/v1/places)");
446454 const asked = placeIn.trim();
@@ -609,11 +617,24 @@ export async function spawnDoor(
609617 if (proved !== undefined || (opts.page === true && !made.value.existed)) void settleChild(ctx.app, made.value.name);
610618 // The receipt names what was made, never what this request asked for.
611619 const receipt = receiptOf(made.value, user?.username ?? null);
620 // Claimed here, the link is spent and never shown; a claim that could not be made leaves the
621 // link unspent and in the answer, with why.
622 let headless: Record<string, unknown> = {};
623 let shown = made.value;
624 if (byToken && user !== undefined && !made.value.existed && made.value.claimUrl !== undefined) {
625 const claimed = await claimByToken(ctx.app, made.value, made.value.claimUrl, user);
626 if (claimed.ok) {
627 const { claimUrl: _spent, ...rest } = made.value;
628 shown = rest;

The claimError branches and the existed branch have no test; add them. Also add the MCP path test.

629 headless = { token: claimed.value.token, tokenExpiresAt: claimed.value.expiresAt, admin: { username: claimed.value.username, scope: claimed.value.scope, expiresIn: claimed.value.expiresIn }, tokenNote: TOKEN_SECRET_WORDS };
630 } else headless = { claimError: claimed.error };
631 } else if (byToken && made.value.existed) headless = { claimError: "this forge was already made: nothing was claimed and no token is shown again" };
612632 return {
613633 status: made.value.existed ? 200 : 201,
614634 body: {
615635 dryRun: false,
616 ...made.value,
636 ...shown,
637 ...headless,
617638 ...(receipt === undefined ? {} : { receipt }),
618639 ...(proved === undefined
619640 ? {}
src/spawn/headless_claim.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * Claiming a new child with no browser (`claim: "token"`): the parent redeems the child's own claim
3 * code at the child's `POST /api/v1/first-admin` (`actions/first_admin.ts`), as the person who
4 * spawned it, and hands back that admin's expiring token. The token is a live secret: it is
5 * answered once under the key `token`, which the idempotency table never keeps
6 * (`SHOWN_ONCE` in `http/server.ts`), and it is neither stored nor logged here.
7 */
8 import type { App } from "../app.ts";
9 import type { User } from "../core/users.ts";
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import { childPublicUrl, parentOrigin } from "./placement.ts";
12 import { homeBudgetOf, fetcherOf } from "./reach.ts";
13
14 export const CLAIM_TOKEN = "token";
15
16 /** What a person or an agent is told about the token, in the same words everywhere. */
17 export const TOKEN_SECRET_WORDS =
18 "The token is a live secret that acts as this forge's first admin. It is shown once, never stored here and not in the replay of this request: keep it now. It expires; use it on the child's /api/v1.";
19
20 export type ChildAdmin = { readonly username: string; readonly token: string; readonly scope: "admin"; readonly expiresAt: string; readonly expiresIn: number };
21
22 /** `claim` as the door takes it: nothing, or "token"; anything else is the caller's mistake. */
23 export function claimOf(raw: unknown): Result<boolean, string> {
24 if (raw === undefined || raw === null || raw === "") return ok(false);
25 return raw === CLAIM_TOKEN ? ok(true) : err(`must be "${CLAIM_TOKEN}" (the parent claims the child and answers its first admin's token) or left out`);
26 }
27
28 /**
29 * Whether `url` is the child this forge just made: the host it would give `name`, over https unless
30 * this forge itself is plain http. The claim code goes nowhere else.
31 */
32 export function isOwnChild(app: App, name: string, url: string): boolean {
33 try {
34 const at = new URL(url);
35 const own = new URL(childPublicUrl(name, parentOrigin(app.config)));
36 return at.hostname === own.hostname && (at.protocol === "https:" || own.protocol === "http:") && at.username === "" && at.password === "";
37 } catch {
38 return false;
outdated

Verify child.url is a host this forge made (its own domain, https outside tests) before posting the claim code to it.

39 }
40 }
41
42 /** Redeem a child's claim link as `user`; waits for the child to answer within the home budget. */
43 export async function claimByToken(
44 app: App,
45 child: { readonly name: string; readonly url: string },
46 claimUrl: string,
47 user: User,
48 ): Promise<Result<ChildAdmin, string>> {
49 if (!isOwnChild(app, child.name, child.url)) return err("the child's address is not one this forge made: the claim code was not sent");
50 const code = claimUrl.split("#")[1];
51 if (code === undefined || code === "") return err("the child gave no claim code");
52 // The child's founder account already holds the spawner's own name, so the first admin is
53 // `<name>-admin`, which the answer names.
54 const username = `${user.username.slice(0, 32)}-admin`;
55 const fetcher = fetcherOf(app);
56 const until = Date.now() + homeBudgetOf(app);
57 let last = "the child did not answer";
58 for (;;) {
59 try {
60 const res = await fetcher(`${child.url}/api/v1/first-admin`, {
61 method: "POST",
62 redirect: "manual",
63 signal: AbortSignal.timeout(10_000),
64 headers: { "content-type": "application/json", origin: child.url },
65 body: JSON.stringify({ code, username, email: user.email, scope: "admin" }),
66 });
67 const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
68 if (res.status === 201 && typeof body["token"] === "string" && typeof body["expiresAt"] === "string")
69 return ok({ username, token: body["token"], scope: "admin", expiresAt: body["expiresAt"], expiresIn: Number(body["expiresIn"]) });
70 last = `the child answered ${res.status}${typeof body["message"] === "string" ? `: ${body["message"].slice(0, 200)}` : ""}`;
71 // Refused is final; a child still starting (5xx, 404 from a proxy) is asked again.
72 if (res.status === 403 || res.status === 422 || res.status === 429) return err(last);
73 } catch (error) {
74 last = `the child did not answer (${String(error instanceof Error ? error.message : error).slice(0, 100)})`;
75 }
76 if (Date.now() >= until || app.closing.signal.aborted) return err(last);
77 await Bun.sleep(250);
78 }
79 }
src/spawn/reach.ts +3
@@ -110,6 +110,9 @@ export function useReachByDefault(o: Options): void {
110110 }
111111
112112 const optionsOf = (app: App): Options => options.get(app) ?? fallback;
113 /** How this forge asks a child's address: the test's fetch, else the real one. */
114 export const fetcherOf = (app: App): FetchLike => optionsOf(app).fetch ?? fetch;
outdated

This doc comment described homeBudgetOf; fetcherOf now splits them. Put fetcherOf above the comment.

115
113116 /** The most a spawn holds its reply for the new forge to come up and answer. */
114117 export const homeBudgetOf = (app: App): number => optionsOf(app).homeWaitMs ?? HOME_WAIT_MS;
115118 const off = (app: App): boolean => optionsOf(app).fetch === undefined && optionsOf(app).off === true;
src/tui/screens/child_token.ts added +33
@@ -0,0 +1,33 @@
1 /**
2 * The first admin's token of a forge this one just made and claimed (`claim: "token"`, the New
3 * forge screen's "Claim it here"). It is a live secret: drawn once, copied on `c`, kept nowhere,
4 * and gone when the dialog closes. `TOKEN_SECRET_WORDS` is what every door says about it.
5 */
6 import { TOKEN_SECRET_WORDS } from "../../spawn/headless_claim.ts";
7 import type { Ctx, Screen } from "../app/app.ts";
8 import { binding } from "../app/keys.ts";
9 import { wrap } from "../term/width.ts";
10 import { dialog } from "../ui/widgets.ts";
11
12 export function childTokenScreen(ctx: Ctx, forge: string, token: string, expiresAt: string): Screen {
13 return {
14 title: "Token",
15 keys: [binding(["c"], "copy"), binding(["esc", "q", "enter"], "close")],
16 render(area, s) {
17 dialog(s, area, ctx.theme.c, {
18 title: `${forge}: first admin's token`,
19 body: [token, "", `Expires ${expiresAt}.`, ...wrap(TOKEN_SECRET_WORDS, 60)],
20 actions: [{ label: "Copy" }, { label: "Close" }],
21 selected: 0,
22 width: Math.max(64, [...token].length + 4),
23 });
24 },
25 key(e) {
26 if (e.key === "c") {
27 ctx.copy(token);
28 ctx.toast("copied through the terminal", "success");
29 } else if (e.key === "esc" || e.key === "q" || e.key === "enter") ctx.pop();
30 return true;
31 },
32 };
33 }
src/tui/screens/newforge.ts +9
@@ -27,6 +27,7 @@ import { style } from "../term/style.ts";
2727 import { truncate } from "../term/width.ts";
2828 import { field } from "../ui/widgets.ts";
2929 import type { Session } from "../session.ts";
30 import { childTokenScreen } from "./child_token.ts";
3031 import { linkScreen, runAsync } from "./common.ts";
3132
3233 interface Spec {
@@ -57,6 +58,7 @@ const SPECS: readonly Spec[] = [
5758 { key: "size", label: "Size", hint: "small (default), medium, large or xlarge: the cell gets that CPU, memory and disk. Left and right choose.", choices: SIZE_CHOICES },
5859 { key: "template", label: "Template", hint: TEMPLATE_HINT, choices: TEMPLATE_CHOICES },
5960 { key: "migration", label: "Mode of the forked apps", hint: "own (default) or migration: the crew works to run each app natively there with parity to its copy here.", choices: ["own", "migration"] },
61 { key: "claim", label: "Claim it here", hint: "token: this forge claims it for you and shows its first admin's token once. Empty: you get a claim link.", choices: ["", "token"] },
6062 { key: "saveAs", label: "Save as recipe", hint: "A name to keep the apps and budget under, saved with the plan. Optional." },
6163 ];
6264
@@ -169,6 +171,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
169171 // Blank is the default: it is not recorded, as on the page.
170172 ...(val("template") === "" || val("template") === DEFAULT_TEMPLATE ? {} : { template: val("template") }),
171173 ...(val("plan") === "" ? {} : { plan: val("plan") }),
174 ...(val("claim") === "token" ? { claim: "token" } : {}),
172175 ...where,
173176 dryRun,
174177 };
@@ -261,6 +264,12 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str
261264 return;
262265 }
263266 const link = body["claimUrl"];
267 if (typeof body["token"] === "string") {
268 ctx.toast(`${String(body["name"] ?? val("name"))} is ready and claimed`, "success");
269 ctx.replace(childTokenScreen(ctx, String(body["name"] ?? val("name")), body["token"], String(body["tokenExpiresAt"] ?? "")));
270 return;
271 }
272 if (typeof body["claimError"] === "string") ctx.toast(`not claimed: ${body["claimError"]}`, "attn");
264273 const name = String(body["name"] ?? val("name"));
265274 if (typeof link === "string") {
266275 ctx.toast(`${name} is ready`, "success");
test/spawn-claim-branches.test.ts added +110
@@ -0,0 +1,110 @@
1 /**
2 * The branches of `claim: "token"` that do not end in a token: the child never answers or refuses
3 * (`claimUrl` stays unspent), a replay of a made forge, a forge on its own machine, and a child
4 * address that is not the one this forge made (the claim code is never sent there).
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 { createApp, type App } from "../src/app.ts";
11 import { addAccount, allowWrite, net } from "../src/actions/cloud.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { usePlacement, useProbe, spawnDoor } from "../src/spawn/door.ts";
14 import { claimByToken, isOwnChild } from "../src/spawn/headless_claim.ts";
15 import { hostedPlacement } from "../src/spawn/placement.ts";
16 import { useReach } from "../src/spawn/reach.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import "./helpers/roomy-disk.ts";
19
20 quietLogs();
21
22 net.fetch = async () => new Response(JSON.stringify({ login: "octo" }), { status: 200 });
23
24 describe("claim: token, without a token", () => {
25 let dir: string;
26 let app: App;
27 let user: User;
28 let admin: User;
29 let sent: { url: string; body: string }[] = [];
30 let answer: () => Promise<Response> = async () => new Response("{}", { status: 502 });
31
32 const ask = (name: string, extra: Record<string, unknown> = {}, as: User = user) => {
33 const url = new URL("https://forge.test/api/v1/forges");
34 const ctx = { app, request: new Request(url.href, { method: "POST" }), url, params: {}, auth: { user: as, scope: "rw" as const, via: "token" as const }, theme: undefined };
35 return spawnDoor(ctx, as, { name, apps: [], dryRun: false, claim: "token", ...extra });
36 };
37
38 beforeAll(async () => {
39 dir = await mkdtemp(join(tmpdir(), "forge-claim-branches-"));
40 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
41 const make = async (username: string, isAdmin: boolean) => {
42 const r = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@x.test`, password: "a-good-passphrase", isAdmin });
43 if (!r.ok) throw new Error(r.error);
44 return r.value;
45 };
46 user = await make("carol", false);
47 admin = await make("alice", true);
48 useProbe(app, () => async () => true);
49 usePlacement(app, hostedPlacement({ host: "forge.test" }));
50 useReach(app, {
51 homeWaitMs: 400,
52 fetch: async (url, init) => {
53 sent.push({ url: String(url), body: String(init?.body ?? "") });
54 return answer();
55 },
56 });
57 });
58 afterAll(async () => {
59 app.db.close();
60 await rm(dir, { recursive: true, force: true });
61 });
62
63 test("a child that refuses leaves the claim link unspent, with why", async () => {
64 answer = async () => new Response(JSON.stringify({ message: "that code is not valid" }), { status: 403 });
65 const made = await ask("refuser");
66 expect(made.status).toBe(201);
67 expect(made.body["claimError"]).toContain("403");
68 expect(made.body["claimError"]).toContain("that code is not valid");
69 expect(typeof made.body["claimUrl"]).toBe("string");
70 expect(made.body["token"]).toBeUndefined();
71 });
72
73 test("a child that never answers does too, after the home budget", async () => {
74 answer = async () => {
75 throw new Error("connection refused");
76 };
77 const made = await ask("silent");
78 expect(made.body["claimError"]).toContain("did not answer");
79 expect(typeof made.body["claimUrl"]).toBe("string");
80 expect(made.body["token"]).toBeUndefined();
81 });
82
83 test("a spawn that already exists claims nothing and says no token comes again", async () => {
84 sent = [];
85 const again = await ask("silent");
86 expect(again.status).toBe(200);
87 expect(again.body["claimError"]).toContain("already made");
88 expect(again.body["token"]).toBeUndefined();
89 expect(sent.filter((s) => s.url.includes("first-admin"))).toEqual([]);
90 });
91
92 test("a forge on its own machine is refused: claim token is for one inside this forge", async () => {
93 expect((await addAccount(app, admin, "digitalocean", "ledger", "dop_v1_" + "a".repeat(64))).ok).toBe(true);
94 expect(allowWrite(app, admin, "digitalocean", "ledger", true).ok).toBe(true);
95 const made = await ask("farway", { target: "digitalocean", account: "ledger" }, admin);
96 expect(made.status).toBe(422);
97 expect(String(made.body["message"])).toContain("claim");
98 expect(String(made.body["message"])).toContain("inside this one");
99 });
100
101 test("the claim code is sent only to the child this forge made", async () => {
102 sent = [];
103 expect(isOwnChild(app, "kid", "https://kid--forge.test")).toBe(true);
104 for (const bad of ["https://evil.test", "https://kid--evil.test", "http://kid--forge.test", "https://u:[email protected]", "not a url", "https://other--forge.test"])
105 expect(isOwnChild(app, "kid", bad)).toBe(false);
106 const refused = await claimByToken(app, { name: "kid", url: "https://evil.test" }, "https://kid--forge.test/claim#secretcode", user);
107 expect(refused.ok).toBe(false);
108 expect(sent).toEqual([]);
109 });
110 });
test/spawn-claim-token.test.ts added +136
@@ -0,0 +1,136 @@
1 /**
2 * An agent makes its own forge with no browser, over HTTP alone: an account, a password-minted
3 * token, a spawn with `claim: "token"` and the first admin's token working on the child.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { readdirSync } from "node:fs";
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 { serve, type Servers } from "../src/http/server.ts";
13 import { firstBoot } from "../src/spawn/first-boot.ts";
14 import { usePlacement, useProbe } from "../src/spawn/door.ts";
15 import { hostedPlacement } from "../src/spawn/placement.ts";
16 import { TOKEN_SECRET_WORDS } from "../src/spawn/headless_claim.ts";
17 import { useReach } from "../src/spawn/reach.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import "./helpers/roomy-disk.ts";
20
21 quietLogs();
22
23 const PASSWORD = "a-long-agent-passphrase-for-grokbot";
24
25 describe("claim: token", () => {
26 let dir: string;
27 let parent: App;
28 let parentServers: Servers;
29 let childServers: Servers | undefined;
30 // Every child booted so far, by its public label; a new label is the one directory not yet used.
31 const booted = new Map<string, { app: App; servers: Servers }>();
32 let mcpToken = "";
33 let base: string;
34
35 const json = (url: string, body: unknown, headers: Record<string, string> = {}) =>
36 fetch(url, { method: "POST", headers: { "content-type": "application/json", origin: new URL(url).origin, ...headers }, body: JSON.stringify(body) });
37
38 beforeAll(async () => {
39 dir = await mkdtemp(join(tmpdir(), "forge-claim-token-"));
40 parent = createApp({ dataDir: dir, port: 0 });
41 parentServers = await serve(parent);
42 base = parentServers.url;
43 useProbe(parent, () => async () => true);
44 usePlacement(parent, hostedPlacement({ host: "forge.test" }));
45 // The child's public address is answered by the child's own server, booted when first asked.
46 useReach(parent, {
47 homeWaitMs: 1000,
48 fetch: async (url, init) => {
49 const at = new URL(url);
50 const label = at.hostname.split("--")[0]!;
51 if (!at.hostname.includes("--")) return new Response("no", { status: 502 });
52 let up = booted.get(label);
53 if (up === undefined) {
54 const used = new Set([...booted.values()].map((b) => b.app.config.dataDir));
55 const body = readdirSync(join(dir, "children")).find((n) => !n.endsWith(".json") && !used.has(childDirOf(parent, n)))!;
56 const app = createApp({ dataDir: childDirOf(parent, body), port: 0 });
57 await firstBoot(app);
58 up = { app, servers: await serve(app) };
59 booted.set(label, up);
60 if (label === "maria") childServers = up.servers;
61 }
62 return fetch(`${up.servers.url}${at.pathname}${at.search}`, { ...init, headers: { ...(init?.headers as Record<string, string>), origin: up.servers.url } });
63 },
64 });
65 }, 30_000);
66
67 afterAll(async () => {
68 for (const b of booted.values()) {
69 b.servers.stop();
70 b.app.close();
71 }
72 parentServers.stop();
73 parent.close();
74 await rm(dir, { recursive: true, force: true });
75 });
76
77 test("account, token, spawn and the child's token, over HTTP alone", async () => {
78 // 1. The account, then a token from its password.
79 const made = await json(`${base}/api/v1/users`, { username: "grokbot", email: "[email protected]", password: PASSWORD });
80 expect(made.status).toBe(201);
81 const minted = await json(`${base}/api/v1/tokens`, { username: "grokbot", password: PASSWORD, scope: "rw", name: "agent" });
82 expect(minted.status).toBe(201);
83 const { token } = (await minted.json()) as { token: string };
84 const auth = { authorization: `Bearer ${token}` };
85
86 // 2. Spawn and claim in one call.
87 const spawned = await json(`${base}/api/v1/forges`, { name: "maria", size: "small", apps: [], dryRun: false, claim: "token" }, { ...auth, "idempotency-key": "k-1" });
88 const body = (await spawned.json()) as Record<string, any>;
89 expect(spawned.status).toBe(201);
90 expect(body.claimError).toBeUndefined();
91 expect(body.claimUrl).toBeUndefined();
92 expect(body.token.length).toBeGreaterThan(10);
93 expect(body.admin).toMatchObject({ username: "grokbot-admin", scope: "admin" });
94 expect(body.tokenNote).toContain("live secret");
95 expect(Date.parse(body.tokenExpiresAt)).toBeGreaterThan(Date.now());
96
97 // 3. The token works on the child.
98 const me = await fetch(`${childServers!.url}/api/v1/user`, { headers: { authorization: `Bearer ${body.token}` } });
99 expect(me.status).toBe(200);
100 expect(((await me.json()) as { username: string }).username).toBe("grokbot-admin");
101
102 mcpToken = token;
103
104 // A replay says it was shown; the table never kept the secret.
105 const replay = await json(`${base}/api/v1/forges`, { name: "maria", size: "small", apps: [], dryRun: false, claim: "token" }, { ...auth, "idempotency-key": "k-1" });
106 const again = (await replay.text()) as string;
107 expect(again).not.toContain(body.token);
108 const stored = parent.db.query("SELECT * FROM idempotency").all().map((r) => JSON.stringify(r)).join("");
109 expect(stored).not.toContain(body.token);
110 }, 30_000);
111
112 test("MCP spawn with claim says the token is a secret and carries it", async () => {
113 const res = await fetch(`${base}/mcp`, {
114 method: "POST",
115 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${mcpToken}` },
116 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "spawn", arguments: { name: "mcpkid", apps: [], dryRun: false, claim: "token" } } }),
117 });
118 const result = ((await res.json()) as any).result;
119 expect(result.isError).not.toBe(true);
120 const out = JSON.parse(result.content[0].text) as Record<string, any>;
121 expect(out.says).toContain(TOKEN_SECRET_WORDS);
122 expect(out.says).not.toContain(out.token);
123 expect(typeof out.token).toBe("string");
124 expect(out.claimUrl).toBeUndefined();
125 const me = await fetch(`${booted.get("mcpkid")!.servers.url}/api/v1/user`, { headers: { authorization: `Bearer ${out.token}` } });
126 expect(me.status).toBe(200);
127 }, 30_000);
128
129 test("claim is refused when it is not \"token\" and for a stranger", async () => {
130 const bad = await json(`${base}/api/v1/forges`, { name: "kid", apps: [], claim: "yes" });
131 expect(bad.status).toBe(422);
132 const stranger = await json(`${base}/api/v1/forges`, { name: "kid", apps: [], claim: "token" });
133 expect(stranger.status).toBe(422);
134 expect(((await stranger.json()) as { message: string }).message).toContain("signed-in");
135 });
136 });
test/tui-child-token.test.ts added +78
@@ -0,0 +1,78 @@
1 /**
2 * The terminal's door to `claim: "token"`: New forge's "Claim it here" field, and the dialog that
3 * shows the first admin's token once (`src/tui/screens/child_token.ts`).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createUser, type User } from "../src/core/users.ts";
11 import { usePlacement, useProbe } from "../src/spawn/door.ts";
12 import { hostedPlacement } from "../src/spawn/placement.ts";
13 import { useReach } from "../src/spawn/reach.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { newForgeScreen } from "../src/tui/screens/newforge.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { settleApp, settleUntil } from "./helpers/tui.ts";
19 import "./helpers/roomy-disk.ts";
20
21 quietLogs();
22
23 const SECRET = "fgt_terminal_door_secret_value_1234567890";
24 let dir: string;
25 let app: App;
26 let user: User;
27 let asked: string[] = [];
28
29 beforeAll(async () => {
30 dir = await mkdtemp(join(tmpdir(), "forge-tui-child-token-"));
31 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
32 const r = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" });
33 if (!r.ok) throw new Error(r.error);
34 user = r.value;
35 useProbe(app, () => async () => true);
36 usePlacement(app, hostedPlacement({ host: "forge.test" }));
37 useReach(app, {
38 homeWaitMs: 400,
39 fetch: async (url, init) => {
40 asked.push(String(url));
41 if (!String(url).endsWith("/api/v1/first-admin")) return new Response("{}", { status: 502 });
42 void init;
43 return new Response(JSON.stringify({ token: SECRET, expiresAt: "2030-01-01T00:00:00.000Z", expiresIn: 86400 }), { status: 201 });
44 },
45 });
46 });
47 afterAll(async () => {
48 app.db.close();
49 await rm(dir, { recursive: true, force: true });
50 });
51
52 test("Claim it here: token spawns, claims and shows the token once, with the secret's words", async () => {
53 const terminal = headlessTerminal(120, 40);
54 const { app: tui, session } = createForgeApp(app, { sshUsername: "carol", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }, { terminal, exitHooks: false });
55 tui.start();
56 tui.ctx.push(newForgeScreen(session, tui.ctx));
57 try {
58 await settleApp(tui);
59 terminal.feed("tokenkid");
60 terminal.feed("\t".repeat(12));
61 await settleApp(tui);
62 expect(tui.screen.toText()).toContain("Claim it here");
63 terminal.feed("\x1b[C");
64 terminal.feed("\x10");
65 await settleApp(tui);
66 terminal.feed("\r");
67 await settleUntil(tui, "live secret");
68 const screen = tui.screen.toText();
69 expect(asked.some((u) => u.endsWith("/api/v1/first-admin"))).toBe(true);
70 expect(screen).toContain(SECRET);
71 expect(screen).toContain("live secret");
72 terminal.feed("q");
73 await settleApp(tui);
74 expect(tui.screen.toText()).not.toContain(SECRET);
75 } finally {
76 tui.stop?.();
77 }
78 });
test/tui-newforge-recipes.test.ts +3 −3
@@ -66,7 +66,7 @@ async function open(keys: string): Promise<string> {
6666
6767 test("Save as recipe keeps the apps with their modes and the budget, with the plan", async () => {
6868 const keys =
69 "zed" + TAB.repeat(3) + "alice/shop:autonomous, alice/old:migration" + TAB.repeat(4) + "20" + TAB.repeat(5) + "client kit" + "\x10";
69 "zed" + TAB.repeat(3) + "alice/shop:autonomous, alice/old:migration" + TAB.repeat(4) + "20" + TAB.repeat(6) + "client kit" + "\x10";
7070 const screen = await open(keys);
7171 // Kept before the plan is asked for; the plan itself may refuse apps this forge does not have.
7272 expect(listRecipes(dir, admin.id).map((r) => r.name)).toEqual(["client kit"]);
@@ -78,12 +78,12 @@ test("Save as recipe keeps the apps with their modes and the budget, with the pl
7878 });
7979
8080 test("a bad recipe name is refused beside its field and nothing is kept", async () => {
81 const screen = await open("zed" + TAB.repeat(12) + "no/slash!" + "\x10");
81 const screen = await open("zed" + TAB.repeat(13) + "no/slash!" + "\x10");
8282 expect(screen).toContain("recipe name is 1-40 characters");
8383 expect(listRecipes(dir, admin.id).map((r) => r.name)).toEqual(["client kit"]);
8484 });
8585
8686 test("Spawn from recipe is offered once there is one", async () => {
87 const screen = await open(TAB.repeat(13));
87 const screen = await open(TAB.repeat(14));
8888 expect(screen).toContain("Spawn from recipe");
8989 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs