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 #444
scout/forge:scout/422-the-child-s-first-boot-its-direction-its → main 2 commits fork
13 files
changed +436
−44
docs/SPAWN.md +2
| @@ -21,6 +21,8 @@ and user accounts. The child mints its own. A test in #420 and #422 proves it. | ||
| 21 | 21 | `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). |
| 22 | 22 | |
| 23 | 23 | | #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 | ||
| 24 | 26 | | #423 | cross-forge following over HTTPS, read-only token | #422 | |
| 25 | 27 | | #424 | propose upstream as a pull on the parent | #423 | |
| 26 | 28 | | #425 | family tree across forges, signed heartbeats | #423 | |
forge.json +2 −1
| @@ -6,7 +6,8 @@ | ||
| 6 | 6 | "ready": 90 |
| 7 | 7 | }, |
| 8 | 8 | "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 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", | |
| 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 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 first-boot", | |
| 10 | ||
| 10 | 11 | "timeout": 1800 |
| 11 | 12 | } |
| 12 | 13 | } |
src/actions/spawn.ts +18 −3
| @@ -26,6 +26,7 @@ import { err, ok, type Result } from "../kernel/result.ts"; | ||
| 26 | 26 | import { crossOrigin } from "../http/context.ts"; |
| 27 | 27 | import type { Placement } from "../spawn/placement.ts"; |
| 28 | 28 | import { planSpawn, type SpawnInput, type SpawnPlan, type SpawnSource } from "../spawn/plan.ts"; |
| 29 | import { firstBoot, type FirstBoot } from "../spawn/firstboot.ts"; | |
| 29 | 30 | import { requireUser } from "./access.ts"; |
| 30 | 31 | |
| 31 | 32 | export interface Spawned { |
| @@ -35,6 +36,11 @@ export interface Spawned { | ||
| 35 | 36 | readonly bodyId: string; |
| 36 | 37 | /** True when this call found the child already made and changed nothing. */ |
| 37 | 38 | 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; | |
| 38 | 44 | } |
| 39 | 45 | |
| 40 | 46 | export type SpawnError = |
| @@ -155,6 +161,7 @@ async function make( | ||
| 155 | 161 | |
| 156 | 162 | const copied = await copyInto(app, owner, plan, ledger); |
| 157 | 163 | if (!copied.ok) return fail(copied.error); |
| 164 | const boot = copied.value; | |
| 158 | 165 | |
| 159 | 166 | ledger.done = true; |
| 160 | 167 | await writeLedger(app, ledger); |
| @@ -163,7 +170,7 @@ async function make( | ||
| 163 | 170 | actorId: owner.id, |
| 164 | 171 | payload: { name: plan.name, org: plan.org, url: ledger.url, apps: plan.apps.map((a) => a.ref) }, |
| 165 | 172 | }); |
| 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 }); | |
| 167 | 174 | } |
| 168 | 175 | |
| 169 | 176 | /** Every step skips what is already there, so a resumed child is finished, not doubled. */ |
| @@ -172,7 +179,7 @@ async function copyInto( | ||
| 172 | 179 | owner: User, |
| 173 | 180 | plan: SpawnPlan, |
| 174 | 181 | ledger: Ledger, |
| 175 | ): Promise<Result<void, string>> { | |
| 182 | ): Promise<Result<FirstBoot, string>> { | |
| 176 | 183 | const dir = childDirOf(app, ledger.bodyId); |
| 177 | 184 | await mkdir(dir, { recursive: true }); |
| 178 | 185 | const child = createApp({ dataDir: dir }); |
| @@ -185,6 +192,7 @@ async function copyInto( | ||
| 185 | 192 | const made = await createUser(child.db, { |
| 186 | 193 | username: owner.username, |
| 187 | 194 | email: `${owner.username}@spawn.forge.invalid`, |
| 195 | isAdmin: true, | |
| 188 | 196 | }); |
| 189 | 197 | return made.ok ? made.value : undefined; |
| 190 | 198 | })()); |
| @@ -247,7 +255,14 @@ async function copyInto( | ||
| 247 | 255 | join(dir, "parent.json"), |
| 248 | 256 | JSON.stringify({ upstream, name: plan.name, org: plan.org }), |
| 249 | 257 | ); |
| 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 | ); | |
| 251 | 266 | } finally { |
| 252 | 267 | child.close(); |
| 253 | 268 | } |
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[] = [ | ||
| 81 | 81 | ); |
| 82 | 82 | CREATE INDEX delivery_due ON webhook_delivery(state, next_try_at); |
| 83 | 83 | `, |
| 84 | ||
| 85 | 84 | // 2 — conversations: issues and (later) pulls share one table, one number |
| 86 | 85 | // sequence per repo, one comment stream, one label system. |
| 87 | 86 | ` |
| @@ -127,7 +126,6 @@ export const migrations: readonly string[] = [ | ||
| 127 | 126 | PRIMARY KEY (issue_id, label_id) |
| 128 | 127 | ); |
| 129 | 128 | `, |
| 130 | ||
| 131 | 129 | // 3 — pull requests: a 1:1 extension of an issue row, plus review-comment |
| 132 | 130 | // anchoring that survives a force-push (path/line + the line's content hash). |
| 133 | 131 | ` |
| @@ -151,7 +149,6 @@ export const migrations: readonly string[] = [ | ||
| 151 | 149 | ALTER TABLE comment ADD COLUMN line_hash TEXT; |
| 152 | 150 | ALTER TABLE comment ADD COLUMN outdated INTEGER NOT NULL DEFAULT 0; |
| 153 | 151 | `, |
| 154 | ||
| 155 | 152 | // 4 — forks: a repo may descend from another. The git objects are shared via |
| 156 | 153 | // alternates (instant, storage-bounded); the parent link records lineage and |
| 157 | 154 | // gates the detach-before-delete path. A pull's head may live in another repo |
| @@ -162,7 +159,6 @@ export const migrations: readonly string[] = [ | ||
| 162 | 159 | |
| 163 | 160 | ALTER TABLE pull ADD COLUMN head_repo_id TEXT REFERENCES repo(id); |
| 164 | 161 | `, |
| 165 | ||
| 166 | 162 | // 5 — organizations and teams. An org is a user row with kind 'org' (so it |
| 167 | 163 | // owns repos through the same owner_id, no repo change). Teams belong to an |
| 168 | 164 | // org, carry a permission level, and have members; a user's access to an |
| @@ -187,7 +183,6 @@ export const migrations: readonly string[] = [ | ||
| 187 | 183 | ); |
| 188 | 184 | CREATE INDEX team_member_user ON team_member(user_id); |
| 189 | 185 | `, |
| 190 | ||
| 191 | 186 | // 6 — SSH public keys. A user may register keys that authenticate them on |
| 192 | 187 | // the SSH listener. The wire blob is stored as-is (base64); the OpenSSH |
| 193 | 188 | // SHA256 fingerprint is the lookup key and is unique across the forge, so a |
| @@ -205,7 +200,6 @@ export const migrations: readonly string[] = [ | ||
| 205 | 200 | ); |
| 206 | 201 | CREATE INDEX user_key_user ON user_key(user_id); |
| 207 | 202 | `, |
| 208 | ||
| 209 | 203 | // 7 — per-user interface preferences (the terminal's theme, today). Not |
| 210 | 204 | // platform state: nothing outside the surface that wrote it consumes these, |
| 211 | 205 | // so they carry no event and rebuilding one costs a keystroke. |
| @@ -217,7 +211,6 @@ export const migrations: readonly string[] = [ | ||
| 217 | 211 | PRIMARY KEY (user_id, key) |
| 218 | 212 | ); |
| 219 | 213 | `, |
| 220 | ||
| 221 | 214 | // 8 — origins. A connected account on another forge (GitHub, Forgejo, |
| 222 | 215 | // Gitea). Mirrored repos hang off an origin: their git objects are fetched |
| 223 | 216 | // from it on a schedule and their issues/pulls/comments are an index over |
| @@ -293,7 +286,6 @@ export const migrations: readonly string[] = [ | ||
| 293 | 286 | PRIMARY KEY (user_id, repo_id) |
| 294 | 287 | ); |
| 295 | 288 | `, |
| 296 | ||
| 297 | 289 | // 9 — OAuth for origins. A pasted token is the fallback, not the front |
| 298 | 290 | // door: GitHub's device grant works from a terminal with no browser, and |
| 299 | 291 | // Forgejo's authorization code + PKCE works from any browser, including |
| @@ -360,7 +352,6 @@ export const migrations: readonly string[] = [ | ||
| 360 | 352 | CREATE UNIQUE INDEX oauth_flow_state ON oauth_flow(state_hash); |
| 361 | 353 | CREATE INDEX oauth_flow_user ON oauth_flow(user_id, id); |
| 362 | 354 | `, |
| 363 | ||
| 364 | 355 | // 10 — a short link for a connect in flight. |
| 365 | 356 | // |
| 366 | 357 | // The device grant asks a person to open a URL on a *different* device. In |
| @@ -379,7 +370,6 @@ export const migrations: readonly string[] = [ | ||
| 379 | 370 | ALTER TABLE oauth_flow ADD COLUMN target_enc TEXT NOT NULL DEFAULT ''; |
| 380 | 371 | CREATE UNIQUE INDEX oauth_flow_short ON oauth_flow(short_code); |
| 381 | 372 | `, |
| 382 | ||
| 383 | 373 | // 11 — counts on a list, and the index that keeps a search off a table |
| 384 | 374 | // scan. A repo row is useless without "how much is open here", and asking |
| 385 | 375 | // per row is the N+1 that turns fifty repos into a hundred queries; the |
| @@ -400,7 +390,6 @@ export const migrations: readonly string[] = [ | ||
| 400 | 390 | -- this the ORDER BY is a scan of every issue in the forge. |
| 401 | 391 | CREATE INDEX issue_repo_updated ON issue(repo_id, updated_at); |
| 402 | 392 | `, |
| 403 | ||
| 404 | 393 | // 12 — the indexes a busy forge needs, and one small table for retries. |
| 405 | 394 | // |
| 406 | 395 | // Every index here removes a scan that `EXPLAIN QUERY PLAN` showed on a |
| @@ -452,7 +441,6 @@ export const migrations: readonly string[] = [ | ||
| 452 | 441 | ); |
| 453 | 442 | CREATE INDEX idempotency_expiry ON idempotency(expires_at); |
| 454 | 443 | `, |
| 455 | ||
| 456 | 444 | // 13 — review states, thread resolution, and the fork a mirror descends |
| 457 | 445 | // from. |
| 458 | 446 | // |
| @@ -506,7 +494,6 @@ export const migrations: readonly string[] = [ | ||
| 506 | 494 | ALTER TABLE repo ADD COLUMN origin_fork_of TEXT; |
| 507 | 495 | ALTER TABLE origin_repo ADD COLUMN fork_of TEXT; |
| 508 | 496 | `, |
| 509 | ||
| 510 | 497 | // 14 — apps, runs, and the crew (docs/APPS.md). |
| 511 | 498 | // |
| 512 | 499 | // An *app* is a repository that runs. The row holds only what git cannot: |
| @@ -599,7 +586,6 @@ export const migrations: readonly string[] = [ | ||
| 599 | 586 | ); |
| 600 | 587 | CREATE INDEX repo_crew_user ON repo_crew(user_id); |
| 601 | 588 | `, |
| 602 | ||
| 603 | 589 | // 15 — an app's environment. |
| 604 | 590 | // |
| 605 | 591 | // The secrets an app reads at start-up (an admin password, a payment |
| @@ -618,7 +604,6 @@ export const migrations: readonly string[] = [ | ||
| 618 | 604 | PRIMARY KEY (app_id, name) |
| 619 | 605 | ); |
| 620 | 606 | `, |
| 621 | ||
| 622 | 607 | // 16 — a paused run. |
| 623 | 608 | // |
| 624 | 609 | // A run the provider turned away (a rate limit, a usage window) is |
| @@ -629,7 +614,6 @@ export const migrations: readonly string[] = [ | ||
| 629 | 614 | ALTER TABLE run ADD COLUMN not_before TEXT; |
| 630 | 615 | ALTER TABLE run ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0; |
| 631 | 616 | `, |
| 632 | ||
| 633 | 617 | // 17 — checks. |
| 634 | 618 | // |
| 635 | 619 | // A repository's own check (`check` in forge.json) runs as a run of a |
| @@ -670,7 +654,6 @@ export const migrations: readonly string[] = [ | ||
| 670 | 654 | CREATE INDEX run_issue ON run(issue_id, id DESC) WHERE issue_id IS NOT NULL; |
| 671 | 655 | CREATE INDEX run_queue ON run(state, id) WHERE state IN ('queued','running'); |
| 672 | 656 | `, |
| 673 | ||
| 674 | 657 | // 18 — a run's lease. |
| 675 | 658 | // |
| 676 | 659 | // The process working a run renews this every so often; a running run |
| @@ -680,12 +663,10 @@ export const migrations: readonly string[] = [ | ||
| 680 | 663 | ` |
| 681 | 664 | ALTER TABLE run ADD COLUMN heartbeat_at TEXT; |
| 682 | 665 | `, |
| 683 | ||
| 684 | 666 | // 19 — how many turns an agent's run took, beside what it cost. |
| 685 | 667 | ` |
| 686 | 668 | ALTER TABLE run ADD COLUMN turns INTEGER NOT NULL DEFAULT 0; |
| 687 | 669 | `, |
| 688 | ||
| 689 | 670 | // 20 — issues that depend on issues: one row per edge, the plan itself. |
| 690 | 671 | ` |
| 691 | 672 | CREATE TABLE issue_dependency ( |
| @@ -697,7 +678,6 @@ export const migrations: readonly string[] = [ | ||
| 697 | 678 | ); |
| 698 | 679 | CREATE INDEX issue_dependency_blocker ON issue_dependency(blocked_by_id); |
| 699 | 680 | `, |
| 700 | ||
| 701 | 681 | // 21 — a repository can run on its own: how much, on what direction, with |
| 702 | 682 | // what ceiling; and each crew member has a role in it. |
| 703 | 683 | ` |
| @@ -709,7 +689,6 @@ export const migrations: readonly string[] = [ | ||
| 709 | 689 | ALTER TABLE repo ADD COLUMN direction_issue_id TEXT REFERENCES issue(id) ON DELETE SET NULL; |
| 710 | 690 | ALTER TABLE repo_crew ADD COLUMN role TEXT NOT NULL DEFAULT 'builder'; |
| 711 | 691 | `, |
| 712 | ||
| 713 | 692 | // 22 — the decision ledger: every fixed-choice decision the crew's |
| 714 | 693 | // decider made, with what it saw, what it answered, and what came of it. |
| 715 | 694 | ` |
| @@ -730,7 +709,6 @@ export const migrations: readonly string[] = [ | ||
| 730 | 709 | CREATE INDEX decision_issue ON decision(issue_id, kind, created_at); |
| 731 | 710 | CREATE INDEX decision_repo ON decision(repo_id, created_at); |
| 732 | 711 | `, |
| 733 | ||
| 734 | 712 | // 23 — the look: a picture of an environment at a commit, at each of two |
| 735 | 713 | // widths, or the reason there is none. Rows go with the app. |
| 736 | 714 | ` |
| @@ -746,7 +724,6 @@ export const migrations: readonly string[] = [ | ||
| 746 | 724 | UNIQUE (app_id, env, commit_oid, kind) |
| 747 | 725 | ); |
| 748 | 726 | `, |
| 749 | ||
| 750 | 727 | // 24 — a variable has a scope: every environment, production only, or |
| 751 | 728 | // previews only, so a preview can carry a test key where production |
| 752 | 729 | // carries the live one. The scope joins the key, which SQLite cannot add |
| @@ -768,7 +745,6 @@ export const migrations: readonly string[] = [ | ||
| 768 | 745 | DROP TABLE app_env; |
| 769 | 746 | ALTER TABLE app_env_scoped RENAME TO app_env; |
| 770 | 747 | `, |
| 771 | ||
| 772 | 748 | // 25 — what a running app said when the forge knocked on its doors and |
| 773 | 749 | // compared with its contract: one row per probe, kept, so the audit can |
| 774 | 750 | // show the last word and what changed. |
| @@ -808,13 +784,11 @@ export const migrations: readonly string[] = [ | ||
| 808 | 784 | CREATE INDEX subscription_grant_scope ON subscription_grant (scope_id, agent_id); |
| 809 | 785 | ALTER TABLE run ADD COLUMN subscription_id TEXT; |
| 810 | 786 | `, |
| 811 | ||
| 812 | 787 | // 27 — the moment a deploy started serving: set once, at the swap-in, |
| 813 | 788 | // distinct from `finished_at` which waits on the tests beside it. |
| 814 | 789 | ` |
| 815 | 790 | ALTER TABLE run ADD COLUMN serving_at TEXT; |
| 816 | 791 | `, |
| 817 | ||
| 818 | 792 | // 28 — a failed check's own detail: the pass/fail counts and the first |
| 819 | 793 | // few failing names, recognised once from a `bun test` tail as the run |
| 820 | 794 | // finishes (`checks/bun-test.ts`) and stored as JSON beside the run, so a |
| @@ -824,7 +798,6 @@ export const migrations: readonly string[] = [ | ||
| 824 | 798 | ` |
| 825 | 799 | ALTER TABLE run ADD COLUMN check_detail TEXT NOT NULL DEFAULT ''; |
| 826 | 800 | `, |
| 827 | ||
| 828 | 801 | // 29 — a third width: thumb, a picture taken small for a slot that only |
| 829 | 802 | // ever showed one small, instead of a full phone or desktop picture |
| 830 | 803 | // squeezed into it. SQLite's CHECK cannot be altered in place, so the |
| @@ -845,7 +818,6 @@ export const migrations: readonly string[] = [ | ||
| 845 | 818 | DROP TABLE look; |
| 846 | 819 | ALTER TABLE look_new RENAME TO look; |
| 847 | 820 | `, |
| 848 | ||
| 849 | 821 | // 30 — take it back: a pull that reverts another, named explicitly rather |
| 850 | 822 | // than sniffed from its title. `reverts_issue_id` points at the issue the |
| 851 | 823 | // shipped pull was (a pull is its own issue), so "was this already taken |
| @@ -854,7 +826,6 @@ export const migrations: readonly string[] = [ | ||
| 854 | 826 | ALTER TABLE pull ADD COLUMN reverts_issue_id TEXT REFERENCES issue(id) ON DELETE SET NULL; |
| 855 | 827 | CREATE INDEX pull_reverts ON pull(reverts_issue_id) WHERE reverts_issue_id IS NOT NULL; |
| 856 | 828 | `, |
| 857 | ||
| 858 | 829 | // 31 — a look knows which page it is of: `app.looks` in `forge.json` can |
| 859 | 830 | // name more than the home page. `page` defaults to `/`, so every row |
| 860 | 831 | // taken before this migration reads as exactly what it always was — a |
| @@ -879,7 +850,6 @@ export const migrations: readonly string[] = [ | ||
| 879 | 850 | DROP TABLE look; |
| 880 | 851 | ALTER TABLE look_new RENAME TO look; |
| 881 | 852 | `, |
| 882 | ||
| 883 | 853 | // 32 — an app's own domains. One host names one app's production; the |
| 884 | 854 | // token is published in DNS to prove the name is held, so it is not a |
| 885 | 855 | // secret. `verified_at` is set by the first check that finds the proof |
| @@ -898,7 +868,6 @@ export const migrations: readonly string[] = [ | ||
| 898 | 868 | ); |
| 899 | 869 | CREATE INDEX app_domain_app ON app_domain(app_id); |
| 900 | 870 | `, |
| 901 | ||
| 902 | 871 | // 33 — where a repository's next tell comes from when nobody is typing: |
| 903 | 872 | // an Instagram account whose latest Reel's top comment becomes the crew's |
| 904 | 873 | // 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[] = [ | ||
| 922 | 891 | ); |
| 923 | 892 | CREATE INDEX prompt_source_repo ON prompt_source(repo_id); |
| 924 | 893 | `, |
| 925 | ||
| 926 | 894 | // 34 — forge-level secrets: credentials the forge itself needs, sealed |
| 927 | 895 | // under AAD `secret:<scope>:<name>` and never read back. `scope_id` is '' |
| 928 | 896 | // for the forge, an org's or a repo's id otherwise. |
| @@ -937,7 +905,6 @@ export const migrations: readonly string[] = [ | ||
| 937 | 905 | PRIMARY KEY (name, scope, scope_id) |
| 938 | 906 | ); |
| 939 | 907 | `, |
| 940 | ||
| 941 | 908 | // 35 — what a viewer did with a feed item: opened it, dwelled on it, |
| 942 | 909 | // dismissed it, muted its app. One row per act; the feed's affinity is |
| 943 | 910 | // these, counted with a decay. `item_id` is the feed's own id, and |
| @@ -956,7 +923,6 @@ export const migrations: readonly string[] = [ | ||
| 956 | 923 | ); |
| 957 | 924 | CREATE INDEX interaction_viewer ON interaction(viewer_id, id); |
| 958 | 925 | `, |
| 959 | ||
| 960 | 926 | // 36 — a share: one item, one sender, one recipient. A share is delivered |
| 961 | 927 | // (it shows in the recipient's feed, boosted), queued (the recipient's |
| 962 | 928 | // daily budget is spent; it waits and decays) or dropped (it decayed). |
| @@ -980,7 +946,6 @@ export const migrations: readonly string[] = [ | ||
| 980 | 946 | CREATE INDEX share_recipient ON share(recipient_id, state); |
| 981 | 947 | CREATE INDEX share_sender ON share(sender_id, state); |
| 982 | 948 | `, |
| 983 | ||
| 984 | 949 | // 37 — the usage ledger (`core/usage.ts`): what each agent run spent, |
| 985 | 950 | // attributed to subscription, app, agent and issue. `subscription_id` is |
| 986 | 951 | // text, not a reference: a removed account's spend stays counted. |
| @@ -1025,7 +990,6 @@ export const migrations: readonly string[] = [ | ||
| 1025 | 990 | CREATE INDEX IF NOT EXISTS usage_repo ON usage(repo_id, at); |
| 1026 | 991 | CREATE INDEX IF NOT EXISTS usage_subscription ON usage(subscription_id, at); |
| 1027 | 992 | `, |
| 1028 | ||
| 1029 | 993 | // 38 — a subscription's standing (`core/standing.ts`): the last time the |
| 1030 | 994 | // provider said each window (5-hour, weekly) was full and when it resets, |
| 1031 | 995 | // and the share of every window the operator keeps for people. |
| @@ -1081,7 +1045,6 @@ export const migrations: readonly string[] = [ | ||
| 1081 | 1045 | PRIMARY KEY (operation_id, position) |
| 1082 | 1046 | ); |
| 1083 | 1047 | `, |
| 1084 | ||
| 1085 | 1048 | // 41 — the meter (`core/meter.ts`): what an app used, in the two |
| 1086 | 1049 | // quantities a forge charges for. `meter` is one row per awake interval |
| 1087 | 1050 | // of an environment, `ended` NULL while it runs and `beat_at` the last |
| @@ -1172,4 +1135,14 @@ export const migrations: readonly string[] = [ | ||
| 1172 | 1135 | OR body LIKE '%without a pull: cancelled' |
| 1173 | 1136 | OR body LIKE '%interrupted by a restart%'); |
| 1174 | 1137 | `, |
| 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 | `, | |
| 1175 | 1148 | ]; |
src/crew/autonomy.ts +1 −1
| @@ -694,7 +694,7 @@ export function truncateAtWord(text: string, limit: number): string { | ||
| 694 | 694 | * The issue the planner works from: the direction, as an open issue the |
| 695 | 695 | * run can be about. Made once, kept, and never counted as work. |
| 696 | 696 | */ |
| 697 | function ensureDirectionIssue( | |
| 697 | export function ensureDirectionIssue( | |
| 698 | 698 | app: App, |
| 699 | 699 | by: User, |
| 700 | 700 | repo: Repo, |
src/http/server.ts +3
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * verdict. Auth is resolved once per request and handed to handlers as data. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { claimPage, claimSubmit } from "../web/pages/claim.ts"; | |
| 8 | 9 | import { canRead, canWrite, getRepo, getRepoById } from "../core/repos.ts"; |
| 9 | 10 | import { trackPullHead } from "../core/pulls.ts"; |
| 10 | 11 | import { createRepo } from "../actions/repos.ts"; |
| @@ -424,6 +425,8 @@ export function buildRouter(): Router<Handler> { | ||
| 424 | 425 | router.add("GET", "/", home); |
| 425 | 426 | router.add("GET", "/signin", signinPage); |
| 426 | 427 | router.add("POST", "/signin", signinSubmit); |
| 428 | router.add("GET", "/claim/:token", claimPage); | |
| 429 | router.add("POST", "/claim/:token", claimSubmit); | |
| 427 | 430 | router.add("GET", "/signup", signupPage); |
| 428 | 431 | router.add("POST", "/signup", signupSubmit); |
| 429 | 432 | 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; | ||
| 13 | 13 | export const MAX_BRIEFS = 100; |
| 14 | 14 | export const MAX_SUBSCRIPTIONS = 200; |
| 15 | 15 | export const MAX_BRIEF_CHARS = 20_000; |
| 16 | export const MAX_DIRECTION_CHARS = 2_000; | |
| 16 | 17 | |
| 17 | 18 | const NAME = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/; |
| 18 | 19 | const APP_REF = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/; |
| @@ -36,6 +37,8 @@ export interface SpawnInput { | ||
| 36 | 37 | readonly apps: unknown; |
| 37 | 38 | readonly carryBriefs: unknown; |
| 38 | 39 | readonly carrySubscriptions: unknown; |
| 40 | /** What the new forge is for, in the spawner's words. Optional. */ | |
| 41 | readonly direction?: unknown; | |
| 39 | 42 | } |
| 40 | 43 | |
| 41 | 44 | /** What the parent has to offer. Extra fields are ignored, never copied. */ |
| @@ -58,6 +61,8 @@ export interface SpawnPlan { | ||
| 58 | 61 | readonly apps: readonly PlannedApp[]; |
| 59 | 62 | readonly briefs: readonly CrewBrief[]; |
| 60 | 63 | readonly subscriptions: readonly string[]; |
| 64 | /** What the child is for; the first boot writes it as the direction issue. */ | |
| 65 | readonly direction: string; | |
| 61 | 66 | } |
| 62 | 67 | |
| 63 | 68 | export interface DryRun { |
| @@ -100,6 +105,15 @@ export function planSpawn( | ||
| 100 | 105 | if (typeof input.carryBriefs !== "boolean") return refuse("carryBriefs", "must be true or false"); |
| 101 | 106 | if (typeof input.carrySubscriptions !== "boolean") return refuse("carrySubscriptions", "must be true or false"); |
| 102 | 107 | |
| 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 | ||
| 103 | 117 | const known = new Map(source.catalog.map((a) => [a.ref, a] as const)); |
| 104 | 118 | const seen = new Set<string>(); |
| 105 | 119 | const apps: PlannedApp[] = []; |
| @@ -136,7 +150,7 @@ export function planSpawn( | ||
| 136 | 150 | subscriptions = [...new Set(source.subscriptions)].sort(byText); |
| 137 | 151 | } |
| 138 | 152 | |
| 139 | return ok({ name, org, apps, briefs, subscriptions }); | |
| 153 | return ok({ name, org, apps, briefs, subscriptions, direction }); | |
| 140 | 154 | } |
| 141 | 155 | |
| 142 | 156 | 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"; | ||
| 2 | 2 | import { hostedPlacement, memoryBodies } from "../src/spawn/placement.ts"; |
| 3 | 3 | import type { SpawnPlan } from "../src/spawn/plan.ts"; |
| 4 | 4 | |
| 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: "" }); | |
| 6 | 6 | const make = (o: Partial<Parameters<typeof hostedPlacement>[0]> = {}) => { |
| 7 | 7 | let n = 0; |
| 8 | 8 | const store = memoryBodies(); |
test/spawn-plan.test.ts +12
| @@ -66,3 +66,15 @@ describe("planSpawn", () => { | ||
| 66 | 66 | expect(d.bytes).toBe(1500 + 10 + 12); |
| 67 | 67 | }); |
| 68 | 68 | }); |
| 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 | }); |
new above
offline