@rightkit/release 0.6.52 → 0.6.54
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/README.md +1 -1
- package/adapter-env.mjs +16 -105
- package/admission-host.mjs +14 -1
- package/bin/darwin/rightkit-swap +0 -0
- package/bin/rightkit-gate.mjs +585 -404
- package/broker-admission.mjs +122 -2
- package/build-launch.mjs +52 -58
- package/build-release.mjs +2 -2
- package/cargo-ledger.mjs +24 -5
- package/cargo-target-shim.mjs +54 -23
- package/cargo-target.mjs +2 -2
- package/carried-adapter-run.mjs +7 -8
- package/carried-cargo-run.mjs +1 -1
- package/ci-compile-admission.mjs +1 -1
- package/clippy-route.mjs +65 -18
- package/compile-inputs.mjs +91 -15
- package/cross-targets.mjs +5 -3
- package/deps-cargo-lock.mjs +1 -1
- package/deterministic-scans.mjs +789 -259
- package/development.mjs +33 -7
- package/direct-receipt.mjs +3 -5
- package/feature-coverage.mjs +45 -9
- package/feature-partition.mjs +204 -0
- package/feature-sets.mjs +113 -0
- package/gate-acceptance.mjs +187 -115
- package/gate-seam.mjs +352 -0
- package/gate-serve.mjs +34 -2
- package/gate-stages.mjs +6 -2
- package/ghsa-audit.mjs +19 -4
- package/heavy-command.mjs +5 -4
- package/install-tauri-authenticode.mjs +73 -4
- package/ios-dev.mjs +3 -3
- package/ios-package-recipe.mjs +6 -6
- package/linux-setup.mjs +3 -2
- package/local-publish.mjs +113 -17
- package/lock-identity.mjs +24 -100
- package/managed-cargo.mjs +3 -3
- package/managed-root-guard.mjs +2 -2
- package/managed-roots.mjs +3 -3
- package/native-adapters.mjs +41 -244
- package/native-helpers.mjs +1 -1
- package/pack-digest.mjs +1 -1
- package/package-recipe-targets.mjs +3 -3
- package/package.json +2 -2
- package/publication-gate.mjs +29 -6
- package/publish-cargo.mjs +4 -5
- package/publish-local-cargo.mjs +77 -1
- package/qualification-verify.mjs +76 -49
- package/receipt-signature.mjs +104 -0
- package/release-switch-registry.json +4 -0
- package/release-switch-scan.mjs +13 -10
- package/rightkit-versions.json +126 -113
- package/scan-digest.mjs +43 -14
- package/seam-broker.mjs +168 -0
- package/snapshot-check.mjs +4 -1
- package/snapshot-dependency-reuse.mjs +1 -1
- package/snapshot-metadata.mjs +24 -35
- package/snapshot.mjs +328 -49
- package/stage-commands.mjs +59 -5
- package/stage-ledger.mjs +2 -2
- package/{carried-cargo.mjs → stage-seam.mjs} +118 -70
- package/stage-sidecar.mjs +3 -3
- package/tauri-bundle-marker.mjs +5 -2
- package/tauri-locked.mjs +1 -1
- package/tool-build.mjs +8 -6
- package/unit-gate.mjs +40 -10
- package/broker-handshake.mjs +0 -160
- package/broker-wire.mjs +0 -278
- package/build-ownership.mjs +0 -1578
- package/cargo-shapes.mjs +0 -332
- package/cargo-width.mjs +0 -49
- package/carrier-census.mjs +0 -124
- package/clippy-equivalence.mjs +0 -202
- package/freshness-census.mjs +0 -405
- package/handle-revocation.mjs +0 -100
- package/handle-revocation.rust-vector.json +0 -1
- package/handle-revocation.vectors.json +0 -53
- package/legion-freeze-consumer.mjs +0 -241
- package/linux-qualifier.mjs +0 -83
- package/native-tool-planning.mjs +0 -94
- package/owner-process-proof.mjs +0 -14
- package/ownership-mark.mjs +0 -191
- package/ownership-recover.mjs +0 -78
- package/pnpm-adapter-grammar.mjs +0 -226
- package/provenance-verify.mjs +0 -413
- package/snapshot-broker.mjs +0 -808
- package/snapshot-request.mjs +0 -722
- package/unit-list-compile.mjs +0 -356
package/gate-seam.mjs
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
// The gate's half of the one gate-broker seam (reset plan docs/plans/2026-11-07-gate-broker-reset.md section 3; rightkit#1536, rustright#235).
|
|
2
|
+
//
|
|
3
|
+
// The gate writes a Class A verdict for the workspace, takes the snapshot lock for the commit, spawns `rustright cargo <argv>` (or
|
|
4
|
+
// `rustright run <adapter-id> -- <argv>`) in the snapshot with RUSTRIGHT_GATE_COMMIT and RUSTRIGHT_CLASS_A set, parses exactly one
|
|
5
|
+
// `rustright-result <json>` line from the child's stderr, and reads the durable receipt that line names. No carrier file, no nonce,
|
|
6
|
+
// no grant, no lease handle, no signature verified here (CI's publication admission verifies the broker's signature).
|
|
7
|
+
//
|
|
8
|
+
// Dependency-free (node built-ins only). Every function here is pure or takes its I/O as an argument, so the writer, parser and judge
|
|
9
|
+
// are tested without a broker; the integration against the installed broker runs after the cutover (plan section 7, step 4).
|
|
10
|
+
import { execFileSync as nodeExecFileSync } from "node:child_process";
|
|
11
|
+
import crypto from "node:crypto";
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
|
|
15
|
+
export const CLASS_A_VERDICT_SCHEMA = "rightkit.class-a-verdict/1";
|
|
16
|
+
export const GATE_COMMIT_ENV = "RUSTRIGHT_GATE_COMMIT";
|
|
17
|
+
export const CLASS_A_ENV = "RUSTRIGHT_CLASS_A";
|
|
18
|
+
export const RESULT_LINE_PREFIX = "rustright-result ";
|
|
19
|
+
/** The exit the client reports when nothing was executed (a refusal, a client failure); an executed command keeps its own exit. */
|
|
20
|
+
export const NOT_EXECUTED_EXIT = 125;
|
|
21
|
+
|
|
22
|
+
const SHA1 = /^[0-9a-f]{40}$/;
|
|
23
|
+
const SAFE_WORKSPACE = /^(?:\.|[A-Za-z0-9_@+.-]+(?:\/[A-Za-z0-9_@+.-]+)*)$/;
|
|
24
|
+
|
|
25
|
+
export class SeamError extends Error {
|
|
26
|
+
constructor(code, message) { super(message); this.code = code; }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The snapshot-relative workspace path the verdict and the request bind to: `"."` for the root, forward slashes, no `..`. */
|
|
30
|
+
export function normalizeWorkspace(cwd) {
|
|
31
|
+
const n = path.posix.normalize(String(cwd ?? ".").split(path.sep).join("/")).replace(/\/+$/, "");
|
|
32
|
+
const out = n === "" || n === "." ? "." : n.replace(/^\.\//, "");
|
|
33
|
+
if (!SAFE_WORKSPACE.test(out) || out.split("/").includes("..")) throw new SeamError("WORKSPACE", `${JSON.stringify(cwd)} is not a snapshot-relative workspace path`);
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The Class A verdict for one workspace at one commit, or a SeamError. `scans` is every planned Class A row of the run with its status;
|
|
39
|
+
* the verdict exists only when all of them passed (a cache hit is a pass), so an incomplete or red plan can never publish one.
|
|
40
|
+
*/
|
|
41
|
+
/** The scope a class A run covered: "full" (no --scope) or the sorted, normalized scope directories. */
|
|
42
|
+
export function normalizeScope(scope) {
|
|
43
|
+
if (scope === null || scope === undefined || scope === "full") return "full";
|
|
44
|
+
if (!Array.isArray(scope) || !scope.length) throw new SeamError("VERDICT", `scope ${JSON.stringify(scope)} is neither "full" nor a list of directories`);
|
|
45
|
+
return [...new Set(scope.map((d) => normalizeWorkspace(d)))].sort();
|
|
46
|
+
}
|
|
47
|
+
const scopeTag = (scope) => (scope === "full" ? "full" : `s${crypto.createHash("sha256").update(scope.join("\0")).digest("hex").slice(0, 12)}`);
|
|
48
|
+
/** The verdict's file name: commit, the scope it covers and the workspace it binds. A scoped verdict can never be read under another scope's name. */
|
|
49
|
+
export function verdictFileName({ commit, scope, workspace }) {
|
|
50
|
+
const ws = normalizeWorkspace(workspace);
|
|
51
|
+
return `class-a-${String(commit).slice(0, 12)}-${scopeTag(normalizeScope(scope))}-${ws === "." ? "root" : crypto.createHash("sha256").update(ws).digest("hex").slice(0, 12)}.json`;
|
|
52
|
+
}
|
|
53
|
+
const sameScope = (a, b) => (a === "full" || b === "full" ? a === b : a.length === b.length && a.every((d, i) => d === b[i]));
|
|
54
|
+
|
|
55
|
+
export function classAVerdict({ commit, tree, repoKey, workspace, scans, scope = "full" }) {
|
|
56
|
+
if (!SHA1.test(String(commit ?? ""))) throw new SeamError("VERDICT", `commit ${JSON.stringify(commit)} is not a full sha`);
|
|
57
|
+
if (!SHA1.test(String(tree ?? ""))) throw new SeamError("VERDICT", `tree ${JSON.stringify(tree)} is not a full tree id`);
|
|
58
|
+
if (typeof repoKey !== "string" || !/^[A-Za-z0-9_-]{8,}$/.test(repoKey)) throw new SeamError("VERDICT", `repoKey ${JSON.stringify(repoKey)} is not a repository key`);
|
|
59
|
+
const ws = normalizeWorkspace(workspace);
|
|
60
|
+
if (!Array.isArray(scans) || !scans.length) throw new SeamError("VERDICT", "a Class A verdict needs at least one scan; an empty plan proves nothing");
|
|
61
|
+
const ids = new Set();
|
|
62
|
+
const rows = scans.map((s) => {
|
|
63
|
+
if (!s || typeof s.id !== "string" || !s.id) throw new SeamError("VERDICT", "a Class A scan without an id cannot be recorded");
|
|
64
|
+
if (ids.has(s.id)) throw new SeamError("VERDICT", `Class A scan id ${s.id} appears twice`);
|
|
65
|
+
ids.add(s.id);
|
|
66
|
+
if (s.status !== "pass") throw new SeamError("CLASS_A_RED", `Class A is not complete and green: ${s.id} is ${s.status ?? "unknown"}; no verdict is written`);
|
|
67
|
+
return { id: s.id, status: "pass" };
|
|
68
|
+
});
|
|
69
|
+
// `scope` records what the class A run covered; the broker reads its bound fields only and ignores this one, the gate reads it (verdictForRun).
|
|
70
|
+
return { schema: CLASS_A_VERDICT_SCHEMA, commit, tree, repoKey, workspace: ws, scope: normalizeScope(scope), status: "pass", scans: rows };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Writes a verdict atomically (temp file, rename) with mode 0600 and returns its absolute path. Refuses a relative directory. */
|
|
74
|
+
export function writeClassAVerdict(dir, verdict, { fsApi = fs } = {}) {
|
|
75
|
+
if (!path.isAbsolute(dir)) throw new SeamError("VERDICT", `verdict directory ${dir} must be absolute`);
|
|
76
|
+
if (verdict?.schema !== CLASS_A_VERDICT_SCHEMA || verdict.status !== "pass") throw new SeamError("VERDICT", "only a passing verdict of the current schema is written");
|
|
77
|
+
fsApi.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
78
|
+
const file = path.join(dir, verdictFileName({ commit: verdict.commit, scope: verdict.scope ?? "full", workspace: verdict.workspace }));
|
|
79
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
|
|
80
|
+
fsApi.writeFileSync(tmp, `${JSON.stringify(verdict)}\n`, { mode: 0o600 });
|
|
81
|
+
fsApi.renameSync(tmp, file);
|
|
82
|
+
return file;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The verdict a class B row of `workspace` names, for one run (`seam`: { commit, tree, repoKey, verdictDir, scope }). When this run ran class A itself
|
|
87
|
+
* (`classARows`: every class A row of the run with its status), the verdict is written from those rows for this run's scope; an incomplete or red set
|
|
88
|
+
* throws (classAVerdict). When it did not (a class-B-only run after the door's class A), the verdict of the SAME scope is read, or a full one (a full
|
|
89
|
+
* class A covers any scope), and checked against commit, tree, repository and status; a nested workspace's verdict is derived from it with the same
|
|
90
|
+
* scope. A verdict of another scope is never read: its file name carries its scope. Returns the absolute path; throws SeamError otherwise.
|
|
91
|
+
*/
|
|
92
|
+
export function verdictForRun({ seam, workspace, classARows = null, fsApi = fs }) {
|
|
93
|
+
const ws = normalizeWorkspace(workspace);
|
|
94
|
+
const scope = normalizeScope(seam.scope);
|
|
95
|
+
if (Array.isArray(classARows)) return writeClassAVerdict(seam.verdictDir, classAVerdict({ commit: seam.commit, tree: seam.tree, repoKey: seam.repoKey, workspace: ws, scans: classARows, scope }), { fsApi });
|
|
96
|
+
// A verdict covers this run when it is full, or when its scope contains every directory of this run's scope (a unit-list class A over many directories
|
|
97
|
+
// covers the compile of any one of them; its closure contains theirs). Exact first, then the smallest covering set, then full; any other is never read.
|
|
98
|
+
const prefix = `class-a-${String(seam.commit).slice(0, 12)}-`;
|
|
99
|
+
let names = [];
|
|
100
|
+
try { names = fsApi.readdirSync(seam.verdictDir).filter((n) => n.startsWith(prefix) && n.endsWith("-root.json") && n.length > prefix.length + "-root.json".length); } catch { names = []; }
|
|
101
|
+
const covering = [];
|
|
102
|
+
for (const name of names) {
|
|
103
|
+
const file = path.join(seam.verdictDir, name);
|
|
104
|
+
let v; try { v = JSON.parse(fsApi.readFileSync(file, "utf8")); } catch { continue; }
|
|
105
|
+
if (v?.schema !== CLASS_A_VERDICT_SCHEMA || v.commit !== seam.commit || v.tree !== seam.tree || v.repoKey !== seam.repoKey || v.status !== "pass" || v.workspace !== "." || !Array.isArray(v.scans) || !v.scans.length) continue;
|
|
106
|
+
let vScope; try { vScope = normalizeScope(v.scope ?? null); } catch { continue; }
|
|
107
|
+
if (name !== verdictFileName({ commit: seam.commit, scope: vScope, workspace: "." })) continue; // a file whose name and recorded scope disagree is not read
|
|
108
|
+
const covers = vScope === "full" || (scope !== "full" && scope.every((d) => vScope.includes(d)));
|
|
109
|
+
if (covers) covering.push({ file, v, vScope, rank: vScope === "full" ? Number.MAX_SAFE_INTEGER : sameScope(vScope, scope) ? 0 : vScope.length });
|
|
110
|
+
}
|
|
111
|
+
covering.sort((a, b) => a.rank - b.rank || (a.file < b.file ? -1 : 1));
|
|
112
|
+
const best = covering[0];
|
|
113
|
+
if (!best) throw new SeamError("VERDICT", `no Class A verdict covering this run's scope (${scope === "full" ? "full" : scope.join(", ")}) for ${String(seam.commit).slice(0, 12)} in ${seam.verdictDir}; class A must run on this snapshot first`);
|
|
114
|
+
if (ws === ".") return best.file;
|
|
115
|
+
return writeClassAVerdict(seam.verdictDir, classAVerdict({ commit: seam.commit, tree: seam.tree, repoKey: seam.repoKey, workspace: ws, scans: best.v.scans, scope: best.vScope }), { fsApi });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The two variables that carry the seam; nothing else is added to the child's environment by the seam. */
|
|
119
|
+
export function seamEnv({ commit, classA }) {
|
|
120
|
+
if (!SHA1.test(String(commit ?? ""))) throw new SeamError("SEAM", `commit ${JSON.stringify(commit)} is not a full sha`);
|
|
121
|
+
if (typeof classA !== "string" || !path.isAbsolute(classA)) throw new SeamError("SEAM", `the Class A verdict path must be absolute (${JSON.stringify(classA)})`);
|
|
122
|
+
return { [GATE_COMMIT_ENV]: commit, [CLASS_A_ENV]: classA };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const nullableString = (v) => v === null || typeof v === "string";
|
|
126
|
+
|
|
127
|
+
/** Whether two absolute paths name the same file: Windows' extended `\\?\` prefix dropped, separators and case normalized there, resolved everywhere. */
|
|
128
|
+
export function samePath(a, b, platform = process.platform) {
|
|
129
|
+
if (typeof a !== "string" || typeof b !== "string") return false;
|
|
130
|
+
const norm = (p) => {
|
|
131
|
+
let s = p.replace(/^\\\\\?\\UNC\\/i, "\\\\").replace(/^\\\\\?\\/, "");
|
|
132
|
+
if (platform === "win32") { s = path.win32.resolve(s).replace(/\//g, "\\").toLowerCase(); return s; }
|
|
133
|
+
return path.posix.normalize(s);
|
|
134
|
+
};
|
|
135
|
+
return norm(a) === norm(b);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Exactly one `rustright-result <json>` line in the child's stderr: the result. None (the child was killed before it replied, or an
|
|
140
|
+
* old client ran) or several is a failure of the row, never a success and never a retry.
|
|
141
|
+
*/
|
|
142
|
+
export function parseResultLine(stderr) {
|
|
143
|
+
const lines = String(stderr ?? "").split(/\r?\n/).filter((l) => l.startsWith(RESULT_LINE_PREFIX));
|
|
144
|
+
if (lines.length === 0) throw new SeamError("NO_RESULT_LINE", "the client printed no rustright-result line (killed before it replied, or not the seam client); the row fails");
|
|
145
|
+
if (lines.length > 1) throw new SeamError("AMBIGUOUS_RESULT_LINE", `the client printed ${lines.length} rustright-result lines; one outcome per request`);
|
|
146
|
+
let r;
|
|
147
|
+
try { r = JSON.parse(lines[0].slice(RESULT_LINE_PREFIX.length)); } catch (e) { throw new SeamError("BAD_RESULT_LINE", `the rustright-result line is not JSON: ${e.message}`); }
|
|
148
|
+
if (!r || typeof r !== "object" || Array.isArray(r)) throw new SeamError("BAD_RESULT_LINE", "the rustright-result line is not an object");
|
|
149
|
+
const bad = [];
|
|
150
|
+
if (!nullableString(r.requestId)) bad.push("requestId");
|
|
151
|
+
if (!(r.exit === null || Number.isInteger(r.exit))) bad.push("exit");
|
|
152
|
+
if (!(r.signal === null || typeof r.signal === "string" || Number.isInteger(r.signal))) bad.push("signal"); // the broker writes the signal number, node the name
|
|
153
|
+
if (!nullableString(r.outputDir) || (typeof r.outputDir === "string" && !path.isAbsolute(r.outputDir))) bad.push("outputDir");
|
|
154
|
+
if (!nullableString(r.receipt) || (typeof r.receipt === "string" && !path.isAbsolute(r.receipt))) bad.push("receipt");
|
|
155
|
+
if (typeof r.receiptPersisted !== "boolean") bad.push("receiptPersisted");
|
|
156
|
+
if (r.code !== undefined && (typeof r.code !== "string" || !/^[A-Z]{2,3}_[A-Z0-9_]+$/.test(r.code))) bad.push("code"); // RK_ today; any short upper-case prefix the broker documents
|
|
157
|
+
if (r.message !== undefined && typeof r.message !== "string") bad.push("message");
|
|
158
|
+
if (bad.length) throw new SeamError("BAD_RESULT_LINE", `the rustright-result line has invalid field(s): ${bad.join(", ")}`);
|
|
159
|
+
return r;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The receipt the result line names, read directly, with its postconditions judged against this request: `gate.commit`, `gate.tree`
|
|
164
|
+
* and `gate.classA` must be this run's, `gate.snapshotUnchanged` must be true. Returns { receipt, sha256, problems }.
|
|
165
|
+
*/
|
|
166
|
+
export function readSeamReceipt(file, { commit, tree, classA = null, expect = null, requestId = null, fsApi = fs } = {}) {
|
|
167
|
+
let text;
|
|
168
|
+
try { text = fsApi.readFileSync(file, "utf8"); } catch (e) { return { receipt: null, sha256: null, problems: [`receipt ${file} cannot be read (${e.code ?? e.message})`] }; }
|
|
169
|
+
let receipt;
|
|
170
|
+
try { receipt = JSON.parse(text); } catch (e) { return { receipt: null, sha256: null, problems: [`receipt ${file} is not JSON (${e.message})`] }; }
|
|
171
|
+
const problems = [];
|
|
172
|
+
const g = receipt?.gate;
|
|
173
|
+
if (!g || typeof g !== "object") problems.push("receipt has no gate object");
|
|
174
|
+
else {
|
|
175
|
+
if (g.commit !== commit) problems.push(`receipt gate.commit ${JSON.stringify(g.commit)} is not this run's ${commit}`);
|
|
176
|
+
// `tree: null` means the caller does not know the tree (a stage child that has only the commit): the commit binding stands, the tree is not compared.
|
|
177
|
+
if (tree !== null && g.tree !== tree) problems.push(`receipt gate.tree ${JSON.stringify(g.tree)} is not this run's ${tree}`);
|
|
178
|
+
if (classA !== null && !samePath(g.classA, classA)) problems.push(`receipt gate.classA ${JSON.stringify(g.classA)} is not the verdict this request named`);
|
|
179
|
+
if (g.snapshotUnchanged !== true) problems.push("the broker found the snapshot changed during the job (gate.snapshotUnchanged is not true)");
|
|
180
|
+
}
|
|
181
|
+
if (receipt && Object.hasOwn(receipt, "testExecutables") && receipt.testExecutables !== null && !Array.isArray(receipt.testExecutables)) problems.push("receipt testExecutables is neither a list nor null");
|
|
182
|
+
// The request the broker admitted, from the fields its producer already writes (provenance.payload: jobId and request.{requestedArgv, workspace, adapter}; no second copy
|
|
183
|
+
// is invented): compared with what this invocation sent, without verifying the signature (CI authenticates the same fields). A receipt that names no request, or another
|
|
184
|
+
// command, directory, adapter or job, is not this row's.
|
|
185
|
+
if (expect) {
|
|
186
|
+
const payload = receipt?.provenance?.payload; const req = payload?.request;
|
|
187
|
+
if (!req || typeof req !== "object") problems.push("receipt names no admitted request (provenance.payload.request), so it cannot be tied to this row");
|
|
188
|
+
else {
|
|
189
|
+
if (JSON.stringify(req.requestedArgv) !== JSON.stringify(expect.argv)) problems.push(`receipt requestedArgv ${JSON.stringify(req.requestedArgv)} is not the argv this row sent ${JSON.stringify(expect.argv)}`);
|
|
190
|
+
if (!samePath(req.workspace, expect.cwd)) problems.push(`receipt workspace ${JSON.stringify(req.workspace)} is not the directory this row ran in ${JSON.stringify(expect.cwd)}`);
|
|
191
|
+
if ((expect.adapter ?? null) !== (req.adapter ?? null)) problems.push(`receipt adapter ${JSON.stringify(req.adapter ?? null)} is not this row's ${JSON.stringify(expect.adapter ?? null)}`);
|
|
192
|
+
}
|
|
193
|
+
if (requestId !== null && payload?.jobId !== requestId) problems.push(`receipt jobId ${JSON.stringify(payload?.jobId)} is not the request id ${JSON.stringify(requestId)} the client reported`);
|
|
194
|
+
}
|
|
195
|
+
return { receipt, sha256: crypto.createHash("sha256").update(text).digest("hex"), problems };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* One verdict for the row from the child's exit, its result line and its receipt. Order: a refusal or client failure (code present, or
|
|
200
|
+
* exit 125 with nothing admitted) fails with that code; a success without a durable receipt fails; the receipt's postconditions are read
|
|
201
|
+
* next and fail the row even when the command exited 0 (a postcondition failure also makes the client exit 125 while `result.exit` keeps
|
|
202
|
+
* the executed command's exit, so this comes before the exit comparison); then a client exit that disagrees with its line; then an
|
|
203
|
+
* executed command that failed keeps its exit as code EXIT; otherwise pass, with the evidence downstream reads (outputDir,
|
|
204
|
+
* testExecutables, receipt digest).
|
|
205
|
+
*/
|
|
206
|
+
export function judgeSeamOutcome({ child, stderr, commit, tree, classA = null, expect = null, fsApi = fs }) {
|
|
207
|
+
let result;
|
|
208
|
+
try { result = parseResultLine(stderr); } catch (e) { return { status: "fail", code: e.code, detail: e.message, result: null, evidence: null }; }
|
|
209
|
+
if (result.code) return { status: "fail", code: result.code, detail: result.requestId === null ? `the broker refused or the client failed before anything was admitted: ${result.message ?? result.code}` : `the client failed after request ${result.requestId} was admitted (${result.message ?? result.code}); the job's state in the broker is unknown`, result, evidence: null };
|
|
210
|
+
if (result.exit === NOT_EXECUTED_EXIT && result.requestId === null) return { status: "fail", code: "RK_NOT_EXECUTED", detail: "the client reported exit 125 with no request admitted and no code", result, evidence: null };
|
|
211
|
+
// A client the gate killed (its own timeout, a cancel) proves nothing whatever its line says: the line may predate the kill or belong to a job the broker went on to cancel.
|
|
212
|
+
if (child && typeof child.signal === "string" && child.signal) return { status: "fail", code: "CLIENT_KILLED", detail: `the client was stopped by ${child.signal} before the row completed`, result, evidence: null };
|
|
213
|
+
if (!result.receiptPersisted || typeof result.receipt !== "string") return { status: "fail", code: "RECEIPT_MISSING", detail: "the broker left no durable receipt for this request; without it the row proves nothing", result, evidence: null };
|
|
214
|
+
const read = readSeamReceipt(result.receipt, { commit, tree, classA, expect, requestId: result.requestId, fsApi });
|
|
215
|
+
// `receiptRead`: the receipt is the terminal record of THIS request's job (receiptIsTerminalFor): then the job is over even when its postconditions fail (the evidence
|
|
216
|
+
// is withheld, the row is settled). A receipt that merely parses, or names another job, proves nothing about the job this client submitted.
|
|
217
|
+
const receiptRead = receiptIsTerminalFor(read.receipt, result.requestId) && receiptProvesTreeGone(read.receipt);
|
|
218
|
+
if (read.problems.length) return { status: "fail", code: read.receipt?.gate && read.receipt.gate.snapshotUnchanged === false ? "RK_SNAPSHOT_CHANGED" : "RECEIPT_MISMATCH", detail: read.problems.join("; "), result, evidence: null, receiptRead };
|
|
219
|
+
const evidence = { receiptSha256: read.sha256, receiptPath: result.receipt, requestId: result.requestId, outputDir: result.outputDir, targetTriple: typeof read.receipt.targetTriple === "string" && read.receipt.targetTriple ? read.receipt.targetTriple : null, testExecutables: Array.isArray(read.receipt.testExecutables) ? read.receipt.testExecutables : null, testExecutablesReason: typeof read.receipt.testExecutablesReason === "string" ? read.receipt.testExecutablesReason : null, receiptStatus: typeof read.receipt.status === "string" ? read.receipt.status : null, gate: read.receipt.gate };
|
|
220
|
+
if (child && Number.isInteger(child.status) && result.exit !== null && child.status !== result.exit) return { status: "fail", code: "RESULT_EXIT_MISMATCH", detail: `the client exited ${child.status} but its result line says ${result.exit}`, result, evidence, receiptRead };
|
|
221
|
+
if (result.exit !== 0 || result.signal) return { status: "fail", code: "EXIT", detail: result.signal ? `the command was stopped by signal ${result.signal}` : `exit ${result.exit}`, result, evidence, receiptRead };
|
|
222
|
+
// An exit 0 is a pass only for a job the broker finished as SUCCEEDED: a job cancelled or timed out after its process exited 0 keeps that observed exit in its receipt
|
|
223
|
+
// (rustright finish_impl.rs: executed commands keep their actual exit), and its result line says exit 0, but the broker stopped it. Every receipt names its status.
|
|
224
|
+
if (read.receipt.status !== "SUCCEEDED") return { status: "fail", code: "RECEIPT_NOT_SUCCEEDED", detail: `the command exited 0 but the broker finished the job ${JSON.stringify(read.receipt.status ?? null)}, not SUCCEEDED`, result, evidence, receiptRead };
|
|
225
|
+
return { status: "pass", code: null, detail: null, result, evidence, receiptRead };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The process-birth identity the broker compares a lock holder with (`rustright-process` identity.rs node_identity_token), spelled the
|
|
230
|
+
* same: `darwin:<pid>:<ps lstart>` (LC_ALL=C LANG=C, trimmed), `linux:<pid>:<starttime>` (field 22 of /proc/<pid>/stat),
|
|
231
|
+
* `win32:<pid>:<creation time, Unix ms>`. Null when it cannot be read; a pid alone is never an identity.
|
|
232
|
+
*/
|
|
233
|
+
export function processIdentity(pid = process.pid, { platform = process.platform, spawnSync = null, readFile = (f) => fs.readFileSync(f, "utf8") } = {}) {
|
|
234
|
+
if (!Number.isInteger(pid) || pid <= 0) return null;
|
|
235
|
+
if (platform === "darwin") {
|
|
236
|
+
if (typeof spawnSync !== "function") return null;
|
|
237
|
+
const r = spawnSync("/bin/ps", ["-o", "lstart=", "-p", String(pid)], { env: { LC_ALL: "C", LANG: "C", PATH: "/bin:/usr/bin" }, encoding: "utf8" });
|
|
238
|
+
const lstart = String(r?.stdout ?? "").trim();
|
|
239
|
+
return r && r.status === 0 && lstart ? `darwin:${pid}:${lstart}` : null;
|
|
240
|
+
}
|
|
241
|
+
if (platform === "linux") {
|
|
242
|
+
let text; try { text = readFile(`/proc/${pid}/stat`); } catch { return null; }
|
|
243
|
+
const close = text.lastIndexOf(")"); if (close < 0) return null;
|
|
244
|
+
const start = text.slice(close + 1).trim().split(/\s+/)[19];
|
|
245
|
+
return start && /^\d+$/.test(start) ? `linux:${pid}:${start}` : null;
|
|
246
|
+
}
|
|
247
|
+
if (platform === "win32") {
|
|
248
|
+
if (typeof spawnSync !== "function") return null;
|
|
249
|
+
// CIM CreationDate in UTC, as milliseconds since the Unix epoch; the broker's GetProcessTimes value matches it.
|
|
250
|
+
const r = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `$p = Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; if ($p) { [DateTimeOffset]::new($p.CreationDate.ToUniversalTime()).ToUnixTimeMilliseconds() }`], { encoding: "utf8" });
|
|
251
|
+
const ms = String(r?.stdout ?? "").trim();
|
|
252
|
+
return r && r.status === 0 && /^\d+$/.test(ms) ? `win32:${pid}:${ms}` : null;
|
|
253
|
+
}
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Parses an identity string into { platform, pid, start } or null. */
|
|
258
|
+
export function parseIdentity(text) {
|
|
259
|
+
const m = /^(darwin|linux|win32):(\d+):(.+)$/.exec(String(text ?? ""));
|
|
260
|
+
if (!m) return null;
|
|
261
|
+
const pid = Number(m[2]);
|
|
262
|
+
return Number.isInteger(pid) && pid > 0 ? { platform: m[1], pid, start: m[3] } : null;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ---- the broker's proof that a dead holder's snapshot is idle (reset plan section 3; astra 2026-11-09) ------------------------------------
|
|
266
|
+
// SNAPSHOT_STATUS { protocol, runtime, snapshot, owner: { pid, identity, commit, token } } -> { type: "SNAPSHOT_STATUS", schema: "rustright.snapshot-status/1",
|
|
267
|
+
// snapshot, owner, state: "IDLE" | "BUSY" | "UNKNOWN", reasons: [string] }. Read-only, no lease. Only an exact echo of snapshot and owner with state IDLE
|
|
268
|
+
// allows a reclaim; BUSY, UNKNOWN, a different echo, an unreachable broker or any error is "no proof".
|
|
269
|
+
export const SNAPSHOT_STATUS_SCHEMA = "rustright.snapshot-status/1";
|
|
270
|
+
|
|
271
|
+
/** The query for one dead holder's lock (`owner` is the lock body as read). */
|
|
272
|
+
export function snapshotStatusMessage({ protocol, runtime, snapshot, owner }) {
|
|
273
|
+
if (typeof protocol !== "string" || !protocol || typeof snapshot !== "string" || !path.isAbsolute(snapshot)) throw new SeamError("STATUS", "a snapshot status query needs the protocol and the absolute snapshot path");
|
|
274
|
+
if (!owner || !Number.isInteger(owner.pid) || typeof owner.identity !== "string" || typeof owner.commit !== "string" || typeof owner.token !== "string") throw new SeamError("STATUS", "a snapshot status query needs the lock's { pid, identity, commit, token }");
|
|
275
|
+
return { type: "SNAPSHOT_STATUS", protocol, runtime, snapshot, owner: { pid: owner.pid, identity: owner.identity, commit: owner.commit, token: owner.token } };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Whether a reply proves the snapshot idle for exactly this owner. Anything short of that is false. */
|
|
279
|
+
export function snapshotStatusAllowsReclaim(reply, { snapshot, owner }) {
|
|
280
|
+
if (!reply || typeof reply !== "object" || reply.type !== "SNAPSHOT_STATUS" || reply.schema !== SNAPSHOT_STATUS_SCHEMA) return false;
|
|
281
|
+
if (reply.snapshot !== snapshot || !reply.owner || typeof reply.owner !== "object") return false;
|
|
282
|
+
for (const k of ["pid", "identity", "commit", "token"]) if (reply.owner[k] !== owner[k]) return false;
|
|
283
|
+
return reply.state === "IDLE";
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// The broker greets every connection with a HANDSHAKE frame before it answers anything (rustright service.rs emit HANDSHAKE on connect), and may interleave
|
|
287
|
+
// other frames; the reader consumes framed lines until the one whose `type` is the answer (SNAPSHOT_STATUS) or the broker's refusal, which is a RESULT frame
|
|
288
|
+
// with status REJECTED (rustright helpers_impl.rs: { type: "RESULT", exitCode: 125, status: "REJECTED", error, code? }), within the deadline.
|
|
289
|
+
const STATUS_SCRIPT = `const net=require("node:net");const [endpoint,msg,timeout,want]=process.argv.slice(1);const c=net.connect({path:endpoint});let buf="";const t=setTimeout(()=>process.exit(3),Number(timeout));const done=(line)=>{process.stdout.write(line);clearTimeout(t);c.destroy();process.exit(0);};c.on("connect",()=>c.write(msg+"\\n"));c.on("data",(d)=>{buf+=d;let i;while((i=buf.indexOf("\\n"))>=0){const line=buf.slice(0,i);buf=buf.slice(i+1);let f=null;try{f=JSON.parse(line);}catch{continue;}if(!f||typeof f!=="object")continue;if(f.type===want||(f.type==="RESULT"&&f.status==="REJECTED"))done(line);}});c.on("error",()=>process.exit(2));c.on("close",()=>process.exit(4));`;
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* One control query, synchronously (the lock is taken inside the synchronous sync): a child node connects to the broker's socket or pipe, writes the
|
|
293
|
+
* message as one line and returns the frame that answers it (`want`, default SNAPSHOT_STATUS), skipping the HANDSHAKE and any other frame before it; a
|
|
294
|
+
* refusal or error frame is returned as the answer (the caller's judge then says no). Null on any failure (no broker, timeout, bad JSON): no proof.
|
|
295
|
+
*/
|
|
296
|
+
export function snapshotStatusSync({ endpoint, message, timeoutMs = 10_000, want = "SNAPSHOT_STATUS", execFileSync = nodeExecFileSync, execPath = process.execPath }) {
|
|
297
|
+
if (typeof endpoint !== "string" || !endpoint) return null;
|
|
298
|
+
let out;
|
|
299
|
+
try { out = execFileSync(execPath, ["-e", STATUS_SCRIPT, endpoint, JSON.stringify(message), String(timeoutMs), String(want)], { encoding: "utf8", timeout: timeoutMs + 2_000, stdio: ["ignore", "pipe", "ignore"], windowsHide: true }); }
|
|
300
|
+
catch { return null; }
|
|
301
|
+
try { const reply = JSON.parse(String(out).trim()); return reply && typeof reply === "object" ? reply : null; } catch { return null; }
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** The lock body the broker reads (`${snapshot}.lock`): exactly { pid, identity, commit, token }. */
|
|
305
|
+
export function snapshotLockBody({ pid = process.pid, identity, commit }) {
|
|
306
|
+
if (!SHA1.test(String(commit ?? ""))) throw new SeamError("LOCK", `commit ${JSON.stringify(commit)} is not a full sha`);
|
|
307
|
+
const parsed = parseIdentity(identity);
|
|
308
|
+
if (!parsed || parsed.pid !== pid) throw new SeamError("LOCK", `identity ${JSON.stringify(identity)} is not this process's identity`);
|
|
309
|
+
return { pid, identity, commit, token: crypto.randomUUID() };
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Whether the job of a judged seam call is settled: positive evidence that nothing of it can still be running (a parsed result line AND either a durable receipt
|
|
314
|
+
* that was read, whatever its postconditions said, or a refusal before admission: a code with no requestId). A missing or bad result line, a missing receipt, a
|
|
315
|
+
* killed client, a spawn error and a client failure after admission (a requestId with no receipt) are not settled. One rule for the door's lock release.
|
|
316
|
+
*/
|
|
317
|
+
export function seamSettled(judged) {
|
|
318
|
+
if (!judged || !judged.result) return false;
|
|
319
|
+
if (judged.receiptRead === true) return true;
|
|
320
|
+
return judged.result.requestId === null && Boolean(judged.result.code);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Whether `receipt` is the terminal record of the job `requestId` names: its `id` or its signed `provenance.payload.jobId` is that id, and it carries the time the
|
|
325
|
+
* job ended (`terminalAt`, written by every receipt the broker's finish writes, the forced one included; rustright finish_impl.rs). No request id, no receipt, another
|
|
326
|
+
* job's receipt or one with no terminal time is not proof that this request's job ended.
|
|
327
|
+
*/
|
|
328
|
+
/**
|
|
329
|
+
* Whether the receipt proves the job's process tree is gone, so nothing of it can still touch the snapshot: either the job never spawned (the broker records
|
|
330
|
+
* `processOwnership: null` and no `startedAt`), or its reap is complete (`reap.status` "REAPED" with `reaped: true`, rustright-process ReapReport::is_complete) AND the
|
|
331
|
+
* broker's signed survivor census says the tree is contained (`provenance.payload.descendants.status` "tree-contained", service.rs descendants_claim). A terminal
|
|
332
|
+
* receipt alone is not that proof: the broker writes a FAILED receipt for a tree it could not reap (finish_impl.rs tree_unreaped), and a forced terminal receipt
|
|
333
|
+
* carries neither field. Anything short of the proof keeps the door's lock (astra, 2026-11-09).
|
|
334
|
+
*/
|
|
335
|
+
export function receiptProvesTreeGone(receipt) {
|
|
336
|
+
if (!receipt || typeof receipt !== "object") return false;
|
|
337
|
+
const payload = receipt.provenance?.payload;
|
|
338
|
+
const neverSpawned = Object.hasOwn(receipt, "processOwnership") && receipt.processOwnership === null && (receipt.startedAt ?? payload?.startedAt ?? null) === null && (receipt.reap ?? null) === null;
|
|
339
|
+
if (neverSpawned) return true;
|
|
340
|
+
const reap = receipt.reap;
|
|
341
|
+
const reaped = Boolean(reap && typeof reap === "object" && reap.status === "REAPED" && reap.reaped === true);
|
|
342
|
+
return reaped && payload?.descendants?.status === "tree-contained";
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export function receiptIsTerminalFor(receipt, requestId) {
|
|
346
|
+
if (!receipt || typeof receipt !== "object" || typeof requestId !== "string" || !requestId) return false;
|
|
347
|
+
const payload = receipt.provenance?.payload;
|
|
348
|
+
const ids = [receipt.id, payload?.jobId].filter((v) => typeof v === "string" && v);
|
|
349
|
+
if (!ids.length || ids.some((v) => v !== requestId)) return false;
|
|
350
|
+
const terminal = [receipt.terminalAt, payload?.terminalAt].some((v) => typeof v === "string" && v);
|
|
351
|
+
return terminal;
|
|
352
|
+
}
|
package/gate-serve.mjs
CHANGED
|
@@ -195,16 +195,40 @@ function startServer({ root, env }) {
|
|
|
195
195
|
const logDir = path.join(dataRoot(env), "gate-serve");
|
|
196
196
|
fs.mkdirSync(logDir, { recursive: true });
|
|
197
197
|
const out = fs.openSync(path.join(logDir, "serve.log"), "a");
|
|
198
|
-
// A minimal environment: the server outlives the run that started it, so it must carry none of that run's tokens
|
|
199
|
-
// ownership guard rightly refuses a run while any process still holds an earlier run's RIGHTKIT_BUILD_OWNERSHIP).
|
|
198
|
+
// A minimal environment: the server outlives the run that started it, so it must carry none of that run's tokens.
|
|
200
199
|
const keep = ["PATH", "HOME", "USERPROFILE", "SYSTEMROOT", "SystemRoot", "TEMP", "TMP", "TMPDIR", "LOCALAPPDATA", "APPDATA", "RIGHTKIT_MANAGED_ROOT", "RK_GATE_SERVE_IDLE_MS"];
|
|
201
200
|
const childEnv = Object.fromEntries(keep.filter((k) => env[k] !== undefined).map((k) => [k, env[k]]));
|
|
201
|
+
if (process.platform === "win32") { fs.closeSync(out); startOutsideJobs({ root, childEnv, logDir, env }); return; }
|
|
202
202
|
const child = spawn(process.execPath, [SELF, "serve", root], { detached: true, stdio: ["ignore", out, out], env: childEnv, cwd: path.dirname(SELF), windowsHide: true });
|
|
203
203
|
child.unref();
|
|
204
204
|
fs.closeSync(out);
|
|
205
205
|
} catch { /* the next run tries again; this one verifies in full */ }
|
|
206
206
|
}
|
|
207
207
|
|
|
208
|
+
/**
|
|
209
|
+
* Windows: a child of the gate stays in the gate's jobs whatever `detached` says (libuv never asks to break away), so a server spawned
|
|
210
|
+
* here sat in the gate's job, where every release counted it and kept the lock (S0, S9, GC-T06), and died with the launcher's
|
|
211
|
+
* kill-on-close job, so it was never resident (S14; a new server on every run, Dell 2026-11-07). WMI starts it outside both, with no
|
|
212
|
+
* window. WMI passes no environment, so the server reads its environment from a file it removes once read (`serve-env`).
|
|
213
|
+
*/
|
|
214
|
+
function startOutsideJobs({ root, childEnv, logDir, env }) {
|
|
215
|
+
const specFile = path.join(logDir, `serve-env-${crypto.randomUUID()}.json`);
|
|
216
|
+
fs.writeFileSync(specFile, JSON.stringify({ root, env: childEnv, log: path.join(logDir, "serve.log") }), { flag: "wx", mode: 0o600 });
|
|
217
|
+
const ps = (s) => `'${String(s).replace(/'/g, "''")}'`;
|
|
218
|
+
const commandLine = `"${process.execPath}" "${SELF}" serve-env "${specFile}"`;
|
|
219
|
+
const script = [
|
|
220
|
+
"$ErrorActionPreference = 'Stop'",
|
|
221
|
+
"$s = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly -Property @{ ShowWindow = [uint16]0 }",
|
|
222
|
+
`$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = ${ps(commandLine)}; CurrentDirectory = ${ps(path.dirname(SELF))}; ProcessStartupInformation = $s }`,
|
|
223
|
+
"exit [int]$r.ReturnValue",
|
|
224
|
+
].join("\n");
|
|
225
|
+
const launcher = spawn("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { stdio: "ignore", windowsHide: true, env });
|
|
226
|
+
// A launch that failed leaves no server to remove the file.
|
|
227
|
+
launcher.on("exit", (code) => { if (code !== 0) fs.rmSync(specFile, { force: true }); });
|
|
228
|
+
launcher.on("error", () => fs.rmSync(specFile, { force: true }));
|
|
229
|
+
launcher.unref();
|
|
230
|
+
}
|
|
231
|
+
|
|
208
232
|
/**
|
|
209
233
|
* GC-A11 `cargo metadata` for a directory inside a gate snapshot, answered by the resident gate (cached per snapshot while it is unchanged), else
|
|
210
234
|
* run directly with `cargo` (an absolute path) and `env`. Returns `{ status, stdout, stderr, served, cached }`. Never through the broker.
|
|
@@ -232,6 +256,14 @@ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(SELF
|
|
|
232
256
|
const [cmd, a, b] = process.argv.slice(2);
|
|
233
257
|
if (cmd === "serve") {
|
|
234
258
|
serve({ root: a, log: (m) => console.log(`${new Date().toISOString()} gate-serve: ${m}`) }).catch((error) => { console.log(`${new Date().toISOString()} gate-serve: cannot serve: ${error?.message ?? error}`); process.exit(1); });
|
|
259
|
+
} else if (cmd === "serve-env") {
|
|
260
|
+
// The Windows start (startOutsideJobs): root, environment and log come from the file, removed once read.
|
|
261
|
+
let spec = null; try { spec = JSON.parse(fs.readFileSync(a, "utf8")); } catch { spec = null; } finally { if (a) fs.rmSync(a, { force: true }); }
|
|
262
|
+
if (typeof spec?.root !== "string" || typeof spec.log !== "string") process.exit(2);
|
|
263
|
+
for (const k of Object.keys(process.env)) delete process.env[k];
|
|
264
|
+
Object.assign(process.env, spec.env ?? {});
|
|
265
|
+
const log = (m) => { try { fs.appendFileSync(spec.log, `${new Date().toISOString()} gate-serve: ${m}\n`); } catch { /* a log that cannot be written never stops the server */ } };
|
|
266
|
+
serve({ root: spec.root, log }).catch((error) => { log(`cannot serve: ${error?.message ?? error}`); process.exit(1); });
|
|
235
267
|
} else if (cmd === "ask") {
|
|
236
268
|
let req = null; try { req = JSON.parse(a); } catch { req = null; }
|
|
237
269
|
// Exit only after the reply is flushed: process.exit right after a large write to a pipe truncates it (a cargo metadata answer is megabytes).
|
package/gate-stages.mjs
CHANGED
|
@@ -177,9 +177,13 @@ export function writeReceipt({ commonDir, receipt, write = (file, data) => write
|
|
|
177
177
|
* The inputs a receipt binds besides the commit: the tree id, each lockfile's digest, the gate's own digest and the toolchain versions.
|
|
178
178
|
* A receipt from an earlier run counts for a stage only when every one of these is unchanged.
|
|
179
179
|
*/
|
|
180
|
-
export function bindingOf({ tree, lockFiles = {}, gateFile, readFile = (f) => fs.readFileSync(f), toolchain = {}, executor }) {
|
|
180
|
+
export function bindingOf({ tree, lockFiles = {}, gateFile, gateJudge = null, readFile = (f) => fs.readFileSync(f), toolchain = {}, executor }) {
|
|
181
181
|
let gate = null;
|
|
182
|
-
try {
|
|
182
|
+
try {
|
|
183
|
+
const bytes = readFile(gateFile);
|
|
184
|
+
// Imported judging code can change while the entrypoint stays byte-identical. A whole-stage hit must not bypass that judge.
|
|
185
|
+
gate = sha256(gateJudge ? Buffer.concat([Buffer.from(bytes), Buffer.from(`\0judge:${gateJudge}`)]) : bytes);
|
|
186
|
+
} catch { /* unreadable: no binding, nothing reused */ }
|
|
183
187
|
return { tree, locks: Object.fromEntries(Object.entries(lockFiles).map(([k, v]) => [k, sha256(v)]).sort(([a], [b]) => a.localeCompare(b))), gate, toolchain, executor };
|
|
184
188
|
}
|
|
185
189
|
|
package/ghsa-audit.mjs
CHANGED
|
@@ -34,10 +34,25 @@ export function registryPackages(lockText) {
|
|
|
34
34
|
|
|
35
35
|
const utcDay = (now) => new Date(now()).toISOString().slice(0, 10);
|
|
36
36
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
// A network failure or a 429/5xx answer is retried (three attempts, 1 s then 3 s apart): parallel qualification jobs each ask
|
|
38
|
+
// OSV for the whole root lock, and a single dropped connection refused whole units (qualify-direct runs 43071676354,
|
|
39
|
+
// 43077177456: "fetch failed"). Any other answer, and a third failure, still throws: the audit never passes unasked.
|
|
40
|
+
const RETRY_DELAYS_MS = [1_000, 3_000];
|
|
41
|
+
const retryable = (status) => status === 429 || status >= 500;
|
|
42
|
+
async function osvJson(fetchFn, url, init, { sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) } = {}) {
|
|
43
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
44
|
+
let r;
|
|
45
|
+
try {
|
|
46
|
+
r = await fetchFn(url, { ...init, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (attempt >= RETRY_DELAYS_MS.length) throw error;
|
|
49
|
+
await sleep(RETRY_DELAYS_MS[attempt]);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (r.ok) return r.json();
|
|
53
|
+
if (!retryable(r.status) || attempt >= RETRY_DELAYS_MS.length) throw new Error(`${url} answered HTTP ${r.status}`);
|
|
54
|
+
await sleep(RETRY_DELAYS_MS[attempt]);
|
|
55
|
+
}
|
|
41
56
|
}
|
|
42
57
|
|
|
43
58
|
/** One OSV batch query over `packages`, following page tokens: a Map of "name@version" to the ids OSV lists for it. */
|
package/heavy-command.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { recordLockChild } from "./snapshot.mjs";
|
|
2
3
|
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, realpathSync } from "node:fs";
|
|
3
4
|
import os from "node:os";
|
|
4
5
|
import path from "node:path";
|
|
5
6
|
import { spawn, spawnSync } from "./background-process.mjs";
|
|
6
|
-
import { spawnUnderOwnership } from "./build-ownership.mjs";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import { randomUUID } from "node:crypto";
|
|
9
9
|
|
|
@@ -209,9 +209,9 @@ export async function watchOwnedProcessTree(
|
|
|
209
209
|
|
|
210
210
|
function spawnOwnerWatcher(details) {
|
|
211
211
|
const payload = Buffer.from(JSON.stringify(details)).toString("base64url");
|
|
212
|
-
const watcher =
|
|
212
|
+
const watcher = recordLockChild(spawn(process.execPath, [SELF, "--watch-owner-base64", payload], {
|
|
213
213
|
detached: true, env: process.env, stdio: "ignore", windowsHide: true,
|
|
214
|
-
});
|
|
214
|
+
}));
|
|
215
215
|
watcher.once("error", () => {
|
|
216
216
|
const observedStart = processStartedAt(details.childPid);
|
|
217
217
|
if (Number.isFinite(observedStart) && Math.abs(observedStart - Number(details.childStartedAtMs)) <= 2000) {
|
|
@@ -367,7 +367,8 @@ export async function runHeavyCommand(args, { env = process.env } = {}) {
|
|
|
367
367
|
|
|
368
368
|
function spawnAttached(command, args, env, slot) {
|
|
369
369
|
return new Promise((resolve, reject) => {
|
|
370
|
-
const child =
|
|
370
|
+
const child = spawn(command, args, { cwd: process.cwd(), env, stdio: "inherit", windowsHide: true, detached: heavyChildDetached({ slot }) });
|
|
371
|
+
if (heavyChildDetached({ slot })) recordLockChild(child, { env });
|
|
371
372
|
try {
|
|
372
373
|
if (child.pid && slot) slot.trackChild(child.pid, command);
|
|
373
374
|
} catch (error) {
|
|
@@ -12,10 +12,13 @@
|
|
|
12
12
|
// 8. verify (the installed exe equals the build, and its Authenticode subject is the signer's)
|
|
13
13
|
// Nothing installs before step 6 has verified, so no unsigned installer is ever run. Every host effect is a dependency, so the order runs with fakes.
|
|
14
14
|
import { createHash } from "node:crypto";
|
|
15
|
-
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
15
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
16
16
|
import path from "node:path";
|
|
17
17
|
import { spawnSync } from "./background-process.mjs";
|
|
18
18
|
import { neutralIgnored } from "./stage-ledger.mjs";
|
|
19
|
+
import { treeEntries } from "./snapshot.mjs";
|
|
20
|
+
import { SOURCE_IDENTITY_FILE, sourceIdentityBytes } from "./snapshot-identity.mjs";
|
|
21
|
+
import { readSourceSplit } from "./source-split.mjs";
|
|
19
22
|
import { patchTauriBundleType } from "./tauri-bundle-marker.mjs";
|
|
20
23
|
import { listNsisPayload, verifyNsisEmbeddedBinary } from "./nsis-payload.mjs";
|
|
21
24
|
import { SIGN_SUBJECT, SuiteSigningError, WINDOWS_SIGNED_KIND, identifierOverrideReason, isProductBuildStep, stepWords } from "./suite-signing-policy.mjs";
|
|
@@ -221,9 +224,70 @@ export function deriveResourceExecutables({ tauriDir, readFile = readText }) {
|
|
|
221
224
|
return [...found.values()];
|
|
222
225
|
}
|
|
223
226
|
|
|
224
|
-
|
|
225
|
-
|
|
227
|
+
const signingSourceError = (message, file) => refuse("TAURI_AUTHENTICODE_TRACKED_RESOURCE", message, { file });
|
|
228
|
+
const containedRelative = (root, file) => {
|
|
229
|
+
const rel = path.relative(root, path.resolve(file));
|
|
230
|
+
if (!rel || rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) signingSourceError(`${file} is outside signing source ${root}`, file);
|
|
231
|
+
return rel.split(path.sep).join("/");
|
|
232
|
+
};
|
|
233
|
+
const regularSigningFile = (file) => {
|
|
234
|
+
const st = lstatSync(file);
|
|
235
|
+
if (!st.isFile() || st.nlink !== 1) signingSourceError(`${file} must be a regular file with exactly one hard link`, file);
|
|
236
|
+
};
|
|
237
|
+
const safeSigningPath = (root, file) => {
|
|
238
|
+
const rel = containedRelative(root, file);
|
|
239
|
+
let dir = root;
|
|
240
|
+
for (const segment of ["", ...rel.split("/").slice(0, -1)]) {
|
|
241
|
+
dir = path.join(dir, segment);
|
|
242
|
+
const st = lstatSync(dir);
|
|
243
|
+
if (!st.isDirectory() || st.isSymbolicLink()) signingSourceError(`${file} has a linked or non-directory signing source parent ${dir}`, file);
|
|
244
|
+
}
|
|
245
|
+
regularSigningFile(file);
|
|
246
|
+
return rel;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
// The snapshot has no git directory. Its adjacent state names the checkout object database & selected commit; the generated
|
|
250
|
+
// source identity must equal that commit's canonical identity. Read tracked paths from the sealed commit, never the checkout's
|
|
251
|
+
// index or the state's mutable paths cache. This works with both legacy door-run and reset seam callers; neither marker is required.
|
|
252
|
+
function signingSnapshot({ appRoot, tauriDir, env }) {
|
|
253
|
+
let root = path.resolve(appRoot ?? tauriDir);
|
|
254
|
+
while (true) {
|
|
255
|
+
const stateFile = `${root}.state.json`;
|
|
256
|
+
const identityFile = path.join(root, SOURCE_IDENTITY_FILE);
|
|
257
|
+
if (existsSync(stateFile) || existsSync(identityFile)) {
|
|
258
|
+
try {
|
|
259
|
+
regularSigningFile(stateFile);
|
|
260
|
+
safeSigningPath(root, identityFile);
|
|
261
|
+
const state = JSON.parse(readFileSync(stateFile, "utf8"));
|
|
262
|
+
if (state?.schema !== "rightkit.snapshot-state/1" || typeof state.repo !== "string" || !path.isAbsolute(state.repo)
|
|
263
|
+
|| !/^[0-9a-f]{40}$/.test(state.commit ?? "") || !/^[0-9a-f]{40}$/.test(state.tree ?? "")) throw new Error("invalid snapshot state");
|
|
264
|
+
const entries = treeEntries(state.repo, state.commit);
|
|
265
|
+
const expected = sourceIdentityBytes({ checkout: state.repo, commit: state.commit, entries });
|
|
266
|
+
if (!readFileSync(identityFile).equals(expected) || JSON.parse(expected.toString("utf8")).trees[""] !== state.tree) throw new Error("snapshot state and selected commit source identity differ");
|
|
267
|
+
if (env.RUSTRIGHT_GATE_COMMIT && env.RUSTRIGHT_GATE_COMMIT !== state.commit) throw new Error("snapshot state differs from RUSTRIGHT_GATE_COMMIT");
|
|
268
|
+
const fold = process.platform === "win32" || process.platform === "darwin" ? (p) => p.toLowerCase() : (p) => p;
|
|
269
|
+
const split = readSourceSplit({ env, cwd: appRoot ?? tauriDir });
|
|
270
|
+
if (split && (fold(path.resolve(split.snapshot)) !== fold(root) || split.commit !== state.commit || split.tree !== state.tree || fold(path.resolve(split.checkout)) !== fold(path.resolve(state.repo)))) throw new Error("snapshot state differs from the live source split");
|
|
271
|
+
return { root, tracked: new Set(entries.map((entry) => fold(entry.path))), fold };
|
|
272
|
+
} catch (error) { signingSourceError(`cannot prove signing snapshot ${root}: ${error.message}`, root); }
|
|
273
|
+
}
|
|
274
|
+
const parent = path.dirname(root);
|
|
275
|
+
if (parent === root) return null;
|
|
276
|
+
root = parent;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** `Map(file -> "tracked" | "ignored" | "unignored")`: selected sealed tree for a snapshot, else git's index; then neutral ignore rules. Fails closed on missing proof or unsafe paths. */
|
|
281
|
+
export function classifyStagedFiles(files, { appRoot, tauriDir, env = process.env }) {
|
|
226
282
|
const out = new Map();
|
|
283
|
+
if (!files.length) return out;
|
|
284
|
+
const snapshot = signingSnapshot({ appRoot, tauriDir, env });
|
|
285
|
+
if (snapshot) {
|
|
286
|
+
const paths = files.map((file) => safeSigningPath(snapshot.root, file));
|
|
287
|
+
const ignored = neutralIgnored({ dir: snapshot.root, paths, env });
|
|
288
|
+
files.forEach((file, index) => out.set(file, snapshot.tracked.has(snapshot.fold(paths[index])) ? "tracked" : ignored.has(paths[index]) ? "ignored" : "unignored"));
|
|
289
|
+
return out;
|
|
290
|
+
}
|
|
227
291
|
for (const file of files) {
|
|
228
292
|
const dir = path.dirname(path.resolve(file));
|
|
229
293
|
const top = spawnSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8", windowsHide: true });
|
|
@@ -277,6 +341,8 @@ export function installTauriAuthenticode({ descriptor: raw, debugDir, appRoot, r
|
|
|
277
341
|
if (kind === "tracked") refuse("TAURI_AUTHENTICODE_TRACKED_RESOURCE", `${file} is tracked by git, and signing it in place would change the commit's tree: stage it (or git-ignore it) the way release stages it`, { file });
|
|
278
342
|
if (kind !== "ignored") refuse("TAURI_AUTHENTICODE_TRACKED_RESOURCE", `${file} is not a git-ignored stage output (${kind ?? "unknown"}): it cannot be signed in place`, { file, state: kind ?? "unknown" });
|
|
279
343
|
}
|
|
344
|
+
// The bytes each in-place copy had before signing: the gate admits a staged entry's change only from exactly these bytes to the signed ones.
|
|
345
|
+
const inPlaceBefore = new Map(inPlace.map((file) => [file, sha256(file)]));
|
|
280
346
|
// 2. The marker reaches its final value before any byte is signed.
|
|
281
347
|
step("patch-marker", () => patchMarker(exe));
|
|
282
348
|
// 3. Sign and verify the exe and every copy of every sidecar, and record each digest.
|
|
@@ -336,10 +402,13 @@ export function installTauriAuthenticode({ descriptor: raw, debugDir, appRoot, r
|
|
|
336
402
|
item.sha256 = sha256(item.path);
|
|
337
403
|
if (!item.sidecar.digests.has(item.sha256)) refuse("TAURI_AUTHENTICODE_SIDECAR_STALE", `installed ${item.path} (sha256 ${item.sha256}) is not the signed ${item.sidecar.file}`, { sidecar: item.sidecar.name });
|
|
338
404
|
}
|
|
405
|
+
const verifiedAfter = new Map(sidecars.flatMap((sidecar) => sidecar.copies.map((copy) => [copy.path, copy.sha256After])));
|
|
339
406
|
return {
|
|
340
407
|
order, exe, installer, installed, payload,
|
|
341
408
|
// In-place signed stage outputs (git-ignored): the gate's ledger walk attributes them from `files` (stage-ledger.mjs reportedPaths); paths are absolute here, the caller makes them app-relative.
|
|
342
|
-
|
|
409
|
+
// The digest after signing is the one the signer recorded and the verify step checked (copy.sha256After), never a rehash after install:
|
|
410
|
+
// a copy rewritten after verification must stay a refused change at the gate's close.
|
|
411
|
+
stageOutputs: { files: inPlace.map((file) => ({ path: file.replaceAll("\\", "/"), kind: "signed-in-place", sha256Before: inPlaceBefore.get(file), sha256: verifiedAfter.get(file) })) },
|
|
343
412
|
sidecars: installedSidecars.map((item) => ({ name: item.sidecar.name, copies: item.sidecar.copies.map((copy) => ({ role: copy.role, path: copy.path, sha256After: copy.sha256After })), installed: { path: item.path, sha256: item.sha256 } })),
|
|
344
413
|
signing: { subject: SIGN_SUBJECT, files: [...signedExe, ...signedInstaller].map((item) => ({ file: item.file, sha256Before: item.before?.sha256, sha256After: item.after?.sha256, subject: item.subject })) },
|
|
345
414
|
};
|