toolroll 0.9.116 → 0.9.117
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +43 -26
- package/dist/acp-agents.js +14 -1
- package/dist/acp-client.js +19 -1
- package/dist/agent-change-check.js +60 -0
- package/dist/agent-change-schema.js +19 -0
- package/dist/agent-detect.js +11 -1
- package/dist/agent-fence.js +39 -10
- package/dist/agent-network-request.js +108 -0
- package/dist/agent-requests.js +105 -0
- package/dist/approval-summary.js +3 -3
- package/dist/backup.js +17 -1
- package/dist/batch-checks.js +81 -18
- package/dist/browser/terminal.js +41 -41
- package/dist/browser/workspace.css +2 -2
- package/dist/browser/workspace.js +36 -36
- package/dist/builder.js +3 -1
- package/dist/candidate-materialize.js +119 -0
- package/dist/central-enrollment-contract.js +156 -0
- package/dist/central-recovery-stage.js +329 -0
- package/dist/chat-actions.js +101 -2
- package/dist/chat-channel.js +40 -0
- package/dist/check-only-standing.js +13 -0
- package/dist/check-only.js +25 -13
- package/dist/check-recovery-hold.js +199 -0
- package/dist/check-recovery-index-schema.js +3 -0
- package/dist/check-screenshots.js +83 -0
- package/dist/cli.js +125 -6
- package/dist/codex-limits.js +4 -0
- package/dist/connect-cli.js +257 -11
- package/dist/contracts/chat-actions.js +4 -0
- package/dist/contracts/console-api.js +14 -3
- package/dist/contracts/engine-api.js +331 -2
- package/dist/contracts/lead-tools.js +56 -2
- package/dist/contracts/provider.js +1 -1
- package/dist/contracts/route.js +1 -1
- package/dist/contracts/terminal-connection.js +50 -0
- package/dist/converse.js +80 -4
- package/dist/device-pair.js +280 -0
- package/dist/direct-chat-artifacts.js +347 -0
- package/dist/direct-chat-catalog.js +311 -0
- package/dist/direct-chat-fence.js +96 -0
- package/dist/direct-chat-git.js +343 -0
- package/dist/direct-chat-laptop.js +19 -0
- package/dist/direct-chat-schema.js +181 -0
- package/dist/direct-chat-ship.js +861 -0
- package/dist/direct-chat-workspace.js +389 -0
- package/dist/direct-chat.js +2107 -0
- package/dist/doctor.js +1 -1
- package/dist/easy-start.js +18 -0
- package/dist/egress.js +25 -4
- package/dist/engine-chat.js +454 -0
- package/dist/engine-reads.js +141 -13
- package/dist/exec.js +4 -3
- package/dist/flexible-agents.js +8 -16
- package/dist/flexible-session.js +91 -47
- package/dist/flexible-ship.js +87 -7
- package/dist/flexible-start.js +4 -1
- package/dist/flexible-thread.js +2 -3
- package/dist/flexible-turns.js +26 -5
- package/dist/flow-triggers.js +13 -4
- package/dist/flows-ui.js +54 -20
- package/dist/handoff-cli.js +630 -0
- package/dist/invoke.js +55 -13
- package/dist/lead-contract.js +5 -4
- package/dist/lead-doors.js +80 -1
- package/dist/lead-progress.js +9 -0
- package/dist/lead-tools.js +681 -10
- package/dist/lead.js +37 -9
- package/dist/live-bus.js +11 -0
- package/dist/live-terminal.js +132 -12
- package/dist/local-handoff.js +363 -0
- package/dist/local-owner-acts.js +264 -2
- package/dist/local-owner.js +16 -1
- package/dist/multiplayer-handoff.js +528 -0
- package/dist/multiplayer-presence.js +471 -0
- package/dist/names.js +17 -4
- package/dist/needs-you.js +10 -0
- package/dist/operate.js +280 -19
- package/dist/policy.js +2 -2
- package/dist/project-delete-ui.js +18 -11
- package/dist/project-delete.js +65 -4
- package/dist/project-tools.js +1 -1
- package/dist/prompt.js +1 -1
- package/dist/provider-connection.js +2 -0
- package/dist/provider-home.js +251 -8
- package/dist/provider.js +3 -2
- package/dist/publish.js +119 -64
- package/dist/pull-request-flow.js +35 -14
- package/dist/read-executor-worker.js +1 -1
- package/dist/read-executor.js +95 -1
- package/dist/restore-retirement.js +152 -0
- package/dist/result-follow-ups.js +116 -37
- package/dist/route-change.js +44 -4
- package/dist/scope.js +62 -5
- package/dist/serve.js +49 -5
- package/dist/server/chat.js +94 -13
- package/dist/server/direct-chat.js +583 -0
- package/dist/server/engine-api.js +219 -21
- package/dist/server/flows.js +43 -10
- package/dist/server/found-repos.js +25 -0
- package/dist/server/guards.js +20 -6
- package/dist/server/live.js +81 -23
- package/dist/server/pages.js +67 -13
- package/dist/server/people-tokens.js +47 -6
- package/dist/server/remote.js +29 -0
- package/dist/server/render-results.js +6 -2
- package/dist/server/render-settings.js +4 -2
- package/dist/server/render-tasks.js +18 -17
- package/dist/server/route-table.js +69 -2
- package/dist/server/settings.js +22 -7
- package/dist/server/task-views.js +15 -3
- package/dist/server/tasks.js +39 -2
- package/dist/server/terminals.js +185 -11
- package/dist/settings-proofs.js +1 -1
- package/dist/store.js +499 -56
- package/dist/subscription-chat.js +33 -6
- package/dist/subscription-usage.js +233 -0
- package/dist/task-live.js +2 -1
- package/dist/teardown-git.js +34 -4
- package/dist/terminal-connection.js +159 -0
- package/dist/tui/darwin-arm64/toolroll-tui +0 -0
- package/dist/tui/darwin-x64/toolroll-tui +0 -0
- package/dist/tui/linux-arm64/toolroll-tui +0 -0
- package/dist/tui/linux-x64/toolroll-tui +0 -0
- package/dist/tui-contract.js +1 -1
- package/dist/tui-launch.js +32 -1
- package/dist/workspace-identity-schema.js +21 -0
- package/package.json +3 -1
package/dist/builder.js
CHANGED
|
@@ -1665,7 +1665,9 @@ async function settleProof(captured, statArtifactId, sealedHead) {
|
|
|
1665
1665
|
}
|
|
1666
1666
|
else if (batched && repo !== null) {
|
|
1667
1667
|
verifyCommand = { configured: false };
|
|
1668
|
-
queueBatchCheck(store, { runId, taskId: request.taskId, repo, head: sealedHead, base: captured.baseRevision, command: configured }, now());
|
|
1668
|
+
const queued = queueBatchCheck(store, { runId, taskId: request.taskId, repo, head: sealedHead, base: captured.baseRevision, command: configured }, now());
|
|
1669
|
+
if (typeof queued !== "number")
|
|
1670
|
+
recordCheckNote("Checks are on hold after recovery. Earlier execution is unverified.");
|
|
1669
1671
|
}
|
|
1670
1672
|
else if (!store.proveRunnerCustodyForSpawn(runId, now())) {
|
|
1671
1673
|
verifyCommand = { configured: true, ran: false, attemptFailed: true, failure: "custody-lost" };
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { run as execRun } from "./exec.js";
|
|
5
|
+
import { storeEvidence } from "./evidence.js";
|
|
6
|
+
import { validateHandoffPatch } from "./local-handoff.js";
|
|
7
|
+
import { requestFollowUpChecks } from "./result-follow-ups.js";
|
|
8
|
+
import { teardownGit } from "./teardown-git.js";
|
|
9
|
+
const COMMIT_SHA = /^[0-9a-f]{40}$/;
|
|
10
|
+
export async function materializePromotedCandidate(input) {
|
|
11
|
+
const { store, evidenceRoot, repo, taskRef, taskId, candidateId, author, promoter, baseCommit, patch, patchSha256, note, now } = input;
|
|
12
|
+
if (!COMMIT_SHA.test(baseCommit)) {
|
|
13
|
+
return { ok: false, error: "invalid_base", message: "Candidate base commit is missing or not a valid Git commit SHA." };
|
|
14
|
+
}
|
|
15
|
+
const checked = validateHandoffPatch(patch);
|
|
16
|
+
if (!checked.ok) {
|
|
17
|
+
return { ok: false, error: "invalid_patch", message: checked.error };
|
|
18
|
+
}
|
|
19
|
+
const git = teardownGit(execRun);
|
|
20
|
+
const scratch = mkdtempSync(join(tmpdir(), "so-promote-"));
|
|
21
|
+
const worktree = join(scratch, "wt");
|
|
22
|
+
const patchFile = join(scratch, "candidate.patch");
|
|
23
|
+
const branch = `toolroll/candidate/${candidateId}`;
|
|
24
|
+
let worktreeAdded = false;
|
|
25
|
+
try {
|
|
26
|
+
writeFileSync(patchFile, patch, { encoding: "utf8", mode: 0o600 });
|
|
27
|
+
const added = await git(repo, ["worktree", "add", "--detach", worktree, baseCommit]);
|
|
28
|
+
if (added.code !== 0) {
|
|
29
|
+
return {
|
|
30
|
+
ok: false,
|
|
31
|
+
error: "worktree_failed",
|
|
32
|
+
message: `Could not create central verification worktree at ${baseCommit.slice(0, 8)}: ${(added.stderr || added.stdout).trim().slice(0, 200)}`,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
worktreeAdded = true;
|
|
36
|
+
const applied = await git(worktree, ["apply", "--index", "--", patchFile]);
|
|
37
|
+
if (applied.code !== 0) {
|
|
38
|
+
return {
|
|
39
|
+
ok: false,
|
|
40
|
+
error: "apply_failed",
|
|
41
|
+
message: `Candidate patch did not apply cleanly at ${baseCommit.slice(0, 8)}: ${(applied.stderr || applied.stdout).trim().slice(0, 200)}`,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const summary = note.trim() === ""
|
|
45
|
+
? `Promote candidate ${candidateId} for ${taskId}`
|
|
46
|
+
: `Promote candidate ${candidateId} for ${taskId}: ${note.trim().slice(0, 120)}`;
|
|
47
|
+
const body = [
|
|
48
|
+
summary,
|
|
49
|
+
"",
|
|
50
|
+
`Task: ${taskId}`,
|
|
51
|
+
`Candidate: ${candidateId}`,
|
|
52
|
+
`Author: ${author}`,
|
|
53
|
+
`Promoted-by: ${promoter}`,
|
|
54
|
+
`Patch-SHA256: ${patchSha256}`,
|
|
55
|
+
].join("\n");
|
|
56
|
+
const committed = await git(worktree, [
|
|
57
|
+
"-c", "user.name=Toolroll Candidate Promotion",
|
|
58
|
+
"-c", "user.email=toolroll@local",
|
|
59
|
+
"commit", "--no-verify", "--no-gpg-sign", "-m", body,
|
|
60
|
+
]);
|
|
61
|
+
if (committed.code !== 0) {
|
|
62
|
+
return {
|
|
63
|
+
ok: false,
|
|
64
|
+
error: "commit_failed",
|
|
65
|
+
message: `Could not commit candidate in central worktree: ${(committed.stderr || committed.stdout).trim().slice(0, 200)}`,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
const headRes = await git(worktree, ["rev-parse", "HEAD"]);
|
|
69
|
+
const headCommit = headRes.stdout.trim();
|
|
70
|
+
if (headRes.code !== 0 || !COMMIT_SHA.test(headCommit)) {
|
|
71
|
+
return { ok: false, error: "commit_failed", message: "Could not read materialized commit SHA." };
|
|
72
|
+
}
|
|
73
|
+
const branched = await git(repo, ["branch", "-f", branch, headCommit]);
|
|
74
|
+
if (branched.code !== 0) {
|
|
75
|
+
return { ok: false, error: "commit_failed", message: `Could not publish central candidate branch ${branch}.` };
|
|
76
|
+
}
|
|
77
|
+
const diffRes = await git(repo, ["diff", `${baseCommit}..${headCommit}`]);
|
|
78
|
+
const canonicalDiff = diffRes.code === 0 && diffRes.stdout.trim() !== "" ? diffRes.stdout : patch;
|
|
79
|
+
const stamp = now.toISOString();
|
|
80
|
+
const runId = store.transact(() => {
|
|
81
|
+
const inserted = store.handle.prepare(`INSERT INTO run (
|
|
82
|
+
task_ref, lease_id, runner, role, provider,
|
|
83
|
+
base_revision, head_revision, branch, worktree, phase,
|
|
84
|
+
outcome, reason, committed, started_at, finished_at
|
|
85
|
+
) VALUES (?, ?, ?, 'builder', 'claude', ?, ?, ?, ?, 'build', 'built', ?, 1, ?, ?)`).run(taskRef, `promote:${candidateId}`, "candidate-promotion", baseCommit, headCommit, branch, repo, `Promoted local candidate ${candidateId} by ${promoter} (author: ${author})`, stamp, stamp);
|
|
86
|
+
const id = Number(inserted.lastInsertRowid);
|
|
87
|
+
store.recordRunCheck(id, { status: "not-run", exitCode: null, suites: [] }, now);
|
|
88
|
+
return id;
|
|
89
|
+
});
|
|
90
|
+
storeEvidence(store, evidenceRoot, runId, "diff", "diff.patch", Buffer.from(canonicalDiff, "utf8"), `git diff ${baseCommit.slice(0, 12)}..${headCommit.slice(0, 12)} (candidate ${candidateId})`, now, { captureStatus: "ok" });
|
|
91
|
+
storeEvidence(store, evidenceRoot, runId, "terminal-diff", "terminal-diff.patch", Buffer.from(canonicalDiff, "utf8"), `git diff ${baseCommit.slice(0, 12)}..${headCommit.slice(0, 12)} (candidate ${candidateId})`, now, { captureStatus: "ok" });
|
|
92
|
+
storeEvidence(store, evidenceRoot, runId, "diff-stat", "diff-stat.json", Buffer.from(JSON.stringify({
|
|
93
|
+
schema: 1,
|
|
94
|
+
head: headCommit,
|
|
95
|
+
base: baseCommit,
|
|
96
|
+
filesTruncated: false,
|
|
97
|
+
fileCount: checked.files.length,
|
|
98
|
+
files: checked.files.map(path => ({ path })),
|
|
99
|
+
}), "utf8"), "git diff --numstat", now, { captureStatus: "ok" });
|
|
100
|
+
const requested = requestFollowUpChecks(store, { runId, level: "full", actor: promoter, why: "person" }, now);
|
|
101
|
+
const checks = requested.ok
|
|
102
|
+
? { status: "queued", requestId: requested.request, level: requested.level }
|
|
103
|
+
: {
|
|
104
|
+
status: requested.reason === "no-check" ? "not-configured" : "refused",
|
|
105
|
+
reason: requested.reason,
|
|
106
|
+
message: requested.message,
|
|
107
|
+
};
|
|
108
|
+
return { ok: true, runId, branch, baseCommit, headCommit, checks };
|
|
109
|
+
}
|
|
110
|
+
finally {
|
|
111
|
+
if (worktreeAdded) {
|
|
112
|
+
await git(repo, ["worktree", "remove", "--force", worktree]).catch(() => undefined);
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
116
|
+
}
|
|
117
|
+
catch { }
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { posix } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { WORKSPACE_ID_PATTERN, RECOVERY_GENERATION_PATTERN } from "./workspace-identity-schema.js";
|
|
5
|
+
export const ENROLLMENT_RECORD_LIMIT = 65_536;
|
|
6
|
+
const uuid = z.string().regex(WORKSPACE_ID_PATTERN);
|
|
7
|
+
const hex = z.string().regex(RECOVERY_GENERATION_PATTERN);
|
|
8
|
+
const digest = z.string().regex(/^[0-9a-f]{64}$/);
|
|
9
|
+
const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
|
10
|
+
const path = z.string().min(2).max(4096).refine(value => value.startsWith("/") && !/[\x00-\x1f\x7f\\]/.test(value)
|
|
11
|
+
&& posix.normalize(value) === value && !value.endsWith("/")
|
|
12
|
+
&& [...value].every(char => { const code = char.codePointAt(0); return code < 0xd800 || code > 0xdfff; }));
|
|
13
|
+
const identity = z.object({ dev: integer, ino: integer }).strict();
|
|
14
|
+
const common = {
|
|
15
|
+
version: z.literal(1), installationId: uuid, workspaceId: uuid, ownerUid: integer,
|
|
16
|
+
databasePath: path, statePath: path, stateIdentity: identity, protocolVersion: z.literal(1), manifestVersion: z.literal(1), transactionId: hex,
|
|
17
|
+
};
|
|
18
|
+
const expectationSchema = z.object({ ...common, pathDigest: digest, phase: z.enum(["enrolling", "enrolled", "recovery-blocked"]),
|
|
19
|
+
services: z.array(z.string().min(1).max(256)).min(1).max(8).refine(v => new Set(v).size === v.length),
|
|
20
|
+
}).strict();
|
|
21
|
+
const rootSchema = z.object({ ...common, recoveryGeneration: hex, phase: z.enum(["prepared", "committed"]) }).strict();
|
|
22
|
+
const receiptSchema = z.object({ ...common, recoveryGeneration: hex }).strict();
|
|
23
|
+
const bindingSchema = z.object({ version: z.literal(1), installationId: uuid, ownerUid: integer, databasePath: path,
|
|
24
|
+
pathDigest: digest, registryVersion: z.literal(1), centralRecoveryRequired: z.literal(true),
|
|
25
|
+
serviceId: z.string().min(1).max(256), definitionDigest: digest,
|
|
26
|
+
}).strict();
|
|
27
|
+
function decode(raw, schema) {
|
|
28
|
+
if (typeof raw !== "string" || Buffer.byteLength(raw, "utf8") > ENROLLMENT_RECORD_LIMIT)
|
|
29
|
+
return null;
|
|
30
|
+
try {
|
|
31
|
+
const value = JSON.parse(raw);
|
|
32
|
+
if (JSON.stringify(value) !== raw)
|
|
33
|
+
return null;
|
|
34
|
+
const parsed = schema.safeParse(value);
|
|
35
|
+
return parsed.success ? parsed.data : null;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export const parseEnrollmentExpectation = (raw) => decode(raw, expectationSchema);
|
|
42
|
+
export const parseEnrollmentRoot = (raw) => decode(raw, rootSchema);
|
|
43
|
+
export const parseEnrollmentReceipt = (raw) => decode(raw, receiptSchema);
|
|
44
|
+
export const parseEnrollmentBinding = (raw) => decode(raw, bindingSchema);
|
|
45
|
+
const unavailable = z.object({ observed: z.literal("unavailable"), path, reason: z.enum(["denied", "changed", "invalid", "unknown"]) }).strict();
|
|
46
|
+
const absent = z.object({ observed: z.literal("absent"), path, error: z.literal("ENOENT") }).strict();
|
|
47
|
+
const directory = z.object({ observed: z.literal("directory"), path, uid: integer, mode: integer, dev: integer, ino: integer }).strict();
|
|
48
|
+
const file = z.object({ observed: z.literal("file"), path, uid: integer, mode: integer, nlink: integer,
|
|
49
|
+
dev: integer, ino: integer, size: integer, bytes: z.string().max(ENROLLMENT_RECORD_LIMIT),
|
|
50
|
+
}).strict();
|
|
51
|
+
const node = z.discriminatedUnion("observed", [unavailable, absent, directory, file]);
|
|
52
|
+
const receipt = z.discriminatedUnion("observed", [
|
|
53
|
+
z.object({ observed: z.literal("absent") }).strict(),
|
|
54
|
+
z.object({ observed: z.literal("unavailable") }).strict(),
|
|
55
|
+
z.object({ observed: z.literal("record"), bytes: z.string().max(ENROLLMENT_RECORD_LIMIT) }).strict(),
|
|
56
|
+
]);
|
|
57
|
+
const captureSchema = z.object({ version: z.literal(1), ownerUid: integer, home: path, databasePath: path,
|
|
58
|
+
homeDirectory: node, stateDirectory: node, registryDirectory: node, expectationsDirectory: node,
|
|
59
|
+
secretsDirectory: node, expectation: node, root: node, binding: node, receipt,
|
|
60
|
+
}).strict();
|
|
61
|
+
export const parseEnrollmentCapture = (raw) => decode(raw, captureSchema);
|
|
62
|
+
const hash = (value) => createHash("sha256").update(value).digest("hex");
|
|
63
|
+
export function capturedEnrollmentNames(home, databasePath) {
|
|
64
|
+
if (!path.safeParse(home).success || !path.safeParse(databasePath).success)
|
|
65
|
+
return null;
|
|
66
|
+
const registry = `${home}/.toolroll-central`, state = posix.dirname(databasePath), pathDigest = hash(databasePath);
|
|
67
|
+
if (!path.safeParse(state).success)
|
|
68
|
+
return null;
|
|
69
|
+
return { registry, expectations: `${registry}/expectations`, expectation: `${registry}/expectations/${pathDigest}.json`,
|
|
70
|
+
state, secrets: `${state}/.toolroll-secrets`, root: `${state}/.toolroll-secrets/central-recovery.json`, pathDigest };
|
|
71
|
+
}
|
|
72
|
+
const privateDirectory = (n, expected, uid) => n.observed === "directory"
|
|
73
|
+
&& n.path === expected && n.uid === uid && n.mode === 0o700;
|
|
74
|
+
const privateFile = (n, expected, uid) => n.observed === "file" && n.path === expected
|
|
75
|
+
&& n.uid === uid && n.mode === 0o600 && n.nlink === 1 && n.size === Buffer.byteLength(n.bytes, "utf8") ? n.bytes : null;
|
|
76
|
+
const missing = (n, expected) => n.observed === "absent" && n.path === expected;
|
|
77
|
+
const inaccessible = (n) => n.observed === "unavailable";
|
|
78
|
+
const assessment = (classification, reason) => Object.freeze({
|
|
79
|
+
classification, reason, nativeProof: "not-performed", capabilities: Object.freeze({ admission: false, enrollment: false,
|
|
80
|
+
recoveryReady: false, remoteReads: false, dispatch: false }),
|
|
81
|
+
});
|
|
82
|
+
export function assessEnrollmentCapture(raw) {
|
|
83
|
+
const c = parseEnrollmentCapture(raw), blocked = (why) => assessment("blocked-capture", why);
|
|
84
|
+
if (c === null)
|
|
85
|
+
return blocked("invalid-capture");
|
|
86
|
+
const n = capturedEnrollmentNames(c.home, c.databasePath);
|
|
87
|
+
if (n === null)
|
|
88
|
+
return blocked("invalid-path");
|
|
89
|
+
if (c.homeDirectory.observed !== "directory" || c.homeDirectory.path !== c.home || c.homeDirectory.uid !== c.ownerUid
|
|
90
|
+
|| (c.homeDirectory.mode & 0o022) !== 0 || !privateDirectory(c.stateDirectory, n.state, c.ownerUid))
|
|
91
|
+
return blocked("unsafe-anchor-capture");
|
|
92
|
+
if ([c.registryDirectory, c.expectationsDirectory, c.secretsDirectory, c.expectation, c.root, c.binding].some(inaccessible)
|
|
93
|
+
|| c.receipt.observed === "unavailable")
|
|
94
|
+
return blocked("indeterminate-capture");
|
|
95
|
+
const registryAbsent = missing(c.registryDirectory, n.registry);
|
|
96
|
+
const registryPresent = privateDirectory(c.registryDirectory, n.registry, c.ownerUid);
|
|
97
|
+
const expectationsAbsent = missing(c.expectationsDirectory, n.expectations);
|
|
98
|
+
const expectationsPresent = privateDirectory(c.expectationsDirectory, n.expectations, c.ownerUid);
|
|
99
|
+
const secretsAbsent = missing(c.secretsDirectory, n.secrets);
|
|
100
|
+
const secretsPresent = privateDirectory(c.secretsDirectory, n.secrets, c.ownerUid);
|
|
101
|
+
if ((!registryAbsent && !registryPresent) || (!expectationsAbsent && !expectationsPresent) || (!secretsAbsent && !secretsPresent)
|
|
102
|
+
|| (registryAbsent && !expectationsAbsent))
|
|
103
|
+
return blocked("unsafe-directory-capture");
|
|
104
|
+
const noExpectation = missing(c.expectation, n.expectation), noRoot = missing(c.root, n.root);
|
|
105
|
+
if (registryAbsent && !noExpectation || expectationsAbsent && !noExpectation || secretsAbsent && !noRoot)
|
|
106
|
+
return blocked("contradictory-capture");
|
|
107
|
+
if (noExpectation && noRoot && c.binding.observed === "absent" && c.receipt.observed === "absent") {
|
|
108
|
+
return assessment("personal-capture", "no-enrollment-evidence-in-capture");
|
|
109
|
+
}
|
|
110
|
+
if (!registryPresent || !expectationsPresent || !secretsPresent)
|
|
111
|
+
return blocked("expected-records-missing");
|
|
112
|
+
const eRaw = privateFile(c.expectation, n.expectation, c.ownerUid), rRaw = privateFile(c.root, n.root, c.ownerUid);
|
|
113
|
+
const bRaw = privateFile(c.binding, c.binding.path, c.ownerUid);
|
|
114
|
+
const e = eRaw === null ? null : parseEnrollmentExpectation(eRaw), r = rRaw === null ? null : parseEnrollmentRoot(rRaw);
|
|
115
|
+
const b = bRaw === null ? null : parseEnrollmentBinding(bRaw);
|
|
116
|
+
const d = c.receipt.observed === "record" ? parseEnrollmentReceipt(c.receipt.bytes) : null;
|
|
117
|
+
if (e === null || r === null || b === null || d === null)
|
|
118
|
+
return blocked("missing-or-invalid-record");
|
|
119
|
+
const s = c.stateDirectory;
|
|
120
|
+
if (s.observed !== "directory")
|
|
121
|
+
return blocked("unsafe-state");
|
|
122
|
+
for (const record of [e, r, d]) {
|
|
123
|
+
if (record.ownerUid !== c.ownerUid || record.databasePath !== c.databasePath || record.statePath !== n.state
|
|
124
|
+
|| record.stateIdentity.dev !== s.dev || record.stateIdentity.ino !== s.ino || record.installationId !== e.installationId
|
|
125
|
+
|| record.workspaceId !== e.workspaceId || record.transactionId !== e.transactionId)
|
|
126
|
+
return blocked("record-mismatch");
|
|
127
|
+
}
|
|
128
|
+
if (e.pathDigest !== n.pathDigest || b.pathDigest !== n.pathDigest || b.ownerUid !== c.ownerUid || b.databasePath !== c.databasePath
|
|
129
|
+
|| b.installationId !== e.installationId || !e.services.includes(b.serviceId) || r.recoveryGeneration !== d.recoveryGeneration)
|
|
130
|
+
return blocked("binding-mismatch");
|
|
131
|
+
if (e.phase !== "enrolled" || r.phase !== "committed")
|
|
132
|
+
return blocked("incomplete-transaction");
|
|
133
|
+
return assessment("consistent-enrolled-capture", "requires-native-exclusion-and-retirement-proof");
|
|
134
|
+
}
|
|
135
|
+
const phases = ["expectation-durable", "records-prepared", "expectation-enrolled", "service-activated"];
|
|
136
|
+
const transitionSchema = z.object({ before: z.string().max(ENROLLMENT_RECORD_LIMIT), after: z.string().max(ENROLLMENT_RECORD_LIMIT),
|
|
137
|
+
from: z.enum(phases), to: z.enum(phases),
|
|
138
|
+
}).strict();
|
|
139
|
+
export function assessEnrollmentTransition(raw) {
|
|
140
|
+
const input = decode(raw, transitionSchema), blocked = (why) => assessment("blocked-capture", why);
|
|
141
|
+
if (input === null)
|
|
142
|
+
return blocked("invalid-transition");
|
|
143
|
+
const before = parseEnrollmentExpectation(input.before), after = parseEnrollmentExpectation(input.after);
|
|
144
|
+
if (before === null || after === null)
|
|
145
|
+
return blocked("invalid-expected-record");
|
|
146
|
+
const from = phases.indexOf(input.from), to = phases.indexOf(input.to);
|
|
147
|
+
if (to !== from + 1)
|
|
148
|
+
return blocked("nonsequential-transition");
|
|
149
|
+
const expectedBefore = from < 2 ? "enrolling" : "enrolled", expectedAfter = to < 2 ? "enrolling" : "enrolled";
|
|
150
|
+
if (before.phase !== expectedBefore || after.phase !== expectedAfter)
|
|
151
|
+
return blocked("phase-mismatch");
|
|
152
|
+
const { phase: _beforePhase, ...oldFields } = before, { phase: _afterPhase, ...newFields } = after;
|
|
153
|
+
if (JSON.stringify(oldFields) !== JSON.stringify(newFields))
|
|
154
|
+
return blocked("expected-record-changed");
|
|
155
|
+
return assessment("consistent-transition-capture", "transition-represented-only-no-write-authority");
|
|
156
|
+
}
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import { resolve, join } from "node:path";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { DatabaseSync } from "node:sqlite";
|
|
5
|
+
import { openStore } from "./store.js";
|
|
6
|
+
import { holdAutoPublish, autoPublishHeld, PUBLISH_ALLOWED_ACTION, PUBLISH_HELD_ACTION } from "./release-auto.js";
|
|
7
|
+
import { revokeCoordinator } from "./coordinator.js";
|
|
8
|
+
export const MAX_STAGE_BYTES = 128 * 1024 * 1024;
|
|
9
|
+
const SUPPORTED_SCHEMA = 184;
|
|
10
|
+
const SCHEMA_OBJECT_COUNT = 724;
|
|
11
|
+
const SCHEMA_DIGEST = "e56d12d9ce4f612ab6de397055ca9aeb233d939c001446fd90b7b3ebbcc5a62c";
|
|
12
|
+
const INVENTORY = [
|
|
13
|
+
["person-credentials", "store.ts:revokeApiToken", "credential", true],
|
|
14
|
+
["lead-credentials", "store.ts:revokeLeadCredentials", "credential", true],
|
|
15
|
+
["coordinator-credentials", "coordinator.ts:revokeCoordinator", "credential/coordinator_proposal", true],
|
|
16
|
+
["inbound-oauth", "mcp-oauth.ts/store.ts", "oauth_code/oauth_grant/oauth_refresh", true],
|
|
17
|
+
["publication-grant-verifier", "store.ts:revokePublicationGrant/publish.ts:permitsPublication", "publication_grant", true],
|
|
18
|
+
["release-publish-ledger-hold", "release-auto.ts:holdAutoPublish/autoPublishHeld", "action_ledger (latest held/allowed by id for nonnull task ids)", true],
|
|
19
|
+
["intake-grant-fresh-command-admission", "store.ts:clearIntakeGrant/operate.ts:intakeCommand", "intake_grant", true],
|
|
20
|
+
["flexible-snapshot-sign-in-admission", "flexible-sign-in.ts verifier semantics (private snapshot SQL only)", "flexible_sign_in/flexible_sign_in_epoch", true],
|
|
21
|
+
["durable-browser-sessions", "server/guards.ts/session.ts", "web_session", true],
|
|
22
|
+
["local-owner-and-memory", "local-owner.ts/server/guards.ts", "local_mode/in-memory nonces and links", false],
|
|
23
|
+
["password-and-saved-login", "scope.ts/login-secrets.ts", "approver/protected login files", false],
|
|
24
|
+
["sso-membership", "sso-settings.ts/store.ts", "sso_identity/protected sign-in settings", false],
|
|
25
|
+
["derived-chat-invites-push", "store.ts/chat-approval.ts", "paired chat/confirmations/invites/push", false],
|
|
26
|
+
["flexible-authority", "flexible-sign-in.ts", "flexible sign-ins/threads/protected secrets", false],
|
|
27
|
+
["runner-and-native-custody", "runner.ts/runner-process.ts", "claims/leases/attempts/protected process records", false],
|
|
28
|
+
["execution-and-publication", "approval-authority.ts/approval-policy.ts", "approvals/modes/releases/schedules/repair", false],
|
|
29
|
+
["public-hooks-and-triggers", "server/remote-hooks.ts/flow-triggers.ts", "intake/trigger/delivery standing", false],
|
|
30
|
+
["provider-and-outbound-oauth", "keys.ts/tool-secret-store.ts", "external secrets/tool and task references", false],
|
|
31
|
+
["central-device-and-transfer", "future central protocol", "enrollment/lease/transfer/settlement", false],
|
|
32
|
+
];
|
|
33
|
+
const stages = new WeakMap();
|
|
34
|
+
const stamp = (s) => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs, ctimeMs: s.ctimeMs });
|
|
35
|
+
const same = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
|
|
36
|
+
const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
37
|
+
function canonical(path, directory = false) {
|
|
38
|
+
if (typeof path !== "string" || resolve(path) !== path || fs.realpathSync(path) !== path)
|
|
39
|
+
throw Error("Stage path must be canonical and contain no symlink");
|
|
40
|
+
const s = fs.lstatSync(path);
|
|
41
|
+
if (s.isSymbolicLink() || (directory ? !s.isDirectory() : !s.isFile()))
|
|
42
|
+
throw Error("Stage path is not a plain file or directory");
|
|
43
|
+
return s;
|
|
44
|
+
}
|
|
45
|
+
function noSidecars(path) {
|
|
46
|
+
for (const suffix of ["-wal", "-shm", "-journal"]) {
|
|
47
|
+
try {
|
|
48
|
+
fs.lstatSync(path + suffix);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (error.code === "ENOENT")
|
|
52
|
+
continue;
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
throw Error("Cold backup has a journal or WAL sidecar");
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function regularBounded(fd) {
|
|
59
|
+
const info = fs.fstatSync(fd);
|
|
60
|
+
if (!info.isFile())
|
|
61
|
+
throw Error("Opened backup is not a regular file");
|
|
62
|
+
if (!Number.isSafeInteger(info.size) || info.size < 0 || info.size > MAX_STAGE_BYTES)
|
|
63
|
+
throw Error("Backup exceeds128MiB stage byte limit");
|
|
64
|
+
return info;
|
|
65
|
+
}
|
|
66
|
+
function readBounded(fd) {
|
|
67
|
+
const initial = regularBounded(fd);
|
|
68
|
+
const bytes = Buffer.allocUnsafe(initial.size);
|
|
69
|
+
let offset = 0;
|
|
70
|
+
while (offset < bytes.length) {
|
|
71
|
+
if (!same(stamp(initial), stamp(regularBounded(fd))))
|
|
72
|
+
throw Error("File changed while being read");
|
|
73
|
+
const size = fs.readSync(fd, bytes, offset, Math.min(64 * 1024, bytes.length - offset), offset);
|
|
74
|
+
if (size === 0)
|
|
75
|
+
throw Error("File changed while being read");
|
|
76
|
+
offset += size;
|
|
77
|
+
}
|
|
78
|
+
if (!same(stamp(initial), stamp(regularBounded(fd))))
|
|
79
|
+
throw Error("File changed while being read");
|
|
80
|
+
const extra = Buffer.allocUnsafe(1);
|
|
81
|
+
if (fs.readSync(fd, extra, 0, 1, offset) !== 0)
|
|
82
|
+
throw Error("File changed while being read");
|
|
83
|
+
if (!same(stamp(initial), stamp(regularBounded(fd))))
|
|
84
|
+
throw Error("File changed while being read");
|
|
85
|
+
return bytes;
|
|
86
|
+
}
|
|
87
|
+
function readStable(path) {
|
|
88
|
+
noSidecars(path);
|
|
89
|
+
const before = stamp(canonical(path));
|
|
90
|
+
const fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
91
|
+
try {
|
|
92
|
+
if (!same(before, stamp(regularBounded(fd))))
|
|
93
|
+
throw Error("File identity changed");
|
|
94
|
+
const bytes = readBounded(fd), hash = digest(bytes);
|
|
95
|
+
if (!same(before, stamp(regularBounded(fd))) || !same(before, stamp(canonical(path))))
|
|
96
|
+
throw Error("File changed while being read");
|
|
97
|
+
noSidecars(path);
|
|
98
|
+
return { mark: before, hash, header: Buffer.from(bytes.subarray(0, 100)) };
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
fs.closeSync(fd);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function schemaOf(path) {
|
|
105
|
+
const db = new DatabaseSync(path, { readOnly: true });
|
|
106
|
+
try {
|
|
107
|
+
if (db.prepare("PRAGMA quick_check").get()?.["quick_check"] !== "ok")
|
|
108
|
+
throw Error("Copied backup integrity check failed");
|
|
109
|
+
const rows = db.prepare("SELECT type,name,tbl_name,sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name").all();
|
|
110
|
+
const version = db.prepare("SELECT version FROM schema_version").all();
|
|
111
|
+
const schema = version.length === 1 && typeof version[0]?.["version"] === "number" ? version[0]["version"] : null;
|
|
112
|
+
return { schema, supported: schema === SUPPORTED_SCHEMA && rows.length === SCHEMA_OBJECT_COUNT && createHash("sha256").update(JSON.stringify(rows)).digest("hex") === SCHEMA_DIGEST };
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
db.close();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
export function copyCentralRecoveryStage(source, privateParent) {
|
|
119
|
+
const parent = canonical(privateParent, true);
|
|
120
|
+
if (parent.uid !== process.getuid?.() || (parent.mode & 0o077) !== 0)
|
|
121
|
+
throw Error("Stage parent must be owner-private");
|
|
122
|
+
const initial = readStable(source);
|
|
123
|
+
const header = initial.header;
|
|
124
|
+
if (header.toString("ascii", 0, 16) !== "SQLite format 3\0" || header[18] !== 1 || header[19] !== 1)
|
|
125
|
+
throw Error("Cold backup must be a standalone rollback-journal database, not WAL mode");
|
|
126
|
+
const directory = fs.mkdtempSync(join(privateParent, "central-recovery-"));
|
|
127
|
+
fs.chmodSync(directory, 0o700);
|
|
128
|
+
const copy = join(directory, "stage.db");
|
|
129
|
+
let stageStore;
|
|
130
|
+
try {
|
|
131
|
+
const fd = fs.openSync(source, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
132
|
+
try {
|
|
133
|
+
if (!same(initial.mark, stamp(regularBounded(fd))))
|
|
134
|
+
throw Error("Source changed before copy");
|
|
135
|
+
const bytes = readBounded(fd);
|
|
136
|
+
if (digest(bytes) !== initial.hash || !same(initial.mark, stamp(regularBounded(fd))))
|
|
137
|
+
throw Error("Source changed during copy");
|
|
138
|
+
const output = fs.openSync(copy, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | fs.constants.O_NOFOLLOW, 0o600);
|
|
139
|
+
try {
|
|
140
|
+
fs.writeFileSync(output, bytes);
|
|
141
|
+
fs.fsyncSync(output);
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
fs.closeSync(output);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
fs.closeSync(fd);
|
|
149
|
+
}
|
|
150
|
+
const after = readStable(source), copied = readStable(copy);
|
|
151
|
+
if (!same(initial.mark, after.mark) || initial.hash !== after.hash || copied.hash !== initial.hash
|
|
152
|
+
|| (copied.mark.dev === initial.mark.dev && copied.mark.ino === initial.mark.ino))
|
|
153
|
+
throw Error("Source/copy identity disagrees");
|
|
154
|
+
const shape = schemaOf(copy), validated = readStable(copy);
|
|
155
|
+
if (validated.hash !== copied.hash || !same(validated.mark, copied.mark))
|
|
156
|
+
throw Error("Stage changed during validation");
|
|
157
|
+
if (shape.supported) {
|
|
158
|
+
stageStore = openStore(copy);
|
|
159
|
+
const openedFile = canonical(copy);
|
|
160
|
+
if (stageStore.databaseFile() !== copy || openedFile.dev !== copied.mark.dev || openedFile.ino !== copied.mark.ino) {
|
|
161
|
+
throw Error("Retained stage database file changed after open");
|
|
162
|
+
}
|
|
163
|
+
const openedVersion = stageStore.handle.prepare("SELECT version FROM schema_version").all();
|
|
164
|
+
const openedRows = stageStore.handle.prepare("SELECT type,name,tbl_name,sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type,name").all();
|
|
165
|
+
if (openedVersion.length !== 1 || openedVersion[0]?.["version"] !== SUPPORTED_SCHEMA || openedRows.length !== SCHEMA_OBJECT_COUNT
|
|
166
|
+
|| createHash("sha256").update(JSON.stringify(openedRows)).digest("hex") !== SCHEMA_DIGEST)
|
|
167
|
+
throw Error("Retained stage schema changed after open");
|
|
168
|
+
stageStore.handle.exec("PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE");
|
|
169
|
+
}
|
|
170
|
+
const final = readStable(copy);
|
|
171
|
+
if (final.mark.dev !== copied.mark.dev || final.mark.ino !== copied.mark.ino)
|
|
172
|
+
throw Error("Copied stage identity replaced");
|
|
173
|
+
const handle = Object.freeze({ copyPath: copy });
|
|
174
|
+
stages.set(handle, { source, sourceStamp: initial.mark, sourceDigest: initial.hash, copy, copyStamp: final.mark, copyDigest: final.hash,
|
|
175
|
+
directory, directoryStamp: stamp(canonical(directory, true)), ...(stageStore === undefined ? {} : { store: stageStore }), ...shape });
|
|
176
|
+
return handle;
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
stageStore?.close();
|
|
180
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
function admitted(handle) {
|
|
185
|
+
const kept = typeof handle === "object" && handle !== null ? stages.get(handle) : undefined;
|
|
186
|
+
if (kept === undefined)
|
|
187
|
+
throw Error("Not an internally constructed recovery stage");
|
|
188
|
+
const dir = stamp(canonical(kept.directory, true));
|
|
189
|
+
if (dir.dev !== kept.directoryStamp.dev || dir.ino !== kept.directoryStamp.ino)
|
|
190
|
+
throw Error("Private stage directory replaced");
|
|
191
|
+
const source = readStable(kept.source), copy = readStable(kept.copy);
|
|
192
|
+
if (!same(source.mark, kept.sourceStamp) || source.hash !== kept.sourceDigest || !same(copy.mark, kept.copyStamp)
|
|
193
|
+
|| copy.hash !== kept.copyDigest || (copy.mark.dev === source.mark.dev && copy.mark.ino === source.mark.ino))
|
|
194
|
+
throw Error("Recovery stage/source changed");
|
|
195
|
+
return kept;
|
|
196
|
+
}
|
|
197
|
+
function report(kept, outcome, counts = new Map()) {
|
|
198
|
+
return { manifestVersion: 1, manifestDigest: createHash("sha256").update(JSON.stringify({ schema: SUPPORTED_SCHEMA, shape: SCHEMA_DIGEST, inventory: INVENTORY })).digest("hex"), schema: kept.schema, schemaSupported: kept.supported, complete: false, recoveryReady: false, outcome, repeated: false,
|
|
199
|
+
entries: INVENTORY.map(([id, owner, storage, implemented]) => ({ id, owner, storage,
|
|
200
|
+
status: outcome === "retired-partial" && implemented ? "retired" : "unsupported",
|
|
201
|
+
affected: outcome === "retired-partial" && implemented ? counts.get(id) ?? 0 : null,
|
|
202
|
+
remaining: outcome === "retired-partial" && implemented ? 0 : null })) };
|
|
203
|
+
}
|
|
204
|
+
const count = (store, sql) => Number(store.handle.prepare(sql).get()?.["n"]);
|
|
205
|
+
export function retireCentralRecoveryStage(handle) {
|
|
206
|
+
const kept = admitted(handle);
|
|
207
|
+
if (kept.report !== undefined)
|
|
208
|
+
return structuredClone({ ...kept.report, repeated: true });
|
|
209
|
+
if (!kept.supported)
|
|
210
|
+
return report(kept, "unsupported-schema");
|
|
211
|
+
let store, result;
|
|
212
|
+
try {
|
|
213
|
+
store = kept.store;
|
|
214
|
+
if (store === undefined)
|
|
215
|
+
throw Error("Stage is closed");
|
|
216
|
+
const stage = store, now = new Date(), by = "central-recovery-stage";
|
|
217
|
+
result = stage.transact(() => {
|
|
218
|
+
const counts = new Map();
|
|
219
|
+
counts.set("person-credentials", count(stage, "SELECT count(*) AS n FROM credential WHERE kind='person' AND revoked_at IS NULL"));
|
|
220
|
+
for (const token of stage.apiTokens(null))
|
|
221
|
+
if (token.revokedAt === null)
|
|
222
|
+
stage.revokeApiToken(token.id, by, now, "isolated recovery stage");
|
|
223
|
+
counts.set("lead-credentials", count(stage, "SELECT count(*) AS n FROM credential WHERE kind='lead' AND revoked_at IS NULL"));
|
|
224
|
+
for (const row of stage.handle.prepare("SELECT DISTINCT account FROM credential WHERE kind='lead' AND revoked_at IS NULL").all())
|
|
225
|
+
stage.revokeLeadCredentials(String(row["account"]), by, now);
|
|
226
|
+
counts.set("coordinator-credentials", count(stage, "SELECT count(*) AS n FROM credential WHERE kind='coordinator' AND revoked_at IS NULL"));
|
|
227
|
+
for (const row of stage.handle.prepare("SELECT id FROM credential WHERE kind='coordinator' AND revoked_at IS NULL").all()) {
|
|
228
|
+
if (!revokeCoordinator(stage, String(row["id"]), by, now).ok)
|
|
229
|
+
throw Error("Coordinator retirement failed");
|
|
230
|
+
}
|
|
231
|
+
for (const row of stage.handle.prepare("SELECT id FROM credential WHERE kind='coordinator'").all())
|
|
232
|
+
stage.sweepCoordinatorProposals(now, String(row["id"]));
|
|
233
|
+
counts.set("inbound-oauth", count(stage, "SELECT (SELECT count(*) FROM oauth_code)+(SELECT count(*) FROM oauth_grant)+(SELECT count(*) FROM oauth_refresh) AS n"));
|
|
234
|
+
stage.handle.exec("DELETE FROM oauth_code; DELETE FROM oauth_refresh; DELETE FROM oauth_grant");
|
|
235
|
+
counts.set("publication-grant-verifier", count(stage, "SELECT count(*) AS n FROM publication_grant WHERE revoked_at IS NULL"));
|
|
236
|
+
for (const row of stage.handle.prepare("SELECT DISTINCT repo FROM publication_grant WHERE revoked_at IS NULL").all()) {
|
|
237
|
+
if (!stage.revokePublicationGrant(String(row["repo"]), by, now))
|
|
238
|
+
throw Error("Publication grant retirement failed");
|
|
239
|
+
}
|
|
240
|
+
const releaseTasks = stage.handle.prepare("SELECT DISTINCT task_id FROM action_ledger WHERE task_id IS NOT NULL AND action IN (?, ?)").all(PUBLISH_HELD_ACTION, PUBLISH_ALLOWED_ACTION);
|
|
241
|
+
let held = 0;
|
|
242
|
+
for (const row of releaseTasks) {
|
|
243
|
+
const taskId = String(row["task_id"]);
|
|
244
|
+
if (autoPublishHeld(stage, taskId) === null) {
|
|
245
|
+
holdAutoPublish(stage, { taskId, now, why: "Restored publication permission is on hold. This does not establish whether earlier work ran or stopped." });
|
|
246
|
+
held += 1;
|
|
247
|
+
}
|
|
248
|
+
if (autoPublishHeld(stage, taskId) === null)
|
|
249
|
+
throw Error("Release publication hold failed");
|
|
250
|
+
}
|
|
251
|
+
counts.set("release-publish-ledger-hold", held);
|
|
252
|
+
const stillAllowed = stage.handle.prepare(`SELECT count(*) AS n FROM action_ledger a
|
|
253
|
+
JOIN (SELECT max(id) AS id FROM action_ledger WHERE task_id IS NOT NULL AND action IN (?, ?) GROUP BY task_id) latest ON latest.id = a.id
|
|
254
|
+
WHERE a.action = ?`).get(PUBLISH_HELD_ACTION, PUBLISH_ALLOWED_ACTION, PUBLISH_ALLOWED_ACTION);
|
|
255
|
+
if (Number(stillAllowed?.["n"]) !== 0)
|
|
256
|
+
throw Error("Restored release permission remains allowed");
|
|
257
|
+
counts.set("intake-grant-fresh-command-admission", count(stage, "SELECT count(*) AS n FROM intake_grant WHERE revoked_at IS NULL"));
|
|
258
|
+
for (const row of stage.handle.prepare("SELECT DISTINCT repo FROM intake_grant WHERE revoked_at IS NULL").all()) {
|
|
259
|
+
if (!stage.clearIntakeGrant(String(row["repo"]), by, now))
|
|
260
|
+
throw Error("Intake grant retirement failed");
|
|
261
|
+
}
|
|
262
|
+
const people = stage.handle.prepare(`SELECT person FROM flexible_sign_in UNION SELECT person FROM flexible_sign_in_epoch
|
|
263
|
+
UNION SELECT created_by AS person FROM flexible_thread UNION SELECT owner AS person FROM thread_turn
|
|
264
|
+
UNION SELECT owner AS person FROM flexible_interactive_session
|
|
265
|
+
UNION SELECT sign_in_person AS person FROM thread_relay_call WHERE sign_in_person IS NOT NULL
|
|
266
|
+
UNION SELECT sign_in_person AS person FROM thread_relay_pending WHERE sign_in_person IS NOT NULL`).all();
|
|
267
|
+
const epochs = new Map();
|
|
268
|
+
for (const row of people) {
|
|
269
|
+
const person = row["person"];
|
|
270
|
+
if (typeof person !== "string" || person.length < 1 || person.length > 200)
|
|
271
|
+
throw Error("Unknown snapshot sign-in identity");
|
|
272
|
+
const old = stage.handle.prepare("SELECT epoch FROM flexible_sign_in_epoch WHERE person = ?").get(person)?.["epoch"] ?? 0;
|
|
273
|
+
if (typeof old !== "number" || !Number.isSafeInteger(old) || old < 0 || old >= Number.MAX_SAFE_INTEGER)
|
|
274
|
+
throw Error("Unsafe snapshot epoch");
|
|
275
|
+
epochs.set(person, old);
|
|
276
|
+
}
|
|
277
|
+
const captured = stage.handle.prepare(`SELECT owner AS person, sign_in_epoch AS epoch FROM flexible_interactive_session
|
|
278
|
+
UNION ALL SELECT sign_in_person AS person, sign_in_epoch AS epoch FROM thread_relay_call WHERE sign_in_epoch IS NOT NULL
|
|
279
|
+
UNION ALL SELECT sign_in_person AS person, sign_in_epoch AS epoch FROM thread_relay_pending WHERE sign_in_epoch IS NOT NULL`).all();
|
|
280
|
+
for (const row of captured) {
|
|
281
|
+
const person = row["person"], epoch = row["epoch"];
|
|
282
|
+
if (typeof person !== "string" || !epochs.has(person) || typeof epoch !== "number" || !Number.isSafeInteger(epoch) || epoch < 0 || epoch > epochs.get(person))
|
|
283
|
+
throw Error("Snapshot captured epoch disagrees");
|
|
284
|
+
}
|
|
285
|
+
counts.set("flexible-snapshot-sign-in-admission", count(stage, "SELECT count(*) AS n FROM flexible_sign_in WHERE state IN ('active','staged')"));
|
|
286
|
+
stage.handle.prepare("UPDATE flexible_sign_in SET state='retiring', save_op=NULL, retire_after=NULL, retired_at=? WHERE state IN ('active','staged')").run(now.toISOString());
|
|
287
|
+
for (const [person, old] of epochs) {
|
|
288
|
+
stage.handle.prepare("INSERT INTO flexible_sign_in_epoch (person,epoch) VALUES (?,?) ON CONFLICT(person) DO UPDATE SET epoch=excluded.epoch").run(person, old + 1);
|
|
289
|
+
if (stage.handle.prepare("SELECT epoch FROM flexible_sign_in_epoch WHERE person=?").get(person)?.["epoch"] !== old + 1)
|
|
290
|
+
throw Error("Snapshot epoch fence failed");
|
|
291
|
+
}
|
|
292
|
+
if (count(stage, "SELECT count(*) AS n FROM flexible_sign_in WHERE state IN ('active','staged')") !== 0)
|
|
293
|
+
throw Error("Snapshot sign-in admission remains live");
|
|
294
|
+
const sessions = stage.webSessions(null);
|
|
295
|
+
counts.set("durable-browser-sessions", sessions.length);
|
|
296
|
+
for (const session of sessions)
|
|
297
|
+
stage.dropWebSession(session.idHash);
|
|
298
|
+
if (count(stage, "SELECT count(*) AS n FROM intake_grant WHERE revoked_at IS NULL") !== 0
|
|
299
|
+
|| count(stage, "SELECT count(*) AS n FROM publication_grant WHERE revoked_at IS NULL") !== 0
|
|
300
|
+
|| count(stage, "SELECT count(*) AS n FROM coordinator_proposal WHERE state IN ('pending','confirming')") !== 0
|
|
301
|
+
|| count(stage, "SELECT count(*) AS n FROM credential WHERE revoked_at IS NULL") !== 0
|
|
302
|
+
|| count(stage, "SELECT (SELECT count(*) FROM oauth_code)+(SELECT count(*) FROM oauth_grant)+(SELECT count(*) FROM oauth_refresh)+(SELECT count(*) FROM web_session) AS n") !== 0)
|
|
303
|
+
throw Error("Retirement postcondition failed");
|
|
304
|
+
return report(kept, "retired-partial", counts);
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
result = report(kept, "failed");
|
|
309
|
+
}
|
|
310
|
+
finally {
|
|
311
|
+
store?.close();
|
|
312
|
+
delete kept.store;
|
|
313
|
+
}
|
|
314
|
+
const copy = readStable(kept.copy);
|
|
315
|
+
if (copy.mark.dev !== kept.copyStamp.dev || copy.mark.ino !== kept.copyStamp.ino)
|
|
316
|
+
throw Error("Retired stage identity replaced");
|
|
317
|
+
kept.copyStamp = copy.mark;
|
|
318
|
+
kept.copyDigest = copy.hash;
|
|
319
|
+
admitted(handle);
|
|
320
|
+
kept.report = structuredClone(result);
|
|
321
|
+
return result;
|
|
322
|
+
}
|
|
323
|
+
export function closeCentralRecoveryStage(handle) {
|
|
324
|
+
const kept = stages.get(handle);
|
|
325
|
+
if (kept === undefined)
|
|
326
|
+
throw Error("Not an internally constructed recovery stage");
|
|
327
|
+
kept.store?.close();
|
|
328
|
+
delete kept.store;
|
|
329
|
+
}
|