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

One button moves a browser forge to a shared server forge by copying its files #17312

opened this

Merged 37h 40m ago, live in production

scout/forge:scout/16862-one-button-moves-a-browser-forge-to-a-sh → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/16862-one-button-moves-a-browser-forge-to-a-sh was merged into main as 245158e.

Review

Sign in to review this change.
15 files changed +552 −3
docs/design/audit.md +1
@@ -111,6 +111,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
111111 - `/forges` — `pages/forges.ts` · the forges this one sent, as a client list · `/family` · colour 1.
112112 - `/forges/refused` — `pages/forges-refused.ts` · the last 20 first asks the forge refused, with its words; an admin's only · `/system` · none seen; reuses the list and muted text.
113113 - `/forges/archive` — `pages/forges.ts` · what archiving does for the forges named, and the one button · `/forges` · colour 1; reuses the list and button.
114 - `/forges/move-in` — `pages/forge_move_in.ts` · move a browser forge to a shared one: the cost said first, then the one button · `/forges` · none seen; reuses the list and button.
114115 - `/forges/new` — `pages/new-forge.ts` · send a new forge · none · colour 1.
115116 - `/family` — `pages/family.ts` · parent, this forge and children as a tree · `/forges` (the same children) · colour 1.
116117 - `/claim` — `pages/claim.ts` · claim a forge that was sent to me · none · colour 1.
docs/features/browser-forge-move.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Move a browser forge to a shared forge by copying its files
4 ---
5 # Move a browser forge to a shared forge (#16862)
6
7 A forge that runs in a browser tab lives on that device and stops when the tab closes. One button moves it to a shared forge on this server: its SQLite file (`forge.db`) and its git data (`repos/`) are uploaded as they are. Nothing is exported to another format, and the shared forge opens the very same file, so its issues are the ones the browser forge had.
8
9 - **The page.** `/forges/move-in` (a link on `/forges`, admins who are people only) says first what it costs: the shared plan's price a month from `src/billing/density.ts`, the 50 MiB of disk it holds and the 32 MiB the form takes, that it sleeps and wakes on the next visit, that its address is new, and that the browser's copy stays. Choose a name, the database, and (optionally) the repositories as a `.tar.gz` of the `repos/` directory; the button is the only step.
10 - **The checks, before anything is kept.** A name this forge can give; the files together within the shared share; the database is a SQLite file whose integrity check says `ok` and holds a forge's tables; the git tar holds only plain files and folders with relative names, and expands (from its listing) to no more than the shared share less the database. A file that fails keeps nothing and says why. The database must be checkpointed (no `-wal` beside it); the browser forge does that before it sends.
11 - **The receipt.** The files go under `children/<bodyId>`; the shared forge's own reader is then asked its counts (issues, pulls, repositories, people) and they must equal what the file said, or everything is removed. The page shows them, and one `forge.moved_in` event keeps the name, byte counts, SHA-256 of each file and the counts.
12 - **The terminal.** Key `i` on the Forges screen (`src/tui/screens/forges.ts`) shows the same cost rows (`moveInCost`) and where to send the files. The terminal is read-only for this feature: it cannot move a forge, because the upload is a browser's file form.
13 - **Not done.** Files past 32 MiB together (the form is read whole to check it; a streamed upload would lift it toward the shared forge's 50 MiB); a start of the process at once (the first visit wakes it); carrying the browser forge's own sign-in sessions to the new address; the browser forge's side of the button (the in-browser forge is not in this repository yet: the form is what its button posts); an API or MCP route (a file does not go through a tool call); charging at a payment provider (the plan is the shared plan, billed as other shared forges are).
outdated

'A start of the process' has a stray capital. Also say that the terminal cannot move a forge, or give it a way to.

14
15 Code: `src/spawn/move_in.ts`, `src/web/pages/forge_move_in.ts`, `recordMovedIn` in `src/actions/spawn.ts`, the `moveIn` cap in `src/kernel/body_caps.ts`. Test: `test/move-in.test.ts`.
src/actions/spawn.ts +24
@@ -290,6 +290,30 @@ async function writeLedger(app: App, ledger: Ledger): Promise<void> {
290290 writePrivate(path, JSON.stringify(ledger));
291291 }
292292
293 /**
294 * The ledger of a forge whose files were copied in whole (`spawn/move_in.ts`, #16862): hosted,
295 * shared, finished, with the tokens a spawned child has. Never overwrites a ledger already there.
296 */
297 export async function recordMovedIn(app: App, f: { readonly name: string; readonly bodyId: string; readonly ownerId: string; readonly plan: string }): Promise<boolean> {
298 if ((await readLedger(app, f.name)) !== undefined) return false;
299 await writeLedger(app, {
300 name: f.name,
301 bodyId: f.bodyId,
302 url: liveChildUrl(app, f.name),
303 planHash: sha256(`moved-in:${f.name}`),
304 done: true,
305 apps: [],
306 createdAt: new Date().toISOString(),
307 ownerId: f.ownerId,
308 size: DEFAULT_SIZE,
309 plan: f.plan,
310 placement: "hosted",
311 statusToken: secret(),
312 beatKey: secret(),
313 });
314 return true;
315 }
316
293317 /**
294318 * The child's founder account: the spawner's own name, or a placeholder
295319 * for a stranger's child (`copyInto`).
src/core/event_audience.ts +1
@@ -125,6 +125,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([
125125 "forge.removed",
126126 "forge.archived",
127127 "forge.restored",
128 "forge.moved_in",
128129 "forge.archive_noticed",
129130 "forge.stopped",
130131 "forge.resized",
src/http/forges_routes.ts +3
@@ -12,6 +12,7 @@ import { forgeLinkForm, forgeRevokeConfirm, forgeLinkRevoke, forgeLinkSubmit, fo
1212 import { billDownload } from "./api/forge_bill.ts";
1313 import { forgeRecoveryForm, forgeRecoverySubmit } from "../web/pages/forges.ts";
1414 import { forgeMachineForm, forgeMachineSubmit } from "../web/pages/forge_machine.ts";
15 import { forgeMoveInForm, forgeMoveInSubmit } from "../web/pages/forge_move_in.ts";
1516 import { forgeUpgradeForm, forgeUpgradeSubmit } from "../web/pages/forge_upgrade.ts";
1617 import { forgesRefusedPage } from "../web/pages/forges-refused.ts";
1718 import { forgeReachAllow, forgeReachLater, forgeReachRevoke } from "../web/pages/hosted-forges.ts";
@@ -26,6 +27,8 @@ export function forgesRoutes(router: Router<Handler>): void {
2627 router.add("GET", "/forges", forgesPage);
2728 router.add("GET", "/forges/export.csv", forgesCsv);
2829 router.add("GET", "/forges/refused", forgesRefusedPage);
30 router.add("GET", "/forges/move-in", forgeMoveInForm);
31 router.add("POST", "/forges/move-in", forgeMoveInSubmit);
2932 router.add("GET", "/forges/archive", forgeArchiveConfirm);
3033 router.add("POST", "/forges/archive", forgeArchiveSubmit);
3134 router.add("POST", "/forges/:name/restore", forgeRestoreSubmit);
src/http/lazy_lists.ts +2
@@ -219,6 +219,8 @@ export const FORGES_ROUTES = [
219219 ["GET", "/forges"],
220220 ["GET", "/forges/export.csv"],
221221 ["GET", "/forges/refused"],
222 ["GET", "/forges/move-in"],
223 ["POST", "/forges/move-in"],
222224 ["GET", "/forges/archive"],
223225 ["POST", "/forges/archive"],
224226 ["POST", "/forges/:name/restore"],
src/http/marks/forges.json +1
@@ -4,6 +4,7 @@
44 "routes": {
55 "/forges": "admin",
66 "/forges/refused": "admin",
7 "/forges/move-in": "admin",
78 "/forges/export.csv": "open",
89 "/forges/name/:name": "open",
910 "/forges/:name/bill": "open",
src/kernel/body_caps.ts +4
@@ -47,6 +47,10 @@ export const BODY_CAPS = {
4747 bytes: 32 * MIB,
4848 reason: "a Drop upload sent as a plain form: read whole to parse; bigger files go by the script or the API, which stream",
4949 },
50 moveIn: {
51 bytes: 32 * MIB,
52 reason: "a browser forge's database and repositories as one form, read whole to check them before anything is kept; the same as a Drop form, below the 50 MiB a shared forge holds",
53 },
5054 beacon: {
5155 bytes: 512,
5256 reason: "a page-view beacon: a few dozen bytes of numbers, so this is already generous",
src/spawn/move_in.ts added +223
@@ -0,0 +1,223 @@
1 /**
2 * Move a browser forge to a shared one by copying its files (#16862). The browser forge's data is
3 * what every forge's is: one SQLite file (`forge.db`) and the git directories (`repos/`). They are
4 * uploaded as they are, never exported to another format, and the shared forge opens the very same
5 * file: its issues are the ones the browser forge had.
6 *
7 * In order, each step safe to stop at: check (an admin who is a person, a free name, the quota,
8 * the file is a SQLite database that is whole and fits the shared share of disk, the git data is a
9 * tar of plain files and folders), keep (the files go under `children/<bodyId>`, nothing else of
10 * this forge is touched), read back (the shared forge's database is asked for its counts and must
11 * say what the file said), record (the ledger, the shared plan, one `forge.moved_in` event). Any
12 * failure removes what this move wrote.
13 *
14 * Not done: the browser forge's own sign-in sessions are not carried (the file holds them, so
15 * they work, but the address is new); a database still in WAL mode must be checkpointed first (the
16 * browser forge does this before it sends); the process starts at the first visit's wake.
17 */
18
19 import { Database } from "bun:sqlite";
20 import { existsSync, mkdirSync, renameSync } from "node:fs";
21 import { rm } from "node:fs/promises";
22 import { join } from "node:path";
23 import { forgeNameVerdict, liveChildUrl, recordMovedIn, childDirOf } from "../actions/spawn.ts";
24 import type { App } from "../app.ts";
25 import { densityOf, DEDICATED_USD, PROMISE, SHARED } from "../billing/density.ts";
26 import { usdPerMonthWords } from "../billing/money.ts";
27 import { tellPlan } from "../billing/notice.ts";
28 import { putEntitlement } from "../billing/store.ts";
29 import type { User } from "../core/users.ts";
30 import { BODY_CAPS } from "../kernel/body_caps.ts";
31 import { sha256 } from "../kernel/hash.ts";
32 import { writePrivate } from "../kernel/file_modes.ts";
33 import { randomBytes } from "node:crypto";
34 import { CHILD_NAME } from "./placement.ts";
35 import { tar } from "./archive.ts";
36 import { childCounts, type ChildCounts } from "./child_db.ts";
37 import { quotaRefusal } from "./quota.ts";
38 import { DEFAULT_SIZE } from "./sizes.ts";
39
40 export type MoveInKind = "not_found" | "invalid" | "failed";
41
42 /** The files a browser forge sends: its database, and its repositories as a gzip tar (optional). */
43 export interface Bundle {
44 readonly name: string;
45 readonly db: Uint8Array;
46 readonly git?: Uint8Array | undefined;
47 }
48
49 /** What the move would cost and do: one list of facts, the page's rows and the terminal's. */
50 export interface MoveInPlan {
51 readonly name: string;
52 readonly bytes: number;
53 readonly priceUsd: number;
54 readonly rows: readonly (readonly [string, string])[];
55 readonly says: string;
56 }
57
58 export type Planned = { readonly ok: true; readonly plan: MoveInPlan } | { readonly ok: false; readonly kind: MoveInKind; readonly says: string };
59 export type Moved =
60 | { readonly ok: true; readonly says: string; readonly plan: MoveInPlan; readonly counts: ChildCounts; readonly url: string }
61 | { readonly ok: false; readonly kind: MoveInKind; readonly says: string };
62
63 const bad = (kind: MoveInKind, says: string) => ({ ok: false as const, kind, says });
64 const MIB = 1_048_576;
65 const mib = (n: number): string => `${(n / MIB).toFixed(n < MIB ? 2 : 1)} MiB`;
66 const HEADER = "SQLite format 3\0";
67
68 /**
69 * The most the two files may be together: the shared share of disk, which is what the price buys.
70 */
71 export const SHARE_BYTES = PROMISE.diskMib * MIB;
72
73 /**
74 * What the move costs, said before any file is chosen (and again with the files' real sizes): the
75 * shared plan's price from the density, the disk it holds, what happens, what stays behind.
outdated

Principle 1: the 'Disk: up to 50 MiB' row is not what the form accepts (32 MiB cap). Say what is true.

76 */
77 export function moveInCost(bytes?: number): MoveInPlan & { readonly name: "" } {
78 const d = densityOf(DEDICATED_USD);
79 const rows: (readonly [string, string])[] = [
80 ["Plan", `shared, ${usdPerMonthWords(d.priceUsd)}, from the move on; nothing is charged before the button`],
81 ["Disk", `${PROMISE.diskMib} MiB for the shared forge; this form takes ${mib(BODY_CAPS.moveIn.bytes)} of database and repositories together${bytes === undefined ? "" : `; this move is ${mib(bytes)}`}`],
82 ["Copied", "forge.db as it is, and the repositories as they are; nothing is converted"],
83 ["Then", "it sleeps when idle and wakes on the next visit in about a second; its address is new"],
84 ["Stays", "the copy in this browser is left as it was; you may delete it once you have looked"],
85 ];
86 return { name: "", bytes: bytes ?? 0, priceUsd: d.priceUsd, rows, says: `Moving costs ${usdPerMonthWords(d.priceUsd)} on the shared plan, from the move on; nothing is charged before you press the button.` };
87 }
88
89 const isPerson = (a: User | undefined): a is User => a?.isAdmin === true && a.kind !== "agent";
90
91 /** The database's own counts read from a copy of its bytes, or why it is not one forge's. */
92 async function inspect(db: Uint8Array, stage: string): Promise<{ readonly ok: true; readonly counts: ChildCounts } | { readonly ok: false; readonly says: string }> {
93 if (db.length < 512 || new TextDecoder("latin1").decode(db.subarray(0, 16)) !== HEADER) return { ok: false, says: "the database is not a SQLite file" };
94 mkdirSync(stage, { recursive: true });
95 const file = join(stage, "check.db");
96 await Bun.write(file, db);
97 let handle: Database | undefined;
98 try {
99 handle = new Database(file, { readonly: true });
100 const verdict = handle.query<{ integrity_check: string }, []>("PRAGMA integrity_check").all();
101 if (verdict.length !== 1 || verdict[0]?.integrity_check !== "ok") return { ok: false, says: "the database is damaged (its own integrity check failed)" };
102 const n = (sql: string): number => Number(handle!.query<{ n: number }, []>(sql).get()?.n ?? 0);
103 return { ok: true, counts: { users: n("SELECT COUNT(*) AS n FROM user"), repos: n("SELECT COUNT(*) AS n FROM repo"), issues: n("SELECT COUNT(*) AS n FROM issue WHERE kind = 'issue'"), pulls: n("SELECT COUNT(*) AS n FROM issue WHERE kind = 'pull'") } };
104 } catch {
105 return { ok: false, says: "the database is not a forge's: it has no users, repositories and issues tables" };
106 } finally {
107 handle?.close();
108 }
109 }
110
111 /**
112 * Whether the git tar holds only relative names of plain files and folders (no link can redirect a
outdated

HIGH: plainTar checks names and types but not the expanded size. A gzip bomb passes at 32 MiB and fills the disk on extraction. Sum the sizes in the -tv listing and refuse above SHARE_BYTES minus the database size. Add a test.

113 * later write) and expands to no more than `room` bytes.
114 */
115 async function plainTar(file: string, room: number): Promise<"ok" | "plain" | "big"> {
116 const listed = await tar(["-tzf", file]);
117 const kinds = await tar(["-tvzf", file]);
118 const names = listed.out.split("\n").filter((l) => l !== "");
119 const types = kinds.out.split("\n").filter((l) => l !== "");
120 const plain = listed.ok && kinds.ok && names.length > 0 && types.length === names.length && types.every((l) => l[0] === "-" || l[0] === "d") && names.every((e) => !e.split("/").includes("..") && !e.startsWith("/"));
121 if (!plain) return "plain";
122 // The listing's third column is each file's expanded size: a small gzip of a huge file is refused
123 // before anything is written.
124 const expanded = types.reduce((sum, l) => sum + (Number(l.split(/\s+/)[2]) || 0), 0);
125 return expanded > room ? "big" : "ok";
126 }
127
128 const stageOf = (app: App, name: string): string => join(app.config.dataDir, "move-in", name);
129 const busy = new Set<string>();
130
131 async function check(app: App, actor: User | undefined, b: Bundle): Promise<Planned & { readonly counts?: ChildCounts }> {
132 if (!isPerson(actor)) return bad("not_found", "no such page");
133 const verdict = await forgeNameVerdict(app, b.name);
134 if (verdict.verdict !== "free") return bad("invalid", `${b.name} is not a name this forge can give: ${verdict.verdict}`);
135 const total = b.db.length + (b.git?.length ?? 0);
136 if (total > SHARE_BYTES) return bad("invalid", `the files are ${mib(total)}; a shared forge holds ${PROMISE.diskMib} MiB. Nothing was copied; a dedicated forge holds more`);
137 const over = quotaRefusal(app.config.dataDir, DEFAULT_SIZE);
138 if (over !== undefined) return bad("invalid", over);
139 const stage = stageOf(app, b.name);
140 await rm(stage, { recursive: true, force: true });
141 try {
142 const seen = await inspect(b.db, stage);
143 if (!seen.ok) return bad("invalid", `${seen.says}. Nothing was copied`);
144 if (b.git !== undefined) {
145 const file = join(stage, "git.tar.gz");
146 await Bun.write(file, b.git);
147 const verdict = await plainTar(file, SHARE_BYTES - b.db.length);
148 if (verdict === "big") return bad("invalid", `the git data expands past what a shared forge holds (${PROMISE.diskMib} MiB with the database). Nothing was copied`);
149 if (verdict === "plain") return bad("invalid", "the git data is not a tar.gz of plain files and folders. Nothing was copied");
150 }
outdated

bodyId and dir are built from b.name before it is validated, and the finally at the end removes dir. Validate first, or use only the random part.

151 const cost = moveInCost(total);
152 const counts = seen.counts;
153 const rows: (readonly [string, string])[] = [["Name", b.name], ...cost.rows.slice(0, 2), ["Holds", `${counts.issues} issues, ${counts.pulls} pulls, ${counts.repos} repositories, ${counts.users} people`], ...cost.rows.slice(2)];
154 return { ok: true, counts, plan: { ...cost, name: b.name, rows } };
155 } finally {
156 await rm(stage, { recursive: true, force: true });
157 }
158 }
159
160 /** What the move would do and cost with these files; nothing is kept. */
161 export async function planMoveIn(app: App, actor: User | undefined, b: Bundle): Promise<Planned> {
162 const c = await check(app, actor, b);
163 return c.ok ? { ok: true, plan: c.plan } : c;
164 }
165
166 /**
167 * The move: the files are checked again here, kept under a new child directory, read back through
168 * the shared forge's own reader, then recorded as a finished shared forge. A second move of a name
169 * is refused while the first runs.
170 */
171 export async function moveIn(app: App, actor: User | undefined, b: Bundle): Promise<Moved> {
172 if (!CHILD_NAME.test(b.name)) return bad("invalid", `${b.name} is not a name this forge can give`);
173 if (busy.has(b.name)) return bad("invalid", `${b.name} is being moved in already`);
174 busy.add(b.name);
175 const bodyId = `in-${b.name}-${randomBytes(4).toString("hex")}`;
176 const dir = childDirOf(app, bodyId);
177 try {
178 const c = await check(app, actor, b);
179 if (!c.ok || c.counts === undefined) return c.ok ? bad("failed", "the files could not be read") : c;
180 const stage = stageOf(app, b.name);
181 await rm(stage, { recursive: true, force: true });
182 mkdirSync(join(stage, "repos"), { recursive: true });
183 try {
184 await Bun.write(join(stage, "forge.db"), b.db);
185 if (b.git !== undefined) {
186 const file = join(stage, "git.tar.gz");
187 await Bun.write(file, b.git);
188 const out = await tar(["-xzf", file, "--no-same-owner", "-C", join(stage, "repos")]);
189 await rm(file, { force: true });
190 if (!out.ok) return bad("failed", "the git data could not be unpacked. Nothing was kept");
191 }
192 mkdirSync(join(app.config.dataDir, "children"), { recursive: true });
193 renameSync(stage, dir);
194 } finally {
195 await rm(stage, { recursive: true, force: true });
196 }
197 const read = await childCounts(dir);
198 const same = read !== undefined && read.issues === c.counts.issues && read.pulls === c.counts.pulls && read.repos === c.counts.repos && read.users === c.counts.users;
199 if (!same) {
200 await rm(dir, { recursive: true, force: true });
201 return bad("failed", "the shared forge did not read the same counts from the copied file. Nothing was kept");
202 }
203 writePrivate(join(dir, "parent.json"), JSON.stringify({ upstream: app.config.url ?? `http://${app.config.host ?? "localhost"}`, name: b.name, org: "", url: liveChildUrl(app, b.name), anonymous: false, size: DEFAULT_SIZE, plan: SHARED, apps: [] }));
204 const made = await recordMovedIn(app, { name: b.name, bodyId, ownerId: (actor as User).id, plan: SHARED });
205 if (!made) {
206 await rm(dir, { recursive: true, force: true });
207 return bad("invalid", `${b.name} was taken while the files were checked. Nothing was kept`);
208 }
209 putEntitlement(app.db, { forge: b.name, plan: SHARED, status: "active", source: "moved-in", provider: "none" }, DEFAULT_SIZE, (actor as User).id);
210 tellPlan(app, b.name);
211 app.bus.append({
212 kind: "forge.moved_in",
213 actorId: (actor as User).id,
214 payload: { name: b.name, dbBytes: b.db.length, dbSha256: sha256(b.db), gitBytes: b.git?.length ?? 0, gitSha256: b.git === undefined ? "" : sha256(b.git), issues: read.issues, pulls: read.pulls, repos: read.repos },
215 });
216 const url = liveChildUrl(app, b.name);
217 const says = `${b.name} is a shared forge now at ${url}: ${read.issues} issues, ${read.pulls} pulls and ${read.repos} repositories, read back from the copied file (database ${sha256(b.db).slice(0, 12)}). ${usdPerMonthWords(c.plan.priceUsd)}, from today. It wakes on the first visit.`;
218 return { ok: true, says, plan: c.plan, counts: read, url };
219 } finally {
220 busy.delete(b.name);
221 if (!existsSync(join(app.config.dataDir, "spawn", `${b.name}.json`))) await rm(dir, { recursive: true, force: true });
222 }
223 }
src/tui/screens/forges.ts +18 −1
@@ -24,6 +24,7 @@ import { archiveForge, archivedForges, destinationWords, restoreForge } from "..
2424 import { writeClientsCsv } from "../../spawn/clients_csv.ts";
2525 import { claimedWords, keepWords } from "../../spawn/keep_words.ts";
2626 import { changeLink, revokePreview, ownCode, removeForge, resizeForge, stopForge } from "../../spawn/manage.ts";
27 import { moveInCost } from "../../spawn/move_in.ts";
2728 import { dedicatedPlans, planUpgrade, sharedForges, upgradeRows, upgradeShared } from "../../actions/upgrade_shared.ts";
2829 import { usdPerMonthWords } from "../../billing/money.ts";
2930 import { machinesOf } from "../../spawn/machines.ts";
@@ -343,6 +344,21 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
343344 }),
344345 );
345346 };
347 // The page's "Move in a forge that runs in a browser": what it costs, in the page's rows
348 // (`moveInCost`). The files are sent from the browser forge's page, so the terminal shows the
349 // cost and where.
350 const moveInOne = (): void => {
351 if (session?.user?.isAdmin !== true) return;
352 const cost = moveInCost();
353 ctx.push(
354 confirmScreen(ctx, screen, {
355 title: "Move in a forge that runs in a browser?",
356 body: [...cost.rows.map(([k, v]) => `${k}: ${v}`), "The terminal only shows this: the files are sent at /forges/move-in on the web page."],
357 actions: [{ label: "Understood" }],
358 onChoose: () => {},
359 }),
360 );
361 };
346362 // Each machine's heartbeat and the emptiest, where a new forge goes (the MCP `kind: machines`).
347363 const machinesSeen = (): void => {
348364 if (session?.user?.isAdmin !== true) return;
@@ -391,7 +407,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
391407 };
392408 const screen: Screen = {
393409 title: "Forges you sent",
394 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["M"], "move to a machine"), binding(["v"], "restore from the newest copy"), binding(["e"], "upgrade a shared forge"), binding(["h"], "machines' heartbeats"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["/"], "search"), binding(["c"], "csv"), binding(["esc"], "close")],
410 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["M"], "move to a machine"), binding(["v"], "restore from the newest copy"), binding(["e"], "upgrade a shared forge"), binding(["i"], "move in a browser forge"), binding(["h"], "machines' heartbeats"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["/"], "search"), binding(["c"], "csv"), binding(["esc"], "close")],
395411 render(area, s) {
396412 const c = ctx.theme.c;
397413 const w = Math.min(100, Math.max(30, area.w - 6));
@@ -459,6 +475,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
459475 else if (e.key === "g") movedKey(ctx, e, "g", "M moves it to a machine now");
460476 else if (e.key === "v") machineOne(true);
461477 else if (e.key === "e") upgradeOne();
478 else if (e.key === "i") moveInOne();
462479 else if (e.key === "h") machinesSeen();
463480 else if (e.key === "w") raiseOne();
464481 else if (e.key === "x" && session !== undefined)
src/web/pages/forge_move_in.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * Move a browser forge to a shared forge by copying its files (#16862): `GET /forges/move-in` says
3 * what it costs before anything happens and shows the one form; `POST` uploads the database and
4 * the git data as they are and shows the receipt. The words and rows are `spawn/move_in.ts`'s, the
5 * same the terminal says. Admins who are people only.
6 */
7
8 import { BODY_CAPS } from "../../kernel/body_caps.ts";
9 import { CHILD_NAME } from "../../spawn/placement.ts";
10 import { moveIn, moveInCost, planMoveIn } from "../../spawn/move_in.ts";
11 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
12 import type { Ctx } from "../../http/context.ts";
13 import { notFoundPage, pageHead } from "../chrome.ts";
14 import { readForm } from "../form.ts";
15 import { html, type Html } from "../html.ts";
16 import { page } from "../layout.ts";
17 import { btn, field } from "../ui.ts";
18 import { statusRow } from "./security.ts";
19
20 const wrap = (title: string, body: Html) =>
21 html`<div class="narrow-wide" data-forges>${pageHead(title)}<section class="settings-block">${body}<p class="mt">${btn("Back to your forges", { href: "/forges", size: "sm" })}</p></section></div>`;
22
23 const done = (response: Response): Response => {
24 response.headers.set("cache-control", "no-store");
25 return response;
26 };
27
28 export function forgeMoveInForm(ctx: Ctx): Response {
29 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
30 if (ctx.auth.user?.isAdmin !== true || ctx.auth.user.kind === "agent") return notFoundPage(ctx);
31 const rendering = performance.now();
32 const cost = moveInCost();
33 const body = html`<dl class="status-rows" data-preview>${cost.rows.map(([label, value]) => statusRow(label, html`${value}`))}</dl>
34 <form method="post" action="/forges/move-in" enctype="multipart/form-data" data-move-in>
outdated

Principles 1 and 7: hand-rolled label and input markup beside field, and the cost sentence repeats the rows. Use the named component and say each fact once.

35 ${field({ label: "Name of the shared forge", name: "name", required: true, placeholder: "my-forge" })}
36 ${field({ label: "Database (forge.db)", name: "db", type: "file", required: true })}
37 ${field({ label: "Git data (repos.tar.gz, optional)", name: "git", type: "file" })}
38 ${btn("Check what it would hold and cost", { name: "check", value: "1", title: "Reads the files and says what they hold; nothing is kept" })}
39 ${btn("Move it to a shared forge", { variant: "primary", title: "Copies the files; the browser's copy stays where it is" })}
40 </form>`;
41 const response = done(page({ ctx, title: "Move a browser forge", body: wrap("Move a browser forge to a shared forge", body) }));
42 notePhase(ctx.request, "render", performance.now() - rendering);
43 return response;
44 }
45
46 export async function forgeMoveInSubmit(ctx: Ctx): Promise<Response> {
47 const user = ctx.auth.user;
48 if (user?.isAdmin !== true || user.kind === "agent") return notFoundPage(ctx);
49 const form = await readForm(ctx, "admin", BODY_CAPS.moveIn.bytes);
50 if (form instanceof Response) return form;
51 const name = String(form.get("name") ?? "").trim().toLowerCase();
52 const db = form.get("db");
53 const git = form.get("git");
54 const file = (v: unknown): v is File => typeof v === "object" && v !== null && "arrayBuffer" in v && "size" in v;
55 let says = "";
56 let status = 200;
57 let kind = "yes";
58 if (!CHILD_NAME.test(name)) [says, status, kind] = ["Name it with lowercase letters, digits and dashes, up to 39 characters.", 422, "invalid"];
59 else if (!file(db) || db.size === 0) [says, status, kind] = ["Choose the database file.", 422, "invalid"];
60 else if (form.get("check") !== null) {
61 const planned = await planMoveIn(ctx.app, user, { name, db: new Uint8Array(await db.arrayBuffer()), ...(file(git) && git.size > 0 ? { git: new Uint8Array(await git.arrayBuffer()) } : {}) });
62 if (planned.ok)
63 return done(page({ ctx, title: "What the move would do", body: wrap("What the move would do", html`<p role="status" data-moved="check">${planned.plan.says}</p><dl class="status-rows" data-preview>${planned.plan.rows.map(([label, value]) => statusRow(label, html`${value}`))}</dl>`) }));
64 [says, status, kind] = [planned.says, planned.kind === "not_found" ? 404 : 422, planned.kind];
65 } else {
66 const moved = await moveIn(ctx.app, user, { name, db: new Uint8Array(await db.arrayBuffer()), ...(file(git) && git.size > 0 ? { git: new Uint8Array(await git.arrayBuffer()) } : {}) });
67 says = moved.says;
68 if (!moved.ok) [status, kind] = [moved.kind === "not_found" ? 404 : moved.kind === "invalid" ? 422 : 409, moved.kind];
69 }
70 const title = status === 200 ? "Forge moved" : "Forge not moved";
71 return done(page({ ctx, title, body: wrap(title, html`<p role="status" data-moved="${kind}">${says}</p>`) }, status));
72 }
src/web/pages/forges.ts +2 −2
@@ -306,8 +306,8 @@ export async function forgesPage(ctx: Ctx): Promise<Response> {
306306 title: "Forges you sent",
307307 body: html`<div class="narrow-wide" data-forges>
308308 ${pageHead("Forges you sent", {
309 sub: "Each forge you sent: who it is for and what runs there.",
310 actions: action,
309 sub: "Each forge you sent, and what runs there.",
310 actions: html`${action}${btn("Move in", { href: "/forges/move-in", size: "sm", title: "Move a forge that runs in a browser onto this one by copying its files" })}`,
311311 })}
312312 ${over === undefined ? null : html`<p class="muted small" role="status" data-memory-over>${over}</p>`}
313313 ${receipt(ctx, everyone)}
test/module-state.baseline.txt +1
@@ -213,3 +213,4 @@ src/web/studio/toolbar.ts:stats
213213 src/apps/egress_refused.ts:said
214214 src/core/readme_description.ts:tips
215215 src/release/leftover_sweep.ts:removing
216 src/spawn/move_in.ts:busy
test/move-in.test.ts added +184
@@ -0,0 +1,184 @@
1 /**
2 * #16862: a browser forge's files (its SQLite file and its git data) are copied to a shared forge
3 * as they are, and the shared forge shows the same issues. The cost is said before; the move is
4 * receipted; a bad file keeps nothing.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { listChildren } from "../src/actions/spawn.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { SHARED } from "../src/billing/density.ts";
13 import { entitlementOf } from "../src/billing/store.ts";
14 import { createIssue } from "../src/core/issues.ts";
15 import { createRepo } from "../src/core/repos.ts";
16 import { getUserById, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { childCounts, closeChildDb } from "../src/spawn/child_db.ts";
19 import { tar } from "../src/spawn/archive.ts";
20 import { moveIn, moveInCost, planMoveIn, type Bundle } from "../src/spawn/move_in.ts";
21 import { clientRows } from "../src/spawn/clients.ts";
22 import { createForgeApp } from "../src/tui/forge.ts";
23 import { forgesScreen } from "../src/tui/screens/forges.ts";
24 import { headlessTerminal } from "../src/tui/term/terminal.ts";
25 import { adminCookie, seedAdmin } from "./helpers/admin.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27 import { settleApp } from "./helpers/tui.ts";
28
29 quietLogs();
30
31 const root = mkdtempSync(join(tmpdir(), "move-in-"));
32 let server: App;
33 let browser: App;
34 let servers: Servers;
35 let cookie = "";
36 let admin: User;
37 let files: { db: Uint8Array; git: Uint8Array };
38
39 beforeAll(async () => {
40 // The browser forge: a forge's own data directory, with three issues and one repository.
41 browser = createApp({ dataDir: join(root, "browser"), url: "https://browser.test", port: 0 });
42 const me = await seedAdmin(browser, { username: "bea", email: "[email protected]" });
43 if (!me.ok) throw new Error(String(me.error));
44 const repo = await createRepo(browser.db, browser.reposRoot, { ownerId: me.value.id, name: "notes", visibility: "private" });
45 if (!repo.ok) throw new Error(String(repo.error));
46 for (const title of ["first", "second", "third"]) createIssue(browser.db, { repoId: repo.value.id, authorId: me.value.id, title });
47 browser.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
48 const db = new Uint8Array(readFileSync(join(root, "browser", "forge.db")));
49 const packed = join(root, "repos.tar.gz");
50 expect((await tar(["-czf", packed, "-C", join(root, "browser", "repos"), "."])).ok).toBe(true);
51 files = { db, git: new Uint8Array(readFileSync(packed)) };
52
53 server = createApp({ dataDir: join(root, "server"), url: "https://forge.test", port: 0 });
54 cookie = await adminCookie(server, { username: "alice", email: "[email protected]" });
55 const row = server.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!;
56 admin = getUserById(server.db, row.id)!;
57 servers = await serve(server);
58 }, 30_000);
59
60 afterAll(() => {
61 servers.stop();
62 closeChildDb();
63 server.close();
64 rmSync(root, { recursive: true, force: true });
65 });
66
67 const bundle = (name: string, over: Partial<Bundle> = {}): Bundle => ({ name, db: files.db, git: files.git, ...over });
68 const kept = (): string[] => readdirSync(join(server.config.dataDir, "children"), { withFileTypes: true }).map((d) => d.name);
69
70 test("the cost is said before anything is kept, with what the files hold", async () => {
71 const planned = await planMoveIn(server, admin, bundle("moved"));
72 if (!planned.ok) throw new Error(planned.says);
73 const text = planned.plan.rows.flat().join(" ");
74 expect(planned.plan.says).toContain("nothing is charged before you press the button");
75 expect(text).toContain("shared, $");
76 expect(text).toContain("3 issues");
77 expect(text).toContain("nothing is converted");
78 expect(existsSync(join(server.config.dataDir, "children"))).toBe(false);
79 expect(await listChildren(server)).toEqual([]);
80 });
81
82 test("the files are copied as they are and the shared forge shows the same issues", async () => {
83 const done = await moveIn(server, admin, bundle("moved"));
84 if (!done.ok) throw new Error(done.says);
85 expect(done.counts.issues).toBe(3);
86 const child = (await listChildren(server)).find((c) => c.name === "moved");
87 expect(child?.done).toBe(true);
88 expect(entitlementOf(server.db, "moved", "small").plan).toBe(SHARED);
89 const dir = join(server.config.dataDir, "children", child!.bodyId);
90 // The same bytes, no other format; the repository directory came across.
91 expect(readFileSync(join(dir, "forge.db")).equals(Buffer.from(files.db))).toBe(true);
92 expect(readdirSync(join(dir, "repos")).length).toBeGreaterThan(0);
93 // The shared forge's own reader sees the browser forge's issues.
94 expect((await childCounts(dir))?.issues).toBe(3);
95 // The receipt is an event naming the checksum.
96 const event = server.db.query<{ payload: string }, []>("SELECT payload FROM event WHERE kind = 'forge.moved_in'").get();
97 expect(JSON.parse(event!.payload)).toMatchObject({ name: "moved", issues: 3, dbBytes: files.db.length });
98 expect(done.says).toContain("3 issues");
99 // A second move of the name is refused and keeps nothing more.
100 const before = kept().length;
101 const again = await moveIn(server, admin, bundle("moved"));
102 expect(again.ok).toBe(false);
103 expect(kept().length).toBe(before);
104 });
105
106 test("what is not a forge's database, a person's request or a clean name keeps nothing", async () => {
107 const before = kept();
108 const junk = await moveIn(server, admin, bundle("junk", { db: new TextEncoder().encode("not a database".repeat(100)) }));
109 expect(junk.ok ? "" : junk.says).toContain("not a SQLite file");
110 const hollow = new Uint8Array(files.db.length);
111 hollow.set(files.db.subarray(0, 16));
112 expect((await moveIn(server, admin, bundle("hollow", { db: hollow }))).ok).toBe(false);
113 const gitless = await moveIn(server, admin, bundle("linky", { git: new TextEncoder().encode("nope") }));
114 expect(gitless.ok ? "" : gitless.says).toContain("git data");
115 const stranger = await moveIn(server, undefined, bundle("sneaky"));
116 expect(stranger.ok ? "" : stranger.kind).toBe("not_found");
117 const named = await moveIn(server, admin, bundle("Bad Name!"));
118 expect(named.ok).toBe(false);
119 expect(kept()).toEqual(before);
120 expect((await listChildren(server)).map((c) => c.name)).toEqual(["moved"]);
121 });
122
123 test("a database over the shared share of disk is refused with the numbers", async () => {
124 const big = await planMoveIn(server, admin, bundle("huge-one", { git: new Uint8Array(51 * 1_048_576) }));
125 expect(big.ok ? "" : big.says).toContain("holds 50 MiB");
126 });
127
128 test("a small gzip of a huge file is refused for its expanded size, and a name is checked before it is used", async () => {
129 const dir = join(root, "bomb");
130 mkdirSync(dir, { recursive: true });
131 await Bun.write(join(dir, "zero"), new Uint8Array(60 * 1_048_576));
132 const packed = join(root, "bomb.tar.gz");
133 expect((await tar(["-czf", packed, "-C", dir, "."])).ok).toBe(true);
134 const git = new Uint8Array(await Bun.file(packed).arrayBuffer());
135 expect(git.length).toBeLessThan(1_048_576);
136 const refused = await moveIn(server, admin, bundle("bomby", { git }));
137 expect(refused.ok ? "" : refused.says).toContain("expands past");
138 const odd = await moveIn(server, admin, bundle("../x"));
139 expect(odd.ok).toBe(false);
140 });
141
142 test("the page says the cost first, takes the files, and shows the receipt", async () => {
143 const form = await (await fetch(`${servers.url}/forges/move-in`, { headers: { cookie } })).text();
144 expect(form).toContain(moveInCost().rows[0]![1]);
145 expect(form).toContain('enctype="multipart/form-data"');
146 const send = (origin: string, name: string) => {
147 const body = new FormData();
148 body.set("name", name);
149 body.set("db", new File([files.db], "forge.db"));
150 body.set("git", new File([files.git], "repos.tar.gz"));
151 return fetch(`${servers.url}/forges/move-in`, { method: "POST", headers: { cookie, origin }, body });
152 };
153 expect((await send("https://evil.test", "pagey")).status).toBe(403);
154 // "Check" reads the files and says what they hold and cost, and keeps nothing.
155 const checkBody = new FormData();
156 checkBody.set("name", "pagey");
157 checkBody.set("db", new File([files.db], "forge.db"));
158 checkBody.set("check", "1");
159 const checked = await (await fetch(`${servers.url}/forges/move-in`, { method: "POST", headers: { cookie, origin: "https://forge.test" }, body: checkBody })).text();
160 expect(checked).toContain("3 issues");
161 expect((await listChildren(server)).map((c) => c.name)).not.toContain("pagey");
162 const res = await send("https://forge.test", "pagey");
163 expect(res.status).toBe(200);
164 expect(await res.text()).toContain("3 issues");
165 expect((await listChildren(server)).map((c) => c.name)).toContain("pagey");
166 const anon = await fetch(`${servers.url}/forges/move-in`);
167 expect(anon.status).toBe(404);
168 expect(await (await fetch(`${servers.url}/forges`, { headers: { cookie } })).text()).toContain("/forges/move-in");
169 });
170
171 test("the terminal says the same cost", async () => {
172 const terminal = headlessTerminal(140, 30);
173 const { app: tui, session } = createForgeApp(server, { sshUsername: admin.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: admin }, { terminal, exitHooks: false });
174 tui.start();
175 await settleApp(tui);
176 tui.push(forgesScreen(tui.ctx, await clientRows(server), session));
177 await settleApp(tui);
178 terminal.feed("i");
179 await settleApp(tui);
180 const text = tui.screen.toText();
181 expect(text).toContain("Move in a forge that runs in a browser?");
182 expect(text).toContain("Plan: shared, $");
183 tui.stop();
184 });
test/worker-database-opens.test.ts +1
@@ -68,6 +68,7 @@ const REACHED: Record<string, { opens: number; why: string }> = {
6868 "src/snapshot/drill_hosted.ts": { opens: 1, why: "a restore drill opens the one hosted forge it restored once, for its integrity check, in the drill's own process or as a duty of the serving thread; no Worker calls it" },
6969 "src/snapshot/restore.ts": { opens: 1, why: "a restore reads the sealed names of the restored copy once, in the restore tool or a drill on the serving thread" },
7070 "src/snapshot/snapshot.ts": { opens: 1, why: "a snapshot counts the rows of its own copy once, as a duty of the serving thread (a hosted forge's copy is read in a process of its own, snapshot/hosted_copy.ts); the mirror Worker imports this file for the manifest only" },
71 "src/spawn/move_in.ts": { opens: 1, why: "inspect opens one uploaded copy of a browser forge's database once, read-only, to count its rows before a move, on the serving thread behind an admin's request; no Worker calls it" },
7172 "src/spawn/child_runs.ts": { opens: 2, why: "called by the reader process (spawn/child_db_reader.ts), never by a thread of the forge; cell.ts re-exports the two for tests that read a file directly" },
7273 "src/web/render/sqlite.ts": { opens: 1, why: "a committed .sqlite file is deserialized read-only in memory for its page, on the serving thread behind a request; a Worker reaches it only through src/generated/screens.ts, which lists every screen so the bundle holds them, and calls no open" },
7374 "src/system/compact.ts": { opens: 2, why: "compactFile opens the database and its copy once each, called only by the compaction's own process (system/compact_child.ts) at boot when the compact-on-boot marker asks; Workers reach the file through db_size.ts's keptCopies, which opens nothing" },

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs