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

Recovery you can print on a notecard: a restore drill from a real snapshot every week, the passphrase carried, the snapshot store off the box, and the runbook short enough for a safe #1872

Parked opened this in answer to
Closed without merging

scout/forge:scout/1147-recovery-you-can-print-on-a-notecard-a-r → main 6 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
21 files changed +441 −82
README.md +6 −1
@@ -577,7 +577,12 @@ A snapshot uploads eight objects at a time. Run logs older than a day go up
577577 bundled per day (cut at 4 MB, so a long history is several objects, never one
578578 huge one); restore unpacks them. While one runs, progress shows on
579579 **Settings → Backups** and as a line in the log every 500 objects or minute.
580 The terminal has no backups view, so it has no readout.
580 The terminal has no backups view, so it has no readout; but `forge recovery`
581 (an admin's token; `GET /api/v1/recovery`) prints the page's one line —
582 "Recoverable: store reachable, newest snapshot 3 h old, key carried, last
583 drill green" — and exits 1 when it is not so, for a cron to branch on. A
584 forge that has not drilled yet says "Recoverable only in part" calmly; a red
585 drill, a missing key or an empty store is the alarm.
581586
582587 **Run a drill** on the same page (admins only) restores the newest snapshot
583588 into scratch, opens it, counts what is there and unseals a value; the page
docs/RECOVERY.md +45 −65
@@ -1,78 +1,58 @@
11 # Recovery — read this at 3 a.m.
22
3 Print it. Keep it somewhere that is not the forge. `test/recovery-doc.test.ts`
4 keeps it true to `src/snapshot/`.
3 Print it. Keep it in the safe, not on the forge. `test/recovery-doc.test.ts`
4 keeps it true to `src/snapshot/`; the weekly drill runs commands 3 and 4.
5
6 ## The five commands
7
8 1. Install `git` and `bun`, clone the forge, then `bun install` in the clone.
9 2. Export the bucket and the passphrase (below):
10
11 S3_ENDPOINT S3_BUCKET S3_REGION S3_ACCESS_KEY S3_SECRET_KEY FORGE_SNAPSHOT_PASSPHRASE
12
13 3. Restore (`latest` is the newest snapshot; the directory must be new or empty):
14
15 bun run src/snapshot/restore.ts latest /srv/forge-data
16
17 4. Start the forge on it (use `PORT=3999` first to look, then the real port):
18
19 FORGE_DATA=/srv/forge-data PORT=3999 FORGE_SSH_PORT=0 bun run src/main.ts
20
21 5. Point DNS at the machine. Check `curl localhost:3999/api/v1/health` is ok
22 and the repositories and latest issues are there before you do.
23
24 ## Where the secrets are
25
26 - `FORGE_SNAPSHOT_PASSPHRASE`: the owner's safe, nowhere else. Without it the
27 restore still works but the key stays behind and every sealed value is set
28 again by hand. A wrong one refuses before writing.
29 - `S3_*`: the bucket credentials, in the owner's password manager.
530
631 ## Where the copies are
732
8 Snapshots are objects in the forge's bucket (`S3_BUCKET`, at `S3_ENDPOINT`,
9 region `S3_REGION`) under the prefix `snapshots/<name>/`, one directory per
10 snapshot, named like `2026-09-22T08-00-00Z`. The restore command accepts `latest` for
11 the newest; no object is called that.
33 Snapshots are objects in `S3_BUCKET` under `snapshots/<name>/`, one directory
34 per snapshot, named like `2026-09-22T08-00-00Z`. Each holds `manifest.json`,
35 `forge.db`, `secret.key.wrapped` (the key under the passphrase), `ssh/`,
36 `repos/<owner>/<repo>.bundle` and `apps/` and `runs/`.
1237
13 ## Where the verdicts are posted
38 If the restore command fails: fetch objects with any S3 client, put `forge.db`
39 and `ssh/` in a new directory, and `git clone --mirror` each bundle into
40 `<dir>/repos/<owner>/<repo>.git`. Sealed values are then set again by hand.
1441
15 Sundays 09:00 UTC the forge drills a restore of the newest snapshot, boots it
16 on a side port and reads `/api/v1/health`. One comment lands on the recovery
17 issue (`FORGE_RECOVERY_ISSUE` in `FORGE_RECOVERY_REPO`): snapshot, restore
18 time, health, counts, pass or fail. A failed drill is an inbox card naming
19 the step (fetch, restore, open, count, unseal, health) until one passes. No
20 comment this week means the backups are unproven.
42 The other path is the hand-made copy under `manual/<date>/` in the same
43 bucket: a tarball sealed with `openssl enc -d -aes-256-cbc -pbkdf2` and the
44 same passphrase; the README beside it lists what it holds.
2145
22 ## What a restore needs
46 ## Where the verdicts are
2347
24 Export these, with the values the forge ran under:
25
26 S3_ENDPOINT S3_BUCKET S3_REGION S3_ACCESS_KEY S3_SECRET_KEY
27
28 and `FORGE_SNAPSHOT_PASSPHRASE`, which is in the owner's safe and nowhere
29 else. Without it the restore still works, but the secret key stays behind and
30 every sealed value is set again by hand. A wrong one refuses before writing.
31 A machine with `git`, `bun` and a clone of the forge (`bun install`).
32
33 ## Route 1 — the restore command
34
35 bun run src/snapshot/restore.ts <snapshot-name|latest> <data-dir>
36
37 `<data-dir>` must be empty or new; the command refuses otherwise. It prints
38 the files and repositories it brought back.
39
40 Then boot the forge on that directory, on a side port, off the public one:
41
42 FORGE_DATA=<data-dir> PORT=3999 FORGE_SSH_PORT=0 bun run src/main.ts
43
44 Look at, in order:
45
46 1. `curl localhost:3999/api/v1/health` answers ok.
47 2. The home page, signed in as the owner: the repositories and the board.
48 3. One repository's issues: the latest ones you remember are there.
49
50 If all three hold, point the real service at `<data-dir>`.
51
52 ## Route 2 — the objects by hand
53
54 Use it when the restore command fails or only one file is wanted. Every
55 object is plain, under `snapshots/<name>/`; fetch with any S3 client:
56
57 manifest.json what is there
58 forge.db the database
59 secret.key.wrapped the key, under the passphrase
60 ssh/... the SSH host key
61 repos/<owner>/<repo>.bundle one git bundle per repository
62 apps/<id>/production/data/... each app's data
63 runs/... run logs
64
65 Put `forge.db` and `ssh/` in a new data directory; turn each bundle back into
66 a repository with `git clone --mirror <file> <data-dir>/repos/<owner>/<repo>.git`
67 (the layout `src/git/repos.ts` reads). Boot as above. The key is wrapped with
68 scrypt and AES-256-GCM (`src/snapshot/wrap.ts`): only `restore.ts` opens it,
69 so by hand the sealed values are set again.
48 Sundays 09:00 UTC the forge restores the newest snapshot, boots it on a side
49 port and reads `/api/v1/health`. One comment lands on the recovery issue
50 (`FORGE_RECOVERY_ISSUE` in `FORGE_RECOVERY_REPO`): snapshot, time, counts,
51 pass or fail. A failed drill is an inbox card naming the step (fetch,
52 restore, open, count, unseal, health). No comment this week: unproven.
7053
7154 ## What a snapshot does NOT hold
7255
73 - Sealed values, unless the passphrase was set: they stay sealed and are set
74 again by hand (the restore lists them by name).
75 - App variables, which are sealed the same way.
76 - The crew's clones: working copies that agents make again from the
77 repositories.
56 - App variables, which are sealed the same way as secrets, without the passphrase.
57 - The crew's clones: agents make them again from the repositories.
7858 - Anything outside the data directory: the code, the machine, the bun.
scripts/gate.ts +3
@@ -179,6 +179,9 @@ export const GATE: readonly string[] = [
179179 "test/drill-verdict.test.ts",
180180 "test/drill-board-line.test.ts",
181181 "test/snapshot-drill-page.test.ts",
182 "test/drill-counts.test.ts",
183 "test/recoverable.test.ts",
184 "test/recovery-terminal.test.ts",
182185 "test/snapshot-store.test.ts",
183186 "test/migrate.test.ts",
184187 "test/schema-additive.test.ts",
src/cli/api.ts +17
@@ -96,6 +96,23 @@ export class ForgeApi {
9696 return ok(parsed as T);
9797 }
9898
99 /** The forge's one-line "can I recover now?"; an admin's token only. */
100 async recovery(): Promise<
101 ApiResult<{ recoverable: boolean; alarm: boolean; line: string }>
102 > {
103 const out = await this.call<{
104 recoverable?: boolean;
105 alarm?: boolean;
106 line?: string;
107 }>("/api/v1/recovery");
108 if (!out.ok) return out;
109 return ok({
110 recoverable: out.value.recoverable === true,
111 alarm: out.value.alarm !== false,
112 line: String(out.value.line ?? ""),
113 });
114 }
115
99116 async whoami(): Promise<ApiResult<Whoami>> {
100117 const out = await this.call<{ username?: string; displayName?: string }>(
101118 "/api/v1/user",
src/cli/main.ts +16
@@ -81,6 +81,8 @@ export async function main(argv: readonly string[]): Promise<number> {
8181 return login(out, args);
8282 case "logout":
8383 return logout(out);
84 case "recovery":
85 return recovery(out);
8486 case "whoami":
8587 return whoami(out);
8688 case "sync":
@@ -112,6 +114,7 @@ function usage(out: Out): void {
112114 out.line(b(" forge login <url>") + " [--token T]");
113115 out.line(b(" forge logout"));
114116 out.line(b(" forge whoami"));
117 out.line(b(" forge recovery") + " can the forge be recovered now? (admins)");
115118 out.line(
116119 b(" forge sync") +
117120 " [--watch] [--interval 5m] [--ff] [--root DIR]",
@@ -189,6 +192,19 @@ async function whoami(out: Out): Promise<number> {
189192 return EXIT.ok;
190193 }
191194
195 /** Exit 0 when recoverable, 1 when not — a cron can branch on it. */
196 async function recovery(out: Out): Promise<number> {
197 const loaded = await requireConfig(out);
198 if (typeof loaded === "number") return loaded;
199 const got = await new ForgeApi(loaded.url, loaded.token).recovery();
200 if (!got.ok) {
201 out.err(`forge recovery: ${got.error.message}`);
202 return EXIT.failed;
203 }
204 out.line(got.value.line);
205 return got.value.recoverable ? EXIT.ok : EXIT.failed;
206 }
207
192208 // ── sync and status ──────────────────────────────────────────────────────
193209
194210 async function sync(out: Out, args: Args, network: boolean): Promise<number> {
src/core/migrations/20261014000000-what-a-drill-counted.ts added +7
@@ -0,0 +1,7 @@
1 // what a restore drill counted besides repositories and issues
2 // (#1147): users, pulls and apps, so the Backups page can say what came back.
3 export default `
4 ALTER TABLE drill ADD COLUMN users INTEGER NOT NULL DEFAULT 0;
5 ALTER TABLE drill ADD COLUMN pulls INTEGER NOT NULL DEFAULT 0;
6 ALTER TABLE drill ADD COLUMN apps INTEGER NOT NULL DEFAULT 0;
7 `;
src/http/api.ts +15
@@ -8,6 +8,7 @@
88 * back to continue); errors are `{ error, message }`.
99 */
1010
11 import { recoverableNow } from "../snapshot/recoverable.ts";
1112 import { voteVariant } from "../actions/variants.ts";
1213 import { parentForgeFor } from "../core/parent_releases.ts";
1314 import { readFlow } from "../flow/read.ts";
@@ -4101,6 +4102,20 @@ export function apiRoutes(router: Router<Handler>): void {
41014102 json(readHealth(ctx.app, ctx.auth.user)),
41024103 );
41034104
4105 // Can the forge be recovered right now: the Backups page's one line, for
4106 // the terminal. A site admin reads it; anyone else finds nothing.
4107 router.add("GET", "/api/v1/recovery", async (ctx) => {
4108 const denied = accountAdmin(ctx, "ro");
4109 if (denied) return denied;
4110 return json(
4111 (await recoverableNow(ctx.app)) ?? {
4112 recoverable: false,
4113 alarm: true,
4114 line: "Not recoverable: no snapshot store is set.",
4115 },
4116 );
4117 });
4118
41044119 // Explore (#607): the rows /explore shows, for the same one line.
41054120 router.add("GET", "/api/v1/explore", async (ctx) => {
41064121 const query = parseExploreQuery(ctx.url.searchParams.get("q") ?? "");
src/snapshot/drill.ts +13 −2
@@ -20,6 +20,14 @@ import type { Store } from "./store.ts";
2020
2121 export const DRILL_TIMEOUT_MS = 10 * 60_000;
2222
23 export interface DrillCounts {
24 readonly repositories: number;
25 readonly users: number;
26 readonly issues: number;
27 readonly pulls: number;
28 readonly apps: number;
29 }
30
2331 export type DrillStep = "fetch" | "restore" | "open" | "count" | "unseal" | "health";
2432
2533 export interface DrillDeps {
@@ -39,7 +47,7 @@ export interface DrillResult {
3947 readonly at: string;
4048 readonly snapshotId: string | null;
4149 readonly ms: number;
42 readonly counts: { readonly repositories: number; readonly issues: number };
50 readonly counts: DrillCounts;
4351 /** The side-booted forge's word; "unreached" when an earlier step failed. */
4452 readonly health: "ok" | "failed" | "unreached";
4553 readonly verdict: "green" | "red";
@@ -64,7 +72,7 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
6472 const at = clock().toISOString();
6573 const timeoutMs = deps.timeoutMs ?? DRILL_TIMEOUT_MS;
6674 const restore = deps.restore ?? restoreSnapshot;
67 const counts = { repositories: 0, issues: 0 };
75 const counts = { repositories: 0, users: 0, issues: 0, pulls: 0, apps: 0 };
6876 let snapshotId: string | null = null;
6977 let step: DrillStep = "fetch";
7078 let scratch: string | undefined;
@@ -98,7 +106,10 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
98106 const n = (sql: string): number =>
99107 db.query<{ n: number }, []>(sql).get()?.n ?? 0;
100108 counts.repositories = n("SELECT count(*) AS n FROM repo");
109 counts.users = n("SELECT count(*) AS n FROM user");
101110 counts.issues = n("SELECT count(*) AS n FROM issue");
111 counts.pulls = n("SELECT count(*) AS n FROM pull");
112 counts.apps = n("SELECT count(*) AS n FROM app");
102113
103114 step = "unseal";
104115 const secret = db
src/snapshot/drills.ts +15 −3
@@ -13,6 +13,9 @@ interface Row {
1313 ms: number;
1414 repositories: number;
1515 issues: number;
16 users: number;
17 pulls: number;
18 apps: number;
1619 verdict: "green" | "red";
1720 failed_step: DrillStep | null;
1821 reason: string | null;
@@ -20,14 +23,17 @@ interface Row {
2023
2124 export function recordDrill(db: Database, result: DrillResult): void {
2225 db.query(
23 `INSERT INTO drill (at, snapshot_id, ms, repositories, issues, verdict, failed_step, reason)
24 VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
26 `INSERT INTO drill (at, snapshot_id, ms, repositories, issues, users, pulls, apps, verdict, failed_step, reason)
27 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2528 ).run(
2629 result.at,
2730 result.snapshotId,
2831 result.ms,
2932 result.counts.repositories,
3033 result.counts.issues,
34 result.counts.users,
35 result.counts.pulls,
36 result.counts.apps,
3137 result.verdict,
3238 result.failedStep,
3339 result.reason,
@@ -45,7 +51,13 @@ export function lastDrill(db: Database): DrillResult | undefined {
4551 at: row.at,
4652 snapshotId: row.snapshot_id,
4753 ms: row.ms,
48 counts: { repositories: row.repositories, issues: row.issues },
54 counts: {

Add a test that recordDrill then lastDrill returns non-zero users, pulls and apps.

55 repositories: row.repositories,
56 users: row.users,
57 issues: row.issues,
58 pulls: row.pulls,
59 apps: row.apps,
60 },
4961 // Not stored: green means health read ok; a red one failed at it or never got there.
5062 health:
5163 row.verdict === "green" ? "ok" : row.failed_step === "health" ? "failed" : "unreached",
src/snapshot/recoverable.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * "Can I recover right now?" read from the forge itself, for every door:
3 * the Backups page, `GET /api/v1/recovery` and `forge recovery` all print
4 * what this returns. Admin gating is the caller's.
5 */
6
7 import type { App } from "../app.ts";
8 import { lastDrill } from "./drills.ts";
9 import { snapshotsOf } from "./service.ts";
10 import { keyOf, type Manifest } from "./snapshot.ts";
11 import { standing, type Standing } from "./standing.ts";
12
13 /** The standing from a listing already in hand (newest first), or "unreachable". */
14 export function standingOf(
15 app: App,
16 listing: readonly Manifest[] | "unreachable",
17 ): Standing {
18 return standing({
19 newest:
20 listing === "unreachable"
21 ? "unreachable"
22 : listing[0]
23 ? { finishedAt: listing[0].finishedAt, key: keyOf(listing[0]) }
24 : null,
25 drill: lastDrill(app.db),
26 now: Date.now(),
27 });
28 }
29
30 /** The standing now, listing the store; undefined when no store is set. */
31 export async function recoverableNow(app: App): Promise<Standing | undefined> {
32 const svc = snapshotsOf(app);
33 if (svc === undefined || svc.store === undefined) return undefined;
34 try {
35 return standingOf(app, await svc.list());
36 } catch {
37 return standingOf(app, "unreachable");
38 }
39 }
src/snapshot/standing.ts added +55
@@ -0,0 +1,55 @@
1 /**
2 * Is the forge recoverable right now, in one line: the store answers, the
3 * newest snapshot is young, it carries the key, and the last drill passed.
4 * Plain data in, plain data out; the Backups page prints `line`.
5 */
6
7 import type { DrillResult } from "./drill.ts";
8
9 /** A snapshot older than this is a night missed. */
10 export const STALE_AFTER_MS = 36 * 3_600_000;
11
12 export interface StandingInput {
13 /** Null when the store could not be listed. */
14 readonly newest: { readonly finishedAt: string; readonly key: "wrapped" | "none" | "raw" } | null | "unreachable";
15 readonly drill: DrillResult | undefined;
16 readonly now: number;
17 }
18
19 export interface Standing {
20 readonly recoverable: boolean;
21 /** Something is wrong now; a drill that has merely not run yet is not. */
22 readonly alarm: boolean;
23 readonly line: string;
24 }
25
26 function age(ms: number): string {
27 const h = Math.floor(ms / 3_600_000);
28 return h < 1 ? "under an hour" : h < 48 ? `${h} h` : `${Math.floor(h / 24)} days`;
29 }
30
31 export function standing(input: StandingInput): Standing {
32 const { newest, drill, now } = input;
33 if (newest === "unreachable")
34 return { recoverable: false, alarm: true, line: "Not recoverable: the store could not be reached." };
35 if (newest === null)
36 return { recoverable: false, alarm: true, line: "Not recoverable: the store holds no snapshot." };
37 const old = now - Date.parse(newest.finishedAt);
38 const parts = [
39 "store reachable",
40 `newest snapshot ${age(old)} old`,
41 newest.key === "wrapped" ? "key carried" : newest.key === "raw" ? "key carried unwrapped" : "no key carried",
42 drill === undefined
43 ? "no drill yet"
44 : drill.verdict === "green"
45 ? `last drill green (${drill.at.slice(0, 10)})`
46 : `last drill failed at ${drill.failedStep ?? "a step"}`,
47 ];
48 const sound = old <= STALE_AFTER_MS && newest.key === "wrapped";
49 const ok = sound && drill?.verdict === "green";
50 return {
51 recoverable: ok,
52 alarm: !ok && !(sound && drill === undefined),
53 line: `${ok ? "Recoverable" : "Recoverable only in part"}: ${parts.join(", ")}.`,
54 };
55 }
src/web/pages/backups.ts +9 −1
@@ -15,6 +15,7 @@ import {
1515 type DestinationInput,
1616 } from "../../actions/destination.ts";
1717 import { resolveDestination, sealedSet } from "../../snapshot/destination.ts";
18 import { standingOf } from "../../snapshot/recoverable.ts";
1819 import { keyOf } from "../../snapshot/snapshot.ts";
1920 import { lastDrill } from "../../snapshot/drills.ts";
2021 import { snapshotsOf } from "../../snapshot/service.ts";
@@ -96,7 +97,7 @@ function drillLine(ctx: Ctx): Html {
9697 ? html`<p class="backups-drill">
9798 ${icon("check")} Last drill ${time(d.at)}: snapshot
9899 <code>${d.snapshotId ?? ""}</code> restored green in ${d.ms} ms —
99 ${d.counts.repositories} repositories, ${d.counts.issues} issues.
100 ${d.counts.repositories} repositories, ${d.counts.users} users, ${d.counts.issues} issues, ${d.counts.pulls} pulls, ${d.counts.apps} apps.
100101 </p>`
101102 : html`<p class="backups-error backups-drill">
102103 ${icon("alert")} Last drill ${time(d.at)}: snapshot
@@ -135,6 +136,10 @@ export async function backupsPage(ctx: Ctx): Promise<Response> {
135136 } catch (error) {
136137 listing = String(error);
137138 }
139 const stand = standingOf(
140 ctx.app,
141 listing !== undefined ? "unreachable" : snapshots,
142 );
138143 const restore = snapshots[0]
139144 ? html`<pre class="backups-restore">
140145 bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>`
@@ -148,6 +153,9 @@ bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>`
148153 crew's logs — to <code>${svc.store.where}</code>, and keeps the newest
149154 fourteen.
150155 </p>
156 <p class="${stand.alarm ? "backups-error" : "backups-drill"}">
157 ${icon(stand.alarm ? "alert" : stand.recoverable ? "check" : "clock")} ${stand.line}
158 </p>
151159 ${keyNote(svc.wraps, snapshots[0])}
152160 ${when(
153161 svc.progress(),
test/domains.test.ts +1 −1
@@ -62,7 +62,7 @@ test("a nearly full disk says the state's words", () => {
6262
6363 test("a red restore drill says the snapshot store's words", () => {
6464 recordVerdict(dataDir, {
65 at: new Date().toISOString(), snapshotId: null, ms: 1, counts: { repositories: 0, issues: 0 },
65 at: new Date().toISOString(), snapshotId: null, ms: 1, counts: { repositories: 0, users: 0, issues: 0, pulls: 0, apps: 0 },
6666 health: "unreached", verdict: "red", failedStep: "fetch", reason: "no bucket",
6767 });
6868 for (const s of said("snapshots")) expect(read()).toContain(s);
test/drill-board-line.test.ts +1 −1
@@ -23,7 +23,7 @@ const drill = (at: number, red: boolean): DrillResult => ({
2323 at: new Date(at).toISOString(),
2424 snapshotId: "snap-1",
2525 ms: 5,
26 counts: { repositories: 1, issues: 1 },
26 counts: { repositories: 1, users: 1, issues: 1, pulls: 0, apps: 0 },
2727 health: red ? "failed" : "ok",
2828 verdict: red ? "red" : "green",
2929 failedStep: red ? "unseal" : null,
test/drill-counts.test.ts added +34
@@ -0,0 +1,34 @@
1 /** A drill's counts survive the database: users, pulls and apps, not only zeros. */
2 import { expect, test } from "bun:test";
3 import { mkdtempSync, rmSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp } from "../src/app.ts";
7 import type { DrillResult } from "../src/snapshot/drill.ts";
8 import { lastDrill, recordDrill } from "../src/snapshot/drills.ts";
9 import { quietLogs } from "./helpers/globals.ts";
10
11 quietLogs();
12
13 test("recordDrill then lastDrill returns the counts it was given", () => {
14 const root = mkdtempSync(join(tmpdir(), "forge-drillcounts-"));
15 const app = createApp({ dataDir: root, port: 0 });
16 try {
17 expect(lastDrill(app.db)).toBeUndefined();
18 const result: DrillResult = {
19 at: "2026-10-12T09:00:00.000Z",
20 snapshotId: "snap-1",
21 ms: 99,
22 counts: { repositories: 7, users: 3, issues: 42, pulls: 5, apps: 2 },
23 health: "ok",
24 verdict: "green",
25 failedStep: null,
26 reason: null,
27 };
28 recordDrill(app.db, result);
29 expect(lastDrill(app.db)).toEqual(result);
30 } finally {
31 app.close();
32 rmSync(root, { recursive: true, force: true });
33 }
34 });
test/drill-verdict.test.ts +2 −2
@@ -134,7 +134,7 @@ describe("the drill's verdict", () => {
134134 at: "2026-09-22T09:00:00Z",
135135 snapshotId: null,
136136 ms: 5,
137 counts: { repositories: 0, issues: 0 },
137 counts: { repositories: 0, users: 0, issues: 0, pulls: 0, apps: 0 },
138138 health: "unreached",
139139 verdict: "red",
140140 failedStep: "fetch",
@@ -221,7 +221,7 @@ describe("telling the recovery issue", () => {
221221 at: "2026-10-18T09:00:00Z",
222222 snapshotId: "s",
223223 ms: 1,
224 counts: { repositories: 0, issues: 0 },
224 counts: { repositories: 0, users: 0, issues: 0, pulls: 0, apps: 0 },
225225 health: "ok",
226226 verdict: "green",
227227 failedStep: null,
test/recoverable.test.ts added +38
@@ -0,0 +1,38 @@
1 import { expect, test } from "bun:test";
2 import { standing, STALE_AFTER_MS } from "../src/snapshot/standing.ts";
3 import type { DrillResult } from "../src/snapshot/drill.ts";
4
5 const now = Date.parse("2026-10-15T12:00:00Z");
6 const counts = { repositories: 1, users: 1, issues: 1, pulls: 1, apps: 1 };
7 const green: DrillResult = {
8 at: "2026-10-12T09:00:00.000Z", snapshotId: "s", ms: 1, counts,
9 health: "ok", verdict: "green", failedStep: null, reason: null,
10 };
11 const young = { finishedAt: new Date(now - 3_600_000).toISOString(), key: "wrapped" as const };
12
13 test("recoverable only with a young keyed snapshot and a green drill", () => {
14 expect(standing({ newest: young, drill: green, now }).recoverable).toBe(true);
15 expect(standing({ newest: { ...young, key: "none" }, drill: green, now }).recoverable).toBe(false);
16 expect(standing({ newest: young, drill: undefined, now }).line).toContain("no drill yet");
17 const old = { ...young, finishedAt: new Date(now - STALE_AFTER_MS - 1).toISOString() };
18 expect(standing({ newest: old, drill: green, now }).recoverable).toBe(false);
19 expect(standing({ newest: young, drill: { ...green, verdict: "red", failedStep: "unseal" }, now }).line).toContain("failed at unseal");
20 });
21
22 test("an unlistable store is not recoverable, said first", () => {
23 const s = standing({ newest: "unreachable", drill: green, now });
24 expect(s.recoverable).toBe(false);
25 expect(s.line).toContain("could not be reached");
26 });
27
28 test("no drill yet is calm; a failed one, a missing key or an empty store is an alarm", () => {
29 const none = standing({ newest: young, drill: undefined, now });
30 expect(none.recoverable).toBe(false);
31 expect(none.alarm).toBe(false);
32 expect(none.line).toStartWith("Recoverable only in part");
33 expect(standing({ newest: young, drill: green, now }).alarm).toBe(false);
34 expect(standing({ newest: young, drill: { ...green, verdict: "red", failedStep: "unseal" }, now }).alarm).toBe(true);
35 expect(standing({ newest: { ...young, key: "none" }, drill: undefined, now }).alarm).toBe(true);
36 expect(standing({ newest: null, drill: green, now }).alarm).toBe(true);
37 expect(standing({ newest: "unreachable", drill: green, now }).alarm).toBe(true);
38 });
test/recovery-doc.test.ts +28 −3
@@ -22,7 +22,7 @@ test("the doc's restore command is the one restore.ts prints", () => {
2222 /"usage: (bun run src\/snapshot\/restore\.ts [^"]+)"/,
2323 )?.[1];
2424 expect(printed).toBeDefined();
25 expect(doc).toContain(` ${printed}\n`);
25 expect(doc).toContain(printed!.replace("<snapshot-name|latest> <data-dir>", "latest /srv/forge-data"));
2626 });
2727
2828 test("the doc's prefix and object names are the ones snapshot.ts writes", () => {
@@ -42,8 +42,8 @@ test("the doc's prefix and object names are the ones snapshot.ts writes", () =>
4242 expect(snap).toContain(p);
4343 expect(snap).toContain(".bundle");
4444 expect(doc).toContain("<repo>.bundle");
45 expect(doc).not.toContain("manual/");
46 expect(doc).not.toContain("openssl");
45 expect(doc).toContain("manual/");
46 expect(doc).toContain("openssl enc -d -aes-256-cbc -pbkdf2");
4747 });
4848
4949 test("`latest` is a name restore.ts accepts, not an object", () => {
@@ -73,3 +73,28 @@ test("the doc says where the drill's verdicts are posted, and names its steps",
7373 const steps = read("src/snapshot/drill.ts").match(/type DrillStep = ([^;]+);/)?.[1];
7474 for (const step of steps!.matchAll(/"(\w+)"/g)) expect(doc).toContain(step[1]!);
7575 });
76
77 test("the drill runs the commands the card prints", () => {
78 // Command 3: the drill restores through the very function restore.ts runs.
79 expect(read("src/snapshot/drill.ts")).toContain('from "./restore.ts"');
80 // Command 4: the boot line is what the drill's child gets — same names,
81 // same values, same entry point.
82 const line = doc.match(/^ {7}(FORGE_DATA=\S+ PORT=\d+ FORGE_SSH_PORT=0 bun run src\/main\.ts)$/m)?.[1];
83 expect(line).toBeDefined();
84 const docEnv = Object.fromEntries(
85 [...line!.matchAll(/\b([A-Z_]+)=(\S+)/g)].map((m) => [m[1]!, m[2]!]),
86 );
87 const src = read("src/snapshot/boot.ts");
88 const block = src.match(/env: \{([\s\S]*?)\n {4}\},/)?.[1] ?? "";
89 const bootEnv = Object.fromEntries(
90 [...block.matchAll(/^ {6}([A-Z_]+): (.+?),$/gm)].map((m) => [m[1]!, m[2]!]),
91 );
92 // The directory and port are the caller's; the SSH listener is off in both.
93 expect(bootEnv["FORGE_DATA"]).toBe("dataDir");
94 expect(bootEnv["PORT"]).toBe("String(port)");
95 expect(bootEnv["FORGE_SSH_PORT"]).toBe(`"${docEnv["FORGE_SSH_PORT"]}"`);
96 expect(Object.keys(docEnv).sort()).toEqual(["FORGE_DATA", "FORGE_SSH_PORT", "PORT"]);
97 expect(src).toContain('join(TREE, "src/main.ts")');
98 expect(line).toContain("bun run src/main.ts");
99 expect(src).toContain("/api/v1/health");
100 });
test/recovery-terminal.test.ts added +93
@@ -0,0 +1,93 @@
1 /**
2 * The terminal's answer to "can I recover right now?": `GET /api/v1/recovery`
3 * for an admin only, and `forge recovery` printing its line.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtempSync, rmSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { ForgeApi } from "../src/cli/api.ts";
13 import { startSnapshots, type SnapshotsHandle } from "../src/snapshot/service.ts";
14 import { dirStore } from "../src/snapshot/store.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 const CLI = new URL("../src/cli/main.ts", import.meta.url).pathname;
18
19 quietLogs();
20
21 let root = "";
22 let app: App;
23 let svc: SnapshotsHandle;
24 let servers: Servers;
25
26 const login = async (username: string, password: string) => {
27 const r = await fetch(`${servers.url}/signin`, {
28 method: "POST",
29 headers: { origin: servers.url },
30 body: new URLSearchParams({ username, password }),
31 redirect: "manual",
32 });
33 return (r.headers.get("set-cookie") ?? "").split(";")[0]!;
34 };
35
36 beforeAll(async () => {
37 root = mkdtempSync(join(tmpdir(), "forge-recterm-"));
38 app = createApp({ dataDir: root, port: 0 });
39 for (const [username, password, admin] of [
40 ["alice", "a-good-passphrase", true],
41 ["bob", "another-good-passphrase", false],
42 ] as const) {
43 const u = await createUser(app.db, {
44 trusted: true, username, email: `${username}@forge.local`, password, adminIfFirst: admin,
45 });
46 if (!u.ok) throw new Error(u.error);
47 }
48 svc = startSnapshots(app, dirStore(join(root, "store")), { version: "t", nightly: false });
49 servers = await serve(app);
50 });
51 afterAll(async () => {
52 servers.stop();
53 await svc.stop();
54 app.close();
55 rmSync(root, { recursive: true, force: true });
56 });
57
58 test("an admin reads the line; anyone else finds nothing", async () => {
59 const alice = await login("alice", "a-good-passphrase");
60 const res = await fetch(`${servers.url}/api/v1/recovery`, { headers: { cookie: alice } });
61 expect(res.status).toBe(200);
62 const body = (await res.json()) as { recoverable: boolean; alarm: boolean; line: string };
63 expect(body.recoverable).toBe(false);
64 expect(body.line).toBe("Not recoverable: the store holds no snapshot.");
65 const bob = await login("bob", "another-good-passphrase");
66 expect((await fetch(`${servers.url}/api/v1/recovery`, { headers: { cookie: bob } })).status).toBe(404);
67 expect((await fetch(`${servers.url}/api/v1/recovery`)).status).toBeGreaterThanOrEqual(401);
68 });
69
70 test("`forge recovery` prints the line and exits 1 while not recoverable", async () => {
71 const minted = await fetch(`${servers.url}/api/v1/tokens`, {
72 method: "POST",
73 headers: { "content-type": "application/json" },
74 body: JSON.stringify({
75 adminConfirm: true, username: "alice", password: "a-good-passphrase", name: "cli", scope: "ro",
76 }),
77 });
78 const token = ((await minted.json()) as { token: string }).token;
79 const api = await new ForgeApi(servers.url, token).recovery();
80 expect(api.ok).toBe(true);
81 const home = mkdtempSync(join(tmpdir(), "forge-recterm-home-"));
82 try {
83 const proc = Bun.spawn(["bun", "run", CLI, "recovery"], {
84 env: { PATH: process.env["PATH"] ?? "", HOME: home, FORGE_URL: servers.url, FORGE_TOKEN: token, NO_COLOR: "1" },
85 stdout: "pipe", stderr: "pipe",
86 });
87 const [out, code] = await Promise.all([new Response(proc.stdout).text(), proc.exited]);
88 expect(out.trim()).toBe("Not recoverable: the store holds no snapshot.");
89 expect(code).toBe(1);
90 } finally {
91 rmSync(home, { recursive: true, force: true });
92 }
93 });
test/snapshot-drill-page.test.ts +3 −2
@@ -62,7 +62,7 @@ describe("the drill on the Backups page", () => {
6262 at: new Date().toISOString(),
6363 snapshotId: "snap-stub-1",
6464 ms: 1234,
65 counts: { repositories: 7, issues: 42 },
65 counts: { repositories: 7, users: 3, issues: 42, pulls: 5, apps: 2 },
6666 health: verdict === "green" ? "ok" : "unreached",
6767 verdict,
6868 failedStep: verdict === "green" ? null : "unseal",
@@ -97,7 +97,8 @@ describe("the drill on the Backups page", () => {
9797 expect(ran).toBe(1);
9898 const html = await page(cookie);
9999 expect(html).toContain("snap-stub-1");
100 expect(html).toContain("7 repositories, 42 issues");
100 expect(html).toContain("7 repositories, 3 users, 42 issues, 5 pulls, 2 apps");
101 expect(html).toContain("Not recoverable: the store holds no snapshot.");
101102 expect(html).toContain("1234 ms");
102103 expect(app.db.query("SELECT count(*) AS n FROM drill").get()).toEqual({ n: 1 });
103104 });
test/snapshot-drill.test.ts +1 −1
@@ -98,7 +98,7 @@ describe("the restore drill", () => {
9898 expect(r.verdict).toBe("green");
9999 expect(r.failedStep).toBeNull();
100100 expect(r.snapshotId).toBe("2026-09-22T08-00-00Z");
101 expect(r.counts).toEqual({ repositories: 1, issues: 2 });
101 expect(r.counts).toEqual({ repositories: 1, users: 1, issues: 2, pulls: 0, apps: 1 });
102102 expect(r.ms).toBeGreaterThanOrEqual(0);
103103 expect(scratchLeft()).toEqual([]);
104104 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs