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

The child's first boot: its direction, its own tokens, its domain, and one claim link for its owner #550

Closed opened this
Closed without merging

scout/forge:scout/422-the-child-s-first-boot-its-direction-its → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +437 −44
docs/SPAWN.md +4
@@ -21,6 +21,8 @@ and user accounts. The child mints its own. A test in #420 and #422 proves it.
2121 `src/actions/spawn.ts` (#421): the child lives in `<data>/children/<bodyId>`; the parent keeps a ledger line in `<data>/spawn/<name>.json` so a retry resumes or answers. Subscription names are in the plan but not yet created in the child (a subscription is a token).
2222
2323 | #422 | first boot: direction, own tokens, domain, claim link | #421 |
24 `src/spawn/firstboot.ts` (#422) runs at the end of the copy: the spawner's `direction` words become one direction issue on the child's first repo, held by its planner (the crew member named `planner`, else the first carried); the child gets its own SSH host key in its own `ssh/`; and one claim link (`/claim/<secret>`, 7 days, single use, hash stored) is returned once to the spawner, never logged or kept. GET on the link only asks; POST redeems and sets an HttpOnly session. The claim page prints `FORGE_APP_SSH` verbatim, or says the terminal is off. No API tokens are minted yet: the first token the child needs is the follower's, in #423.
25
2426 | #423 | cross-forge following over HTTPS, read-only token | #422 |
2527 | #424 | propose upstream as a pull on the parent | #423 |
2628 | #425 | family tree across forges, signed heartbeats | #423 |
@@ -36,3 +38,5 @@ as a second implementation of the placement seam (#427), in their own issue.
3638 - The parent never reaches into a child; children report in with a signed
3739 heartbeat carrying counts and version only.
3840 - A proposal can only create branches under `child/<name>/` and open pulls.
41
42 First boot was checked on a clean data directory: `/healthz` answers 200 in about 11 ms once the server is up, and `/` in under 100 ms cold.
forge.json +1 −1
@@ -6,7 +6,7 @@
66 "ready": 90
77 },
88 "check": {
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits crew-parks crew-sandbox steer session-settle landing decide ledger checks dependencies autonomy studio studio-words forks fork-flow cross-repo-pull pulls apps apps-adversarial apps-busy apps-token surfaces-adversarial orgs web git-trust helpers shards migrate vitals guard asks feed feed-page offline share cloud run-secrets forge-cloudflare usage credentials standing board-windows spawn-plan spawn web-apps fleet-ops meter told-by",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits crew-parks crew-sandbox steer session-settle landing decide ledger checks dependencies autonomy studio studio-words forks fork-flow cross-repo-pull pulls apps apps-adversarial apps-busy apps-token surfaces-adversarial orgs web git-trust helpers shards migrate vitals guard asks feed feed-page offline share cloud run-secrets forge-cloudflare usage credentials standing board-windows spawn-plan spawn web-apps fleet-ops meter told-by first-boot",
1010 "timeout": 1800
1111 }
1212 }
src/actions/spawn.ts +18 −3
@@ -26,6 +26,7 @@ import { err, ok, type Result } from "../kernel/result.ts";
2626 import { crossOrigin } from "../http/context.ts";
2727 import type { Placement } from "../spawn/placement.ts";
2828 import { planSpawn, type SpawnInput, type SpawnPlan, type SpawnSource } from "../spawn/plan.ts";
29 import { firstBoot, type FirstBoot } from "../spawn/firstboot.ts";
2930 import { requireUser } from "./access.ts";
3031
3132 export interface Spawned {
@@ -35,6 +36,11 @@ export interface Spawned {
3536 readonly bodyId: string;
3637 /** True when this call found the child already made and changed nothing. */
3738 readonly existed: boolean;
39 /**
40 * The child's first boot, present only on the call that made it: the claim
41 * link is shown once and cannot be read back, so a retry answers without it.
42 */
43 readonly boot?: FirstBoot;
3844 }
3945
4046 export type SpawnError =
@@ -155,6 +161,7 @@ async function make(
155161
156162 const copied = await copyInto(app, owner, plan, ledger);
157163 if (!copied.ok) return fail(copied.error);
164 const boot = copied.value;
158165
159166 ledger.done = true;
160167 await writeLedger(app, ledger);
@@ -163,7 +170,7 @@ async function make(
163170 actorId: owner.id,
164171 payload: { name: plan.name, org: plan.org, url: ledger.url, apps: plan.apps.map((a) => a.ref) },
165172 });
166 return ok({ name: plan.name, org: plan.org, url: ledger.url, bodyId: ledger.bodyId, existed: false });
173 return ok({ name: plan.name, org: plan.org, url: ledger.url, bodyId: ledger.bodyId, existed: false, boot });
167174 }
168175
169176 /** Every step skips what is already there, so a resumed child is finished, not doubled. */
@@ -172,7 +179,7 @@ async function copyInto(
172179 owner: User,
173180 plan: SpawnPlan,
174181 ledger: Ledger,
175 ): Promise<Result<void, string>> {
182 ): Promise<Result<FirstBoot, string>> {
176183 const dir = childDirOf(app, ledger.bodyId);
177184 await mkdir(dir, { recursive: true });
178185 const child = createApp({ dataDir: dir });
@@ -185,6 +192,7 @@ async function copyInto(
185192 const made = await createUser(child.db, {
186193 username: owner.username,
187194 email: `${owner.username}@spawn.forge.invalid`,
195 isAdmin: true,
188196 });
189197 return made.ok ? made.value : undefined;
190198 })());
@@ -247,7 +255,14 @@ async function copyInto(
247255 join(dir, "parent.json"),
248256 JSON.stringify({ upstream, name: plan.name, org: plan.org }),
249257 );
250 return ok();
258 return ok(
259 firstBoot(child, {
260 founder,
261 direction: plan.direction,
262 url: ledger.url,
263 agents: plan.briefs.map((b) => b.agent),
264 }),
265 );
251266 } finally {
252267 child.close();
253268 }
src/core/claims.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * Claim links: one single-use, expiring secret that hands a forge's first
3 * account to a person. The link carries the secret; the database holds only
4 * its hash, so a leaked database never yields a usable claim. Redeeming is
5 * one conditional UPDATE — two people racing on one link cannot both win.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { sha256 } from "../kernel/hash.ts";
10 import { secret } from "../kernel/id.ts";
11 import { err, ok, type Result } from "../kernel/result.ts";
12 import { getUserById, type User } from "./users.ts";
13
14 export const CLAIM_TTL_MS = 7 * 24 * 60 * 60 * 1000;
15
16 /** Mint a claim for a user. Any earlier unused claim for them is revoked. */
17 export function mintClaim(
18 db: Database,
19 userId: string,
20 now: Date = new Date(),
21 ): { token: string; expiresAt: Date } {
22 const token = secret();
23 const expiresAt = new Date(now.getTime() + CLAIM_TTL_MS);
24 db.query("DELETE FROM claim WHERE user_id = ?1 AND used_at IS NULL").run(userId);
25 db.query("INSERT INTO claim (token_hash, user_id, expires_at) VALUES (?1, ?2, ?3)").run(
26 sha256(token),
27 userId,
28 expiresAt.toISOString(),
29 );
30 return { token, expiresAt };
31 }
32
33 /** Is this claim still good? Reads only; used to draw the confirm page. */
34 export function claimOpen(db: Database, token: string, now: Date = new Date()): boolean {
35 return (
36 db
37 .query("SELECT 1 FROM claim WHERE token_hash = ?1 AND used_at IS NULL AND expires_at > ?2")
38 .get(sha256(token), now.toISOString()) !== null
39 );
40 }
41
42 export function redeemClaim(
43 db: Database,
44 token: string,
45 now: Date = new Date(),
46 ): Result<User, "invalid_claim"> {
47 const hash = sha256(token);
48 const row = db
49 .query<{ user_id: string }, [string, string]>(
50 "UPDATE claim SET used_at = ?2 WHERE token_hash = ?1 AND used_at IS NULL AND expires_at > ?2 RETURNING user_id",
51 )
52 .get(hash, now.toISOString());
53 const user = row ? getUserById(db, row.user_id) : undefined;
54 return user ? ok(user) : err("invalid_claim");
55 }
src/core/schema.ts +10 −37
@@ -81,7 +81,6 @@ export const migrations: readonly string[] = [
8181 );
8282 CREATE INDEX delivery_due ON webhook_delivery(state, next_try_at);
8383 `,
84
8584 // 2 — conversations: issues and (later) pulls share one table, one number
8685 // sequence per repo, one comment stream, one label system.
8786 `
@@ -127,7 +126,6 @@ export const migrations: readonly string[] = [
127126 PRIMARY KEY (issue_id, label_id)
128127 );
129128 `,
130
131129 // 3 — pull requests: a 1:1 extension of an issue row, plus review-comment
132130 // anchoring that survives a force-push (path/line + the line's content hash).
133131 `
@@ -151,7 +149,6 @@ export const migrations: readonly string[] = [
151149 ALTER TABLE comment ADD COLUMN line_hash TEXT;
152150 ALTER TABLE comment ADD COLUMN outdated INTEGER NOT NULL DEFAULT 0;
153151 `,
154
155152 // 4 — forks: a repo may descend from another. The git objects are shared via
156153 // alternates (instant, storage-bounded); the parent link records lineage and
157154 // gates the detach-before-delete path. A pull's head may live in another repo
@@ -162,7 +159,6 @@ export const migrations: readonly string[] = [
162159
163160 ALTER TABLE pull ADD COLUMN head_repo_id TEXT REFERENCES repo(id);
164161 `,
165
166162 // 5 — organizations and teams. An org is a user row with kind 'org' (so it
167163 // owns repos through the same owner_id, no repo change). Teams belong to an
168164 // org, carry a permission level, and have members; a user's access to an
@@ -187,7 +183,6 @@ export const migrations: readonly string[] = [
187183 );
188184 CREATE INDEX team_member_user ON team_member(user_id);
189185 `,
190
191186 // 6 — SSH public keys. A user may register keys that authenticate them on
192187 // the SSH listener. The wire blob is stored as-is (base64); the OpenSSH
193188 // SHA256 fingerprint is the lookup key and is unique across the forge, so a
@@ -205,7 +200,6 @@ export const migrations: readonly string[] = [
205200 );
206201 CREATE INDEX user_key_user ON user_key(user_id);
207202 `,
208
209203 // 7 — per-user interface preferences (the terminal's theme, today). Not
210204 // platform state: nothing outside the surface that wrote it consumes these,
211205 // so they carry no event and rebuilding one costs a keystroke.
@@ -217,7 +211,6 @@ export const migrations: readonly string[] = [
217211 PRIMARY KEY (user_id, key)
218212 );
219213 `,
220
221214 // 8 — origins. A connected account on another forge (GitHub, Forgejo,
222215 // Gitea). Mirrored repos hang off an origin: their git objects are fetched
223216 // from it on a schedule and their issues/pulls/comments are an index over
@@ -293,7 +286,6 @@ export const migrations: readonly string[] = [
293286 PRIMARY KEY (user_id, repo_id)
294287 );
295288 `,
296
297289 // 9 — OAuth for origins. A pasted token is the fallback, not the front
298290 // door: GitHub's device grant works from a terminal with no browser, and
299291 // Forgejo's authorization code + PKCE works from any browser, including
@@ -360,7 +352,6 @@ export const migrations: readonly string[] = [
360352 CREATE UNIQUE INDEX oauth_flow_state ON oauth_flow(state_hash);
361353 CREATE INDEX oauth_flow_user ON oauth_flow(user_id, id);
362354 `,
363
364355 // 10 — a short link for a connect in flight.
365356 //
366357 // The device grant asks a person to open a URL on a *different* device. In
@@ -379,7 +370,6 @@ export const migrations: readonly string[] = [
379370 ALTER TABLE oauth_flow ADD COLUMN target_enc TEXT NOT NULL DEFAULT '';
380371 CREATE UNIQUE INDEX oauth_flow_short ON oauth_flow(short_code);
381372 `,
382
383373 // 11 — counts on a list, and the index that keeps a search off a table
384374 // scan. A repo row is useless without "how much is open here", and asking
385375 // per row is the N+1 that turns fifty repos into a hundred queries; the
@@ -400,7 +390,6 @@ export const migrations: readonly string[] = [
400390 -- this the ORDER BY is a scan of every issue in the forge.
401391 CREATE INDEX issue_repo_updated ON issue(repo_id, updated_at);
402392 `,
403
404393 // 12 — the indexes a busy forge needs, and one small table for retries.
405394 //
406395 // Every index here removes a scan that `EXPLAIN QUERY PLAN` showed on a
@@ -452,7 +441,6 @@ export const migrations: readonly string[] = [
452441 );
453442 CREATE INDEX idempotency_expiry ON idempotency(expires_at);
454443 `,
455
456444 // 13 — review states, thread resolution, and the fork a mirror descends
457445 // from.
458446 //
@@ -506,7 +494,6 @@ export const migrations: readonly string[] = [
506494 ALTER TABLE repo ADD COLUMN origin_fork_of TEXT;
507495 ALTER TABLE origin_repo ADD COLUMN fork_of TEXT;
508496 `,
509
510497 // 14 — apps, runs, and the crew (docs/APPS.md).
511498 //
512499 // An *app* is a repository that runs. The row holds only what git cannot:
@@ -599,7 +586,6 @@ export const migrations: readonly string[] = [
599586 );
600587 CREATE INDEX repo_crew_user ON repo_crew(user_id);
601588 `,
602
603589 // 15 — an app's environment.
604590 //
605591 // The secrets an app reads at start-up (an admin password, a payment
@@ -618,7 +604,6 @@ export const migrations: readonly string[] = [
618604 PRIMARY KEY (app_id, name)
619605 );
620606 `,
621
622607 // 16 — a paused run.
623608 //
624609 // A run the provider turned away (a rate limit, a usage window) is
@@ -629,7 +614,6 @@ export const migrations: readonly string[] = [
629614 ALTER TABLE run ADD COLUMN not_before TEXT;
630615 ALTER TABLE run ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0;
631616 `,
632
633617 // 17 — checks.
634618 //
635619 // A repository's own check (`check` in forge.json) runs as a run of a
@@ -670,7 +654,6 @@ export const migrations: readonly string[] = [
670654 CREATE INDEX run_issue ON run(issue_id, id DESC) WHERE issue_id IS NOT NULL;
671655 CREATE INDEX run_queue ON run(state, id) WHERE state IN ('queued','running');
672656 `,
673
674657 // 18 — a run's lease.
675658 //
676659 // The process working a run renews this every so often; a running run
@@ -680,12 +663,10 @@ export const migrations: readonly string[] = [
680663 `
681664 ALTER TABLE run ADD COLUMN heartbeat_at TEXT;
682665 `,
683
684666 // 19 — how many turns an agent's run took, beside what it cost.
685667 `
686668 ALTER TABLE run ADD COLUMN turns INTEGER NOT NULL DEFAULT 0;
687669 `,
688
689670 // 20 — issues that depend on issues: one row per edge, the plan itself.
690671 `
691672 CREATE TABLE issue_dependency (
@@ -697,7 +678,6 @@ export const migrations: readonly string[] = [
697678 );
698679 CREATE INDEX issue_dependency_blocker ON issue_dependency(blocked_by_id);
699680 `,
700
701681 // 21 — a repository can run on its own: how much, on what direction, with
702682 // what ceiling; and each crew member has a role in it.
703683 `
@@ -709,7 +689,6 @@ export const migrations: readonly string[] = [
709689 ALTER TABLE repo ADD COLUMN direction_issue_id TEXT REFERENCES issue(id) ON DELETE SET NULL;
710690 ALTER TABLE repo_crew ADD COLUMN role TEXT NOT NULL DEFAULT 'builder';
711691 `,
712
713692 // 22 — the decision ledger: every fixed-choice decision the crew's
714693 // decider made, with what it saw, what it answered, and what came of it.
715694 `
@@ -730,7 +709,6 @@ export const migrations: readonly string[] = [
730709 CREATE INDEX decision_issue ON decision(issue_id, kind, created_at);
731710 CREATE INDEX decision_repo ON decision(repo_id, created_at);
732711 `,
733
734712 // 23 — the look: a picture of an environment at a commit, at each of two
735713 // widths, or the reason there is none. Rows go with the app.
736714 `
@@ -746,7 +724,6 @@ export const migrations: readonly string[] = [
746724 UNIQUE (app_id, env, commit_oid, kind)
747725 );
748726 `,
749
750727 // 24 — a variable has a scope: every environment, production only, or
751728 // previews only, so a preview can carry a test key where production
752729 // carries the live one. The scope joins the key, which SQLite cannot add
@@ -768,7 +745,6 @@ export const migrations: readonly string[] = [
768745 DROP TABLE app_env;
769746 ALTER TABLE app_env_scoped RENAME TO app_env;
770747 `,
771
772748 // 25 — what a running app said when the forge knocked on its doors and
773749 // compared with its contract: one row per probe, kept, so the audit can
774750 // show the last word and what changed.
@@ -808,13 +784,11 @@ export const migrations: readonly string[] = [
808784 CREATE INDEX subscription_grant_scope ON subscription_grant (scope_id, agent_id);
809785 ALTER TABLE run ADD COLUMN subscription_id TEXT;
810786 `,
811
812787 // 27 — the moment a deploy started serving: set once, at the swap-in,
813788 // distinct from `finished_at` which waits on the tests beside it.
814789 `
815790 ALTER TABLE run ADD COLUMN serving_at TEXT;
816791 `,
817
818792 // 28 — a failed check's own detail: the pass/fail counts and the first
819793 // few failing names, recognised once from a `bun test` tail as the run
820794 // finishes (`checks/bun-test.ts`) and stored as JSON beside the run, so a
@@ -824,7 +798,6 @@ export const migrations: readonly string[] = [
824798 `
825799 ALTER TABLE run ADD COLUMN check_detail TEXT NOT NULL DEFAULT '';
826800 `,
827
828801 // 29 — a third width: thumb, a picture taken small for a slot that only
829802 // ever showed one small, instead of a full phone or desktop picture
830803 // squeezed into it. SQLite's CHECK cannot be altered in place, so the
@@ -845,7 +818,6 @@ export const migrations: readonly string[] = [
845818 DROP TABLE look;
846819 ALTER TABLE look_new RENAME TO look;
847820 `,
848
849821 // 30 — take it back: a pull that reverts another, named explicitly rather
850822 // than sniffed from its title. `reverts_issue_id` points at the issue the
851823 // shipped pull was (a pull is its own issue), so "was this already taken
@@ -854,7 +826,6 @@ export const migrations: readonly string[] = [
854826 ALTER TABLE pull ADD COLUMN reverts_issue_id TEXT REFERENCES issue(id) ON DELETE SET NULL;
855827 CREATE INDEX pull_reverts ON pull(reverts_issue_id) WHERE reverts_issue_id IS NOT NULL;
856828 `,
857
858829 // 31 — a look knows which page it is of: `app.looks` in `forge.json` can
859830 // name more than the home page. `page` defaults to `/`, so every row
860831 // taken before this migration reads as exactly what it always was — a
@@ -879,7 +850,6 @@ export const migrations: readonly string[] = [
879850 DROP TABLE look;
880851 ALTER TABLE look_new RENAME TO look;
881852 `,
882
883853 // 32 — an app's own domains. One host names one app's production; the
884854 // token is published in DNS to prove the name is held, so it is not a
885855 // secret. `verified_at` is set by the first check that finds the proof
@@ -898,7 +868,6 @@ export const migrations: readonly string[] = [
898868 );
899869 CREATE INDEX app_domain_app ON app_domain(app_id);
900870 `,
901
902871 // 33 — where a repository's next tell comes from when nobody is typing:
903872 // an Instagram account whose latest Reel's top comment becomes the crew's
904873 // next tell, once a day at `at_utc`. The token is sealed under the forge's
@@ -922,7 +891,6 @@ export const migrations: readonly string[] = [
922891 );
923892 CREATE INDEX prompt_source_repo ON prompt_source(repo_id);
924893 `,
925
926894 // 34 — forge-level secrets: credentials the forge itself needs, sealed
927895 // under AAD `secret:<scope>:<name>` and never read back. `scope_id` is ''
928896 // for the forge, an org's or a repo's id otherwise.
@@ -937,7 +905,6 @@ export const migrations: readonly string[] = [
937905 PRIMARY KEY (name, scope, scope_id)
938906 );
939907 `,
940
941908 // 35 — what a viewer did with a feed item: opened it, dwelled on it,
942909 // dismissed it, muted its app. One row per act; the feed's affinity is
943910 // these, counted with a decay. `item_id` is the feed's own id, and
@@ -956,7 +923,6 @@ export const migrations: readonly string[] = [
956923 );
957924 CREATE INDEX interaction_viewer ON interaction(viewer_id, id);
958925 `,
959
960926 // 36 — a share: one item, one sender, one recipient. A share is delivered
961927 // (it shows in the recipient's feed, boosted), queued (the recipient's
962928 // daily budget is spent; it waits and decays) or dropped (it decayed).
@@ -980,7 +946,6 @@ export const migrations: readonly string[] = [
980946 CREATE INDEX share_recipient ON share(recipient_id, state);
981947 CREATE INDEX share_sender ON share(sender_id, state);
982948 `,
983
984949 // 37 — the usage ledger (`core/usage.ts`): what each agent run spent,
985950 // attributed to subscription, app, agent and issue. `subscription_id` is
986951 // text, not a reference: a removed account's spend stays counted.
@@ -1025,7 +990,6 @@ export const migrations: readonly string[] = [
1025990 CREATE INDEX IF NOT EXISTS usage_repo ON usage(repo_id, at);
1026991 CREATE INDEX IF NOT EXISTS usage_subscription ON usage(subscription_id, at);
1027992 `,
1028
1029993 // 38 — a subscription's standing (`core/standing.ts`): the last time the
1030994 // provider said each window (5-hour, weekly) was full and when it resets,
1031995 // and the share of every window the operator keeps for people.
@@ -1081,7 +1045,6 @@ export const migrations: readonly string[] = [
10811045 PRIMARY KEY (operation_id, position)
10821046 );
10831047 `,
1084
10851048 // 41 — the meter (`core/meter.ts`): what an app used, in the two
10861049 // quantities a forge charges for. `meter` is one row per awake interval
10871050 // of an environment, `ended` NULL while it runs and `beat_at` the last
@@ -1172,4 +1135,14 @@ export const migrations: readonly string[] = [
11721135 OR body LIKE '%without a pull: cancelled'
11731136 OR body LIKE '%interrupted by a restart%');
11741137 `,
1138 // 44 — claim links (`core/claims.ts`): a single-use, expiring secret that
1139 // hands a spawned forge's first account to a person. Only the hash is kept.
1140 `
1141 CREATE TABLE claim (
1142 token_hash TEXT PRIMARY KEY,
1143 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
1144 expires_at TEXT NOT NULL,
1145 used_at TEXT
1146 );
1147 `,
11751148 ];
src/crew/autonomy.ts +1 −1
@@ -694,7 +694,7 @@ export function truncateAtWord(text: string, limit: number): string {
694694 * The issue the planner works from: the direction, as an open issue the
695695 * run can be about. Made once, kept, and never counted as work.
696696 */
697 function ensureDirectionIssue(
697 export function ensureDirectionIssue(
698698 app: App,
699699 by: User,
700700 repo: Repo,
src/http/server.ts +3
@@ -5,6 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { claimPage, claimSubmit } from "../web/pages/claim.ts";
89 import { canRead, canWrite, getRepo, getRepoById } from "../core/repos.ts";
910 import { trackPullHead } from "../core/pulls.ts";
1011 import { createRepo } from "../actions/repos.ts";
@@ -424,6 +425,8 @@ export function buildRouter(): Router<Handler> {
424425 router.add("GET", "/", home);
425426 router.add("GET", "/signin", signinPage);
426427 router.add("POST", "/signin", signinSubmit);
428 router.add("GET", "/claim/:token", claimPage);
429 router.add("POST", "/claim/:token", claimSubmit);
427430 router.add("GET", "/signup", signupPage);
428431 router.add("POST", "/signup", signupSubmit);
429432 router.add("POST", "/logout", logoutSubmit);
src/spawn/firstboot.ts added +75
@@ -0,0 +1,75 @@
1 /**
2 * A child's first boot: what turns a copied forge into one that is usable
3 * and owned. It writes the direction (the spawner's words) as one issue held
4 * by a planner, gives the child its own SSH host key, and mints one claim
5 * link for the new owner. Every step is idempotent: a resumed spawn finds the
6 * direction issue and the host key where the first try left them, and only
7 * the claim is made again (the older one is revoked), because a claim's
8 * secret is shown once and cannot be read back.
9 *
10 * Nothing here reads the parent: the child's keys come from its own data
11 * directory and its own randomness.
12 */
13
14 import { join } from "node:path";
15 import type { App } from "../app.ts";
16 import { assignIssue } from "../actions/issues.ts";
17 import { addCrew, listCrewRoles, setCrewRole } from "../core/agents.ts";
18 import { mintClaim } from "../core/claims.ts";
19 import { getRepoById, listEveryRepo, updateRepoSettings } from "../core/repos.ts";
20 import type { User } from "../core/users.ts";
21 import { getUserByName } from "../core/users.ts";
22 import { ensureDirectionIssue } from "../crew/autonomy.ts";
23 import { loadOrCreateHostKey } from "../ssh/keys.ts";
24
25 export interface FirstBoot {
26 /** Where the owner claims the forge: shown once, to the spawner. */
27 readonly claimLink: string;
28 readonly expiresAt: string;
29 /** The child's own SSH host key fingerprint; never the parent's. */
30 readonly hostKey: string;
31 /** The planner holding the direction issue, when the crew had one. */
32 readonly planner: string | undefined;
33 /** "owner/name#number" of the direction issue, when there was a repo and words. */
34 readonly direction: string | undefined;
35 }
36
37 export function firstBoot(
38 child: App,
39 input: { founder: User; direction: string; url: string; agents: readonly string[] },
40 ): FirstBoot {
41 const hostKey = loadOrCreateHostKey(join(child.config.dataDir, "ssh")).publicKey.fingerprint;
42
43 let direction: string | undefined;
44 let planner: string | undefined;
45 // The direction lives on the child's first repository, by name order.
46 const repo = listEveryRepo(child.db)[0];
47 if (repo && input.direction !== "") {
48 const set = repo.autonomyDirection === "" ? updateRepoSettings(child.db, repo, { autonomyDirection: input.direction }) : repo;
49 // Once: ensureDirectionIssue keeps the one it made, and a planner already holding it is left alone.
50 const issue = ensureDirectionIssue(child, input.founder, set);
51 if (issue) {
52 direction = `${repo.ownerName}/${repo.name}#${issue.number}`;
53 const name = input.agents.includes("planner") ? "planner" : input.agents[0];
54 const agent = name === undefined ? undefined : getUserByName(child.db, name);
55 if (agent && issue.assigneeId === null) {
56 addCrew(child.db, repo.id, agent.id, input.founder.id);
57 const current = getRepoById(child.db, repo.id)!;
58 if (!listCrewRoles(child.db, current.id).some((c) => c.agent.user.id === agent.id && c.role === "planner"))
59 setCrewRole(child.db, current.id, agent.id, "planner");
60 if (assignIssue(child, input.founder, current, issue, agent).ok) planner = agent.username;
61 } else if (issue.assigneeId !== null) {
62 planner = issue.assigneeName ?? undefined;
63 }
64 }
65 }
66
67 const claim = mintClaim(child.db, input.founder.id);
68 return {
69 claimLink: `${input.url.replace(/\/+$/, "")}/claim/${claim.token}`,
70 expiresAt: claim.expiresAt.toISOString(),
71 hostKey,
72 planner,
73 direction,
74 };
75 }
src/spawn/plan.ts +15 −1
@@ -13,6 +13,7 @@ export const MAX_APPS = 50;
1313 export const MAX_BRIEFS = 100;
1414 export const MAX_SUBSCRIPTIONS = 200;
1515 export const MAX_BRIEF_CHARS = 20_000;
16 export const MAX_DIRECTION_CHARS = 2_000;
1617
1718 const NAME = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/;
1819 const APP_REF = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
@@ -36,6 +37,8 @@ export interface SpawnInput {
3637 readonly apps: unknown;
3738 readonly carryBriefs: unknown;
3839 readonly carrySubscriptions: unknown;
40 /** What the new forge is for, in the spawner's words. Optional. */
41 readonly direction?: unknown;
3942 }
4043
4144 /** What the parent has to offer. Extra fields are ignored, never copied. */
@@ -58,6 +61,8 @@ export interface SpawnPlan {
5861 readonly apps: readonly PlannedApp[];
5962 readonly briefs: readonly CrewBrief[];
6063 readonly subscriptions: readonly string[];
64 /** What the child is for; the first boot writes it as the direction issue. */
65 readonly direction: string;
6166 }
6267
6368 export interface DryRun {
@@ -100,6 +105,15 @@ export function planSpawn(
100105 if (typeof input.carryBriefs !== "boolean") return refuse("carryBriefs", "must be true or false");
101106 if (typeof input.carrySubscriptions !== "boolean") return refuse("carrySubscriptions", "must be true or false");
102107
108 let direction = "";
109 if (input.direction !== undefined) {
110 if (typeof input.direction !== "string") return refuse("direction", "direction must be text");
111 direction = input.direction.trim();
112 if (direction.length > MAX_DIRECTION_CHARS) return refuse("direction", `direction is at most ${MAX_DIRECTION_CHARS} characters`);
113 // eslint-disable-next-line no-control-regex
114 if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(direction)) return refuse("direction", "direction has control characters");
115 }
116
103117 const known = new Map(source.catalog.map((a) => [a.ref, a] as const));
104118 const seen = new Set<string>();
105119 const apps: PlannedApp[] = [];
@@ -136,7 +150,7 @@ export function planSpawn(
136150 subscriptions = [...new Set(source.subscriptions)].sort(byText);
137151 }
138152
139 return ok({ name, org, apps, briefs, subscriptions });
153 return ok({ name, org, apps, briefs, subscriptions, direction });
140154 }
141155
142156 const enc = new TextEncoder();
src/web/pages/claim.ts added +68
@@ -0,0 +1,68 @@
1 /**
2 * The claim page: where the owner of a freshly spawned forge takes it over.
3 * GET only draws a confirm button — a link scanner or a prefetch must not
4 * spend the single use. POST redeems, signs the owner in with an HttpOnly
5 * session cookie, and goes to the front door. The page also says how to
6 * connect: `FORGE_APP_SSH` verbatim, or that the terminal is off.
7 */
8
9 import { claimOpen, redeemClaim } from "../../core/claims.ts";
10 import { createSession } from "../../core/sessions.ts";
11 import { crossOrigin, type Ctx } from "../../http/context.ts";
12 import { pageHead } from "../chrome.ts";
13 import { html } from "../html.ts";
14 import { page, redirect } from "../layout.ts";
15 import { btn, card, terminalLine } from "../ui.ts";
16 import { sessionCookie } from "./site.ts";
17
18 const TOKEN = /^[A-Za-z0-9_-]{16,128}$/;
19
20 const connect = (): ReturnType<typeof terminalLine> => {
21 const command = (process.env.FORGE_APP_SSH ?? "").trim();
22 return terminalLine(command === "" ? {} : { command });
23 };
24
25 function gone(ctx: Ctx): Response {
26 return page(
27 {
28 ctx,
29 title: "Claim this forge",
30 body: html`<div class="narrow">
31 ${pageHead("This link has been used or has expired")}
32 ${card(html`<p>Ask whoever made this forge for a new claim link.</p>`)}
33 </div>`,
34 },
35 404,
36 );
37 }
38
39 export function claimPage(ctx: Ctx): Response {
40 const token = ctx.params.token ?? "";
41 if (!TOKEN.test(token) || !claimOpen(ctx.app.db, token)) return gone(ctx);
42 const res = page({
43 ctx,
44 title: "Claim this forge",
45 body: html`<div class="narrow">
46 ${pageHead("Claim this forge")}
47 ${card(html`<form method="post" action="/claim/${token}">
48 <p>This link works once. Claiming it signs you in as this forge's owner.</p>
49 <div class="form-actions">${btn("Claim and sign in", { variant: "primary" })}</div>
50 <p class="muted small">To connect with a terminal:</p>
51 ${connect()}
52 </form>`)}
53 </div>`,
54 });
55 res.headers.set("cache-control", "no-store");
56 return res;
57 }
58
59 export function claimSubmit(ctx: Ctx): Response {
60 if (crossOrigin(ctx.request, ctx.url, ctx.app.log))
61 return new Response("forbidden", { status: 403 });
62 const token = ctx.params.token ?? "";
63 if (!TOKEN.test(token)) return gone(ctx);
64 const claimed = redeemClaim(ctx.app.db, token);
65 if (!claimed.ok) return gone(ctx);
66 const session = createSession(ctx.app.db, claimed.value.id);
67 return redirect("/", sessionCookie(session.token, session.expiresAt, ctx.url));
68 }
test/first-boot.test.ts added +174
@@ -0,0 +1,174 @@
1 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createRepo } from "../src/actions/repos.ts";
6 import { childDirOf, spawnForge, type SpawnDeps } from "../src/actions/spawn.ts";
7 import { createApp, type App } from "../src/app.ts";
8 import { mintClaim, redeemClaim } from "../src/core/claims.ts";
9 import { createUser, type User } from "../src/core/users.ts";
10 import { repoDir } from "../src/git/repos.ts";
11 import { commitFiles } from "../src/git/write.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { hostedPlacement } from "../src/spawn/placement.ts";
14 import type { SpawnSource } from "../src/spawn/plan.ts";
15 import { loadOrCreateHostKey } from "../src/ssh/keys.ts";
16
17 const SECRET = "sk-live-SECRET-value";
18 const author = { name: "a", email: "[email protected]" };
19
20 let dir: string;
21 let app: App;
22 let alice: User;
23 let deps: SpawnDeps;
24 let source: SpawnSource;
25 const input = {
26 name: "kid",
27 org: "kids",
28 apps: ["alice/notes"],
29 carryBriefs: true,
30 carrySubscriptions: false,
31 direction: "A forge for the chess club's newsletter.",
32 };
33
34 beforeEach(async () => {
35 dir = await mkdtemp(join(tmpdir(), "forge-boot-"));
36 app = createApp({ dataDir: dir, url: "https://forge.test" });
37 const made = await createUser(app.db, { username: "alice", email: "[email protected]", isAdmin: true });
38 if (!made.ok) throw new Error("user");
39 alice = made.value;
40 const repo = await createRepo(app, alice, { name: "notes" });
41 if (!repo.ok) throw new Error("repo");
42 const c = await commitFiles(repoDir(app.reposRoot, "alice", "notes"), {
43 branch: "main",
44 message: "add",
45 files: [{ path: "a.txt", content: "a" }],
46 author,
47 });
48 if (!c.ok) throw new Error("commit");
49 app.db.run("UPDATE user SET password_hash = ?1 WHERE id = ?2", [SECRET, alice.id]);
50 loadOrCreateHostKey(join(dir, "ssh"));
51 source = {
52 catalog: [{ ref: "alice/notes", readable: true, bytes: 10, forgeJsonBytes: 0 }],
53 briefs: [{ agent: "planner", text: "plan" }],
54 subscriptions: [],
55 };
56 deps = {
57 placement: hostedPlacement({ host: "forge.test" }),
58 request: new Request("https://forge.test/spawn", { method: "POST", headers: { origin: "https://forge.test" } }),
59 url: new URL("https://forge.test/spawn"),
60 };
61 });
62
63 afterEach(async () => {
64 app.close();
65 await rm(dir, { recursive: true, force: true });
66 });
67
68 async function made() {
69 const r = await spawnForge(app, alice, input, source, deps);
70 if (!r.ok || !r.value.boot) throw new Error(JSON.stringify(r));
71 return { ...r.value, boot: r.value.boot, dir: childDirOf(app, r.value.bodyId) };
72 }
73
74 describe("first boot", () => {
75 test("writes the direction once and a planner holds it", async () => {
76 const r = await made();
77 expect(r.boot.direction).toBe("kids/notes#1");
78 expect(r.boot.planner).toBe("planner");
79 const again = await spawnForge(app, alice, input, source, deps);
80 expect(again).toMatchObject({ ok: true, value: { existed: true } });
81 const child = createApp({ dataDir: r.dir });
82 const issues = child.db.query("SELECT title, assignee_id FROM issue").all() as { title: string; assignee_id: string | null }[];
83 expect(issues).toHaveLength(1);
84 expect(issues[0]!.title).toStartWith("Direction: A forge for the chess club");
85 expect(issues[0]!.assignee_id).not.toBeNull();
86 child.close();
87 });
88
89 test("the child's keys are its own and no parent secret is readable from it", async () => {
90 const r = await made();
91 const parentKey = loadOrCreateHostKey(join(dir, "ssh")).publicKey.fingerprint;
92 expect(r.boot.hostKey).not.toBe(parentKey);
93 expect(loadOrCreateHostKey(join(r.dir, "ssh")).publicKey.fingerprint).toBe(r.boot.hostKey);
94 const { readdir } = await import("node:fs/promises");
95 let all = "";
96 for (const e of await readdir(r.dir, { recursive: true, withFileTypes: true }))
97 if (e.isFile()) all += await Bun.file(join(e.parentPath, e.name)).text().catch(() => "");
98 expect(all).not.toContain(SECRET);
99 const parentPriv = await Bun.file(join(dir, "ssh", (await readdir(join(dir, "ssh"))).find((f) => !f.endsWith(".pub"))!)).text();
100 expect(all).not.toContain(parentPriv.trim());
101 });
102
103 test("the claim link is single-use, expires, stored hashed", async () => {
104 const r = await made();
105 const token = r.boot.claimLink.split("/claim/")[1]!;
106 expect(r.boot.claimLink).toBe(`${r.url}/claim/${token}`);
107 const child = createApp({ dataDir: r.dir });
108 const row = child.db.query("SELECT token_hash FROM claim").get() as { token_hash: string };
109 expect(row.token_hash).not.toContain(token);
110 expect(Bun.file(join(r.dir, "forge.db")).size).toBeGreaterThan(0);
111 expect(redeemClaim(child.db, token).ok).toBe(true);
112 expect(redeemClaim(child.db, token).ok).toBe(false);
113 const founder = child.db.query("SELECT id FROM user WHERE username = 'alice'").get() as { id: string };
114 const m = mintClaim(child.db, founder.id, new Date(Date.now() - 8 * 24 * 3600 * 1000));
115 expect(redeemClaim(child.db, m.token).ok).toBe(false);
116 child.close();
117 });
118
119 test("the claim page signs the owner in with an HttpOnly cookie, once, same-origin only", async () => {
120 const r = await made();
121 const child = createApp({ dataDir: r.dir, port: 0 });
122 const servers: Servers = await serve(child);
123 try {
124 const token = r.boot.claimLink.split("/claim/")[1]!;
125 const url = `${servers.url}/claim/${token}`;
126 const get = await fetch(url);
127 expect(get.status).toBe(200);
128 expect(await get.text()).toContain("The terminal is off");
129 // A GET spends nothing, and a cross-origin POST is refused.
130 const cross = await fetch(url, { method: "POST", headers: { origin: "https://evil.test" }, redirect: "manual" });
131 expect(cross.status).toBe(403);
132 const t0 = performance.now();
133 const post = await fetch(url, { method: "POST", headers: { origin: servers.url }, redirect: "manual" });
134 expect(post.status).toBe(303);
135 const cookie = post.headers.get("set-cookie") ?? "";
136 expect(cookie).toContain("forge_session=");
137 expect(cookie).toContain("HttpOnly");
138 const again = await fetch(url, { method: "POST", headers: { origin: servers.url }, redirect: "manual" });
139 expect(again.status).toBe(404);
140 expect((await fetch(url)).status).toBe(404);
141 const t1 = performance.now();
142 expect(t1 - t0).toBeLessThan(2000);
143 for (const path of ["/healthz", "/"]) {
144 await (await fetch(`${servers.url}${path}`)).text(); // warm: first render compiles
145 const s = performance.now();
146 const res = await fetch(`${servers.url}${path}`);
147 expect(res.status).toBe(200);
148 await res.text();
149 expect(performance.now() - s).toBeLessThan(50);
150 }
151 } finally {
152 servers.stop?.();
153 child.close();
154 }
155 });
156
157 test("the page prints FORGE_APP_SSH verbatim when set", async () => {
158 const r = await made();
159 const child = createApp({ dataDir: r.dir, port: 0 });
160 const servers = await serve(child);
161 const before = process.env.FORGE_APP_SSH;
162 process.env.FORGE_APP_SSH = "ssh -p 2222 kid@localhost";
163 try {
164 const body = await (await fetch(r.boot.claimLink.replace(r.url, servers.url))).text();
165 expect(body).toContain("ssh -p 2222 kid@localhost");
166 expect(body).not.toContain("The terminal is off");
167 } finally {
168 if (before === undefined) delete process.env.FORGE_APP_SSH;
169 else process.env.FORGE_APP_SSH = before;
170 servers.stop?.();
171 child.close();
172 }
173 });
174 });
test/spawn-placement.test.ts +1 −1
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
22 import { hostedPlacement, memoryBodies } from "../src/spawn/placement.ts";
33 import type { SpawnPlan } from "../src/spawn/plan.ts";
44
5 const plan = (name: string): SpawnPlan => ({ name, org: "o", apps: [], briefs: [], subscriptions: [] });
5 const plan = (name: string): SpawnPlan => ({ name, org: "o", apps: [], briefs: [], subscriptions: [], direction: "" });
66 const make = (o: Partial<Parameters<typeof hostedPlacement>[0]> = {}) => {
77 let n = 0;
88 const store = memoryBodies();
test/spawn-plan.test.ts +12
@@ -66,3 +66,15 @@ describe("planSpawn", () => {
6666 expect(d.bytes).toBe(1500 + 10 + 12);
6767 });
6868 });
69
70 describe("direction", () => {
71 const src = { catalog: [], briefs: [], subscriptions: [] };
72 const base = { name: "kid", org: "kids", apps: [], carryBriefs: false, carrySubscriptions: false };
73 test("is optional, trimmed, bounded, and text", () => {
74 expect(planSpawn(base, src)).toMatchObject({ ok: true, value: { direction: "" } });
75 expect(planSpawn({ ...base, direction: " for chess " }, src)).toMatchObject({ ok: true, value: { direction: "for chess" } });
76 expect(planSpawn({ ...base, direction: 5 }, src)).toMatchObject({ ok: false, error: { field: "direction" } });
77 expect(planSpawn({ ...base, direction: "x".repeat(2001) }, src)).toMatchObject({ ok: false, error: { field: "direction" } });
78 expect(planSpawn({ ...base, direction: "a\u0000b" }, src)).toMatchObject({ ok: false, error: { field: "direction" } });
79 });
80 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs