@rightkit/release 0.6.40 → 0.6.42

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.
Files changed (85) hide show
  1. package/README.md +110 -11
  2. package/admission-files.mjs +40 -0
  3. package/admission-host.mjs +2 -1
  4. package/app-check.mjs +303 -16
  5. package/app-closure.mjs +6 -4
  6. package/bin/rightkit-gate.mjs +177 -32
  7. package/cargo-contract.mjs +17 -31
  8. package/cargo-license-notices.mjs +129 -19
  9. package/cargo-target-shim.mjs +14 -0
  10. package/carried-cargo.mjs +2 -4
  11. package/cli/right-release.mjs +24 -2
  12. package/cross-targets.mjs +24 -0
  13. package/deterministic-scans.mjs +150 -58
  14. package/development-signing.mjs +25 -2
  15. package/development.mjs +34 -1
  16. package/direct-release-command.mjs +154 -0
  17. package/disk-policy.mjs +16 -0
  18. package/feature-coverage.mjs +134 -0
  19. package/gate-coverage.mjs +38 -0
  20. package/gate-stages.mjs +1 -0
  21. package/ghsa-audit.mjs +95 -0
  22. package/install-app.mjs +33 -5
  23. package/install-channels.mjs +301 -0
  24. package/interactive-session-run.mjs +105 -0
  25. package/legal-contract.mjs +10 -1
  26. package/legion-freeze-consumer.mjs +241 -0
  27. package/linux-publish.mjs +136 -0
  28. package/local-publish.mjs +31 -8
  29. package/nsis-pack.mjs +95 -0
  30. package/nsis-upgrade-template.mjs +93 -0
  31. package/outdated-command.mjs +19 -0
  32. package/ownership-class-rules.mjs +32 -10
  33. package/ownership-mandatory-set.json +23 -0
  34. package/ownership-mandatory-set.mjs +66 -8
  35. package/package-recipe-targets.mjs +54 -19
  36. package/package.json +1 -1
  37. package/payload-root-install.mjs +123 -0
  38. package/plugin-delivery.mjs +141 -0
  39. package/prebuild-gates.mjs +8 -4
  40. package/preflight.mjs +6 -1
  41. package/provision-model-bundle.mjs +172 -0
  42. package/pub-upload.mjs +1 -1
  43. package/publish-local-npm.mjs +34 -9
  44. package/publish-retention.mjs +106 -0
  45. package/publish-update.mjs +15 -8
  46. package/qa-build-features.mjs +24 -15
  47. package/qa-contract.mjs +5 -6
  48. package/qa-control-scan.mjs +14 -0
  49. package/qa-web-pairing.mjs +76 -0
  50. package/r2-s3-multipart.mjs +190 -0
  51. package/r2-verified-upload.mjs +28 -16
  52. package/recipe-build.mjs +53 -3
  53. package/release-checks.mjs +53 -2
  54. package/release-config.mjs +8 -3
  55. package/release-invocation.mjs +12 -2
  56. package/release-pin-floor.mjs +44 -0
  57. package/release-qa-audit.mjs +18 -2
  58. package/release-qa-command.mjs +17 -1
  59. package/release-qa-policy.mjs +30 -3
  60. package/release-switch-cfg.mjs +271 -0
  61. package/release-switch-registry.json +60 -1
  62. package/release-switch-scan.mjs +398 -23
  63. package/release.mjs +97 -6
  64. package/render-views.mjs +141 -0
  65. package/rightkit-registry-resolver.mjs +1 -1
  66. package/rightkit-versions.json +140 -103
  67. package/runtime-artifact-manifest.mjs +9 -0
  68. package/runtime-manifest-refresh.mjs +88 -0
  69. package/rustright-stage.mjs +197 -0
  70. package/scan-digest.mjs +15 -9
  71. package/scan-tool-enrolment.mjs +1 -1
  72. package/security-policy.mjs +196 -0
  73. package/shell-contract.mjs +32 -0
  74. package/snapshot-broker.mjs +8 -1
  75. package/snapshot-check.mjs +58 -0
  76. package/snapshot-request.mjs +25 -2
  77. package/stage-commands.mjs +33 -4
  78. package/stage-receipt.mjs +115 -0
  79. package/stage-sidecar.mjs +188 -17
  80. package/stage-xcframework.mjs +118 -0
  81. package/suite-api.generated.mjs +16 -1
  82. package/unit-gate.mjs +14 -2
  83. package/upload-large.mjs +4 -4
  84. package/upload-release.mjs +6 -0
  85. package/win-package-recipe.mjs +26 -4
@@ -474,6 +474,28 @@ export function verifySnapshotEvidenceIdentity(evidence, { commit, tree = commit
474
474
  }
475
475
 
476
476
  export const NESTED_CHILD_FIELDS = Object.freeze(["requestId", "parentRequestId", "shim", "argv", "cwd", "exitCode", "status", "outputDir"]);
477
+ /**
478
+ * Fields a nested child may also carry (rightkit#1418): `declaredInputDigests`, the digests of the snapshot's declared inputs the BROKER signs from
479
+ * the child's own admission and binds at its exit, as it does for a top-level compile. Optional until the broker signs them (rustright, nested compile
480
+ * children); when present it is well formed here and compared strictly by the gate (declaredInputDigestProblems, verifyBrokerLedger).
481
+ */
482
+ export const NESTED_CHILD_OPTIONAL_FIELDS = Object.freeze(["declaredInputDigests"]);
483
+ const DIGEST_ENTRY_KEYS = (d) => { const k = Object.keys(d).sort().join(); return (k === "path,sha256" && typeof d.sha256 === "string" && /^[0-9a-f]{64}$/.test(d.sha256)) || (k === "absent,path" && d.absent === true); };
484
+
485
+ /**
486
+ * The problems of a nested child's signed `declaredInputDigests` against the gate's own truth, `[]` when they hold: `gateInputs` are the snapshot's
487
+ * declared input paths in declaration order, `policy` is `{ produced: Set, current: one digest per declared input }` as verifySnapshotReceipt takes it.
488
+ * Each entry must be the gate's digest of that input at the end of the stage unless the stage itself produced the input: an input swapped for the
489
+ * child and restored before the stage ended is seen as the child's differing digest (a child that read B while the stage ends with A).
490
+ */
491
+ export function declaredInputDigestProblems(signed, { gateInputs, policy }) {
492
+ if (!Array.isArray(signed) || signed.length !== gateInputs.length || !signed.every((d, i) => isObject(d) && d.path === gateInputs[i] && DIGEST_ENTRY_KEYS(d))) return ["its signed declaredInputDigests are not the snapshot's declared inputs in declaration order, each exactly { path, sha256 } or { path, absent: true }"];
493
+ const { produced, current } = policy ?? {};
494
+ if (!(produced instanceof Set) || !Array.isArray(current) || current.length !== gateInputs.length) return ["the gate has no end-of-stage digest of the declared inputs to compare it with"];
495
+ const problems = [];
496
+ signed.forEach((d, i) => { if (!produced.has(gateInputs[i]) && !same(d, current[i])) problems.push(`its signed declaredInputDigests entry for ${gateInputs[i]} is not the gate's own digest of that input at the end of the stage, and the stage did not change it`); });
497
+ return problems;
498
+ }
477
499
  /** The most children a root job's list may carry (rustright#190: the broker's cap; a refused child is never listed). */
478
500
  export const NESTED_CHILDREN_CAP = 8192;
479
501
 
@@ -497,7 +519,8 @@ export function verifyNestedChildren(evidence, receipt, { snapshotPath, checkout
497
519
  const ids = new Set();
498
520
  return list.map((child, index) => {
499
521
  const where = `nestedChildren[${index}]`;
500
- if (!isObject(child) || Object.keys(child).sort().join() !== [...NESTED_CHILD_FIELDS].sort().join()) fail("nested", `${where} is not exactly { ${NESTED_CHILD_FIELDS.join(", ")} }`);
522
+ if (!isObject(child) || !NESTED_CHILD_FIELDS.every((k) => Object.hasOwn(child, k)) || !Object.keys(child).every((k) => NESTED_CHILD_FIELDS.includes(k) || NESTED_CHILD_OPTIONAL_FIELDS.includes(k))) fail("nested", `${where} is not exactly { ${NESTED_CHILD_FIELDS.join(", ")} } (plus optionally ${NESTED_CHILD_OPTIONAL_FIELDS.join(", ")})`);
523
+ if (child.declaredInputDigests !== undefined && (!Array.isArray(child.declaredInputDigests) || !child.declaredInputDigests.every((d) => isObject(d) && typeof d.path === "string" && DIGEST_ENTRY_KEYS(d)))) fail("nested", `${where} declaredInputDigests is not a list of { path, sha256 } or { path, absent: true }`);
501
524
  if (typeof child.requestId !== "string" || !child.requestId || child.requestId === jobId || ids.has(child.requestId)) fail("nested", `${where} has no request id of its own`);
502
525
  const name = `${where} (${child.requestId})`;
503
526
  // The parent is the job the request named: this job, or a child listed before it (admission order; depth >= 2, rustright#190 ad9ecb37).
@@ -517,7 +540,7 @@ export function verifyNestedChildren(evidence, receipt, { snapshotPath, checkout
517
540
  if (inside(out, checkout, platform) || inside(out, canon(checkout), platform)) fail("nested", `${name} output directory ${out} is inside the checkout`);
518
541
  if (!isInsideGenerationTarget(out, outputRoots, platform)) fail("nested", `${name} output directory ${out} is not inside a managed generation target under ${outputRoots.join(", ")}`);
519
542
  }
520
- return { requestId: child.requestId, parentRequestId: child.parentRequestId, shim: child.shim, argv: [...child.argv], cwd: child.cwd, exitCode: 0, status: child.status, outputDir: out };
543
+ return { requestId: child.requestId, parentRequestId: child.parentRequestId, shim: child.shim, argv: [...child.argv], cwd: child.cwd, exitCode: 0, status: child.status, outputDir: out, ...(child.declaredInputDigests !== undefined ? { declaredInputDigests: child.declaredInputDigests.map((d) => ({ ...d })) } : {}) };
521
544
  });
522
545
  }
523
546
 
@@ -6,7 +6,8 @@ import fs from "node:fs";
6
6
  import path from "node:path";
7
7
  import { CARGO_METADATA_ARGS, cargoPackageArgs, localTestPlan, npmPackArgs, qualifyFmtArgs } from "./local-publish.mjs";
8
8
  import { SWAP_HELPER_CARGO_ARGS, SWAP_HELPER_METADATA_ARGS, SWAP_HELPER_PACKAGE } from "./swap-helper-bundle.mjs";
9
- import { carriedRequestOf } from "./snapshot-request.mjs";
9
+ import { carriedRequestOf, lockedArgv, splitCarriedArgs } from "./snapshot-request.mjs";
10
+ import { directCargoShape } from "./cargo-target-shim.mjs";
10
11
 
11
12
  /** Stands for the one argument that is a fresh absolute scratch path (`pnpm pack --pack-destination <mkdtemp>`). */
12
13
  export const ANY_ABSOLUTE_PATH = Object.freeze({ anyAbsolutePath: true });
@@ -20,7 +21,10 @@ const PNPM = (...argvs) => ({ kind: "adapter", adapter: "rightkit-pnpm", argvs }
20
21
  const CARGO = (cwd, ...argvs) => {
21
22
  const carried = argvs.map((argv) => carriedRequestOf(argv, cwd) ?? { argv, cwd });
22
23
  if (new Set(carried.map((c) => c.cwd)).size !== 1) throw new Error(`the spellings of one cargo command run in different directories: ${argvs.map((a) => a.join(" ")).join(" | ")}`);
23
- return { kind: "cargo", argvs: carried.map((c) => c.argv), cwd: carried[0].cwd };
24
+ // GC-A11: a command of the direct shape (directCargoShape, the one list carried-cargo.mjs runs by) compiles nothing and runs directly,
25
+ // so it makes no broker job and no signed receipt: the row is `direct`, the stage owes its recorded direct ledger entry instead.
26
+ const direct = carried.every((c) => directCargoShape(c.argv));
27
+ return { kind: "cargo", argvs: carried.map((c) => c.argv), cwd: carried[0].cwd, ...(direct ? { direct: true } : {}) };
24
28
  };
25
29
 
26
30
  /** Readable name of an expected command (scratch paths shown as <scratch>). */
@@ -90,11 +94,12 @@ export function requestIs(payload, row, { checkout = null } = {}) {
90
94
  }
91
95
 
92
96
  /**
93
- * Assigns each job (`{ id, payload }`) to a distinct command of the stage. Returns { assigned: Map(id -> row), unmatched: [id...],
97
+ * Assigns each job (`{ id, payload }`) to a distinct command of the stage that runs in the broker (a `direct` row has none). Returns { assigned: Map(id -> row), unmatched: [id...],
94
98
  * missing: [row...] }: a job that is none of the commands is unmatched; a command no job covers is missing.
95
99
  */
96
100
  export function assignJobs(rows, jobs, options = {}) {
97
- const free = rows.map((row) => ({ row, taken: false }));
101
+ // A direct row (GC-A11) is never a broker job: it is neither matched to a receipt nor reported missing; directRowsNotRun checks it.
102
+ const free = rows.filter((row) => row.direct !== true).map((row) => ({ row, taken: false }));
98
103
  const assigned = new Map(), unmatched = [];
99
104
  for (const job of jobs) {
100
105
  const slot = free.find((s) => !s.taken && requestIs(job.payload, s.row, options));
@@ -102,3 +107,27 @@ export function assignJobs(rows, jobs, options = {}) {
102
107
  }
103
108
  return { assigned, unmatched, missing: free.filter((s) => !s.taken).map((s) => s.row) };
104
109
  }
110
+
111
+ /**
112
+ * The direct rows (GC-A11) of a stage that the carrier's ledger does not show as run, each with why. `entries` are the stage's ledger
113
+ * records (cargo-ledger.mjs readLedger). A direct row is satisfied by a record of a direct call (`direct: true`, status `ran`) with exit 0
114
+ * whose cargo words, locked as the stage's are, are one of the row's spellings and whose directory (the process cwd, or the
115
+ * `--manifest-path` directory) is the row's `cwd` of the checkout the stage ran in. One record satisfies one row.
116
+ */
117
+ export function directRowsNotRun(rows, entries) {
118
+ const pool = (entries ?? []).filter((e) => e?.direct === true && e.status === "ran");
119
+ const problems = [];
120
+ for (const row of rows.filter((r) => r.direct === true)) {
121
+ const matching = pool.filter((e) => {
122
+ const split = splitCarriedArgs(Array.isArray(e.argv) ? e.argv : []);
123
+ if (split.refusal) return false;
124
+ const dir = posixOf(split.manifestPath === null ? e.cwd : path.resolve(String(e.cwd), path.dirname(split.manifestPath)));
125
+ const words = lockedArgv(split.words);
126
+ return row.argvs.some((argv) => argv.length === words.length && argv.every((w, i) => w === words[i])) && (row.cwd === "." ? dir !== "" : dir.endsWith(`/${row.cwd}`) || dir === row.cwd);
127
+ });
128
+ const ran = matching.find((e) => e.exit === 0);
129
+ if (ran) { pool.splice(pool.indexOf(ran), 1); continue; }
130
+ problems.push({ row, why: matching.length ? `ran with exit ${matching[0].exit}` : "has no recorded direct run" });
131
+ }
132
+ return problems;
133
+ }
@@ -0,0 +1,115 @@
1
+ // Read the stage receipt back and prove it (rightkit#1039, #428).
2
+ //
3
+ // `stage-sidecar` writes `stage-sidecar.json` (receipt) with one row per staged file: name, path, sha256, and for a cargo-bin row the Cargo profile.
4
+ // An app that assembles a payload by hand (copies those files into an .app or a payload folder) must not trust the receipt's word: this module
5
+ // reads it back and compares it with the bytes on disk.
6
+ //
7
+ // readVerifiedStageReceipt({ root, receiptPath?, target, profile?, mode?, names, kind? }) -> { [name]: { path (absolute), sha256 } }
8
+ // throws StageReceiptError when the receipt is not a valid receipt for `target`, a name has no row (or more than one), a row was staged with another
9
+ // Cargo `profile`, the receipt was written by another build `mode` (a release asks for mode "release"; a receipt that records none is refused),
10
+ // or the file on disk is missing, is not a regular file, or has other bytes than the row.
11
+ //
12
+ // assertStageReceiptGuard({ root, config, mode }) the release-time guard, enabled by `targets.<platform>.sign.stageReceipt`:
13
+ // { receipt: "<app-relative receipt>", bind?: { "<app-relative payload file>": "<row name>" } }
14
+ // Immediately before signing: the receipt must be a release receipt (every profiled row `release`), every row's staged file must still have
15
+ // its recorded sha256, and every bound payload file must be byte-identical to its row (a hand-assembled copy that drifted refuses).
16
+ import { createHash } from "node:crypto";
17
+ import nodeFs from "node:fs";
18
+ import path from "node:path";
19
+ import { validateStageSidecarReceipt } from "./stage-sidecar.mjs";
20
+
21
+ export const DEFAULT_STAGE_RECEIPT = "src-tauri/binaries/stage-sidecar.json";
22
+
23
+ export class StageReceiptError extends Error {
24
+ constructor(message, details = {}) { super(message); this.name = "StageReceiptError"; this.code = "RK_STAGE_RECEIPT"; Object.assign(this, details); }
25
+ }
26
+ const fail = (message, details) => { throw new StageReceiptError(message, details); };
27
+ const sha256Of = (fs, file) => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
28
+
29
+ function contained(root, relative, label) {
30
+ if (typeof relative !== "string" || !relative || path.isAbsolute(relative) || path.win32.isAbsolute(relative) || /^[A-Za-z]:/.test(relative) || relative.split(/[\\/]/).includes("..")) fail(`${label} must be a relative path inside the app: ${JSON.stringify(relative)}`);
31
+ return path.resolve(root, relative);
32
+ }
33
+
34
+ function loadReceipt({ root, receiptPath, target, fs }) {
35
+ const file = contained(root, receiptPath, "receiptPath");
36
+ let raw;
37
+ try { raw = JSON.parse(String(fs.readFileSync(file, "utf8"))); } catch (error) { fail(`cannot read the stage receipt ${file}: ${error.message}`); }
38
+ try { validateStageSidecarReceipt(raw, target ? { target } : {}); } catch (error) { fail(error.message); }
39
+ return { receipt: raw, file };
40
+ }
41
+
42
+ /** Rows that are staged files themselves (not the per-arch thin slices of a universal row). */
43
+ const mainRows = (receipt) => receipt.files.filter((row) => row.sliceOf === undefined);
44
+
45
+ function verifyRow(root, row, fs) {
46
+ const file = path.resolve(root, row.path);
47
+ const info = fs.lstatSync(file, { throwIfNoEntry: false });
48
+ if (!info) fail(`${row.name}: the staged file ${row.path} is missing`, { name: row.name });
49
+ if (info.isSymbolicLink() || !info.isFile()) fail(`${row.name}: ${row.path} is not a regular file`, { name: row.name });
50
+ const actual = sha256Of(fs, file);
51
+ if (actual !== row.sha256) fail(`${row.name}: ${row.path} has sha256 ${actual}, the receipt row says ${row.sha256}; the staged file changed after it was staged`, { name: row.name, expected: row.sha256, actual });
52
+ return file;
53
+ }
54
+
55
+ export function readVerifiedStageReceipt({ root, receiptPath = DEFAULT_STAGE_RECEIPT, target, profile, mode, names, kind, fs = nodeFs } = {}) {
56
+ if (typeof root !== "string" || !path.isAbsolute(root)) fail("root must be the absolute app root");
57
+ if (!Array.isArray(names) || !names.length || names.some((name) => typeof name !== "string" || !name)) fail("names must be a non-empty list of receipt row names");
58
+ const { receipt } = loadReceipt({ root, receiptPath, target, fs });
59
+ if (mode !== undefined) {
60
+ if (receipt.mode === undefined) fail(`the receipt records no build mode, so it cannot be accepted for a ${mode} build; stage again`);
61
+ if (receipt.mode !== mode) fail(`the receipt was staged in ${receipt.mode} mode, not ${mode}`, { expected: mode, actual: receipt.mode });
62
+ }
63
+ const out = {};
64
+ for (const name of names) {
65
+ const rows = mainRows(receipt).filter((row) => row.name === name && (kind === undefined || row.kind === kind));
66
+ if (rows.length !== 1) fail(`the receipt has ${rows.length} row(s) named ${name}${kind ? ` of kind ${kind}` : ""}, expected exactly one`, { name });
67
+ const [row] = rows;
68
+ if (profile !== undefined && row.profile !== profile) fail(`${name} was staged with Cargo profile ${row.profile === undefined ? "(none recorded)" : row.profile}, not ${profile}`, { name, expected: profile, actual: row.profile });
69
+ out[name] = { path: verifyRow(root, row, fs), sha256: row.sha256 };
70
+ }
71
+ return out;
72
+ }
73
+
74
+ /** Validate `sign.stageReceipt`; returns { receipt, bind } (bind: array of [file, rowName]). */
75
+ export function validateStageReceiptConfig(value, label = "sign.stageReceipt") {
76
+ if (value === null || typeof value !== "object" || Array.isArray(value)) fail(`${label} must be { receipt, bind? }`);
77
+ const unknown = Object.keys(value).filter((key) => !["receipt", "bind"].includes(key));
78
+ if (unknown.length) fail(`${label} has unknown key(s): ${unknown.join(", ")} (allowed: receipt, bind)`);
79
+ const receipt = value.receipt === undefined ? DEFAULT_STAGE_RECEIPT : value.receipt;
80
+ contained(path.sep === "\\" ? "C:\\app" : "/app", receipt, `${label}.receipt`);
81
+ const bind = value.bind === undefined ? {} : value.bind;
82
+ if (bind === null || typeof bind !== "object" || Array.isArray(bind)) fail(`${label}.bind must map payload file paths to receipt row names`);
83
+ const pairs = Object.entries(bind).map(([file, name]) => {
84
+ contained(path.sep === "\\" ? "C:\\app" : "/app", file, `${label}.bind key`);
85
+ if (typeof name !== "string" || !name) fail(`${label}.bind[${JSON.stringify(file)}] must be a receipt row name`);
86
+ return [file, name];
87
+ });
88
+ return { receipt, bind: pairs };
89
+ }
90
+
91
+ /** The release-time guard. Throws StageReceiptError naming every problem; returns { rows, bound } when it passes. */
92
+ export function assertStageReceiptGuard({ root, config, mode = "release", target, fs = nodeFs } = {}) {
93
+ const { receipt: receiptPath, bind } = validateStageReceiptConfig(config);
94
+ const { receipt } = loadReceipt({ root, receiptPath, target, fs });
95
+ const problems = [];
96
+ if (mode === "release") {
97
+ if (receipt.mode !== "release") problems.push(receipt.mode === undefined ? "the receipt records no build mode (a release needs a receipt staged in release mode)" : `the receipt was staged in ${receipt.mode} mode; a release build refuses a ${receipt.mode} receipt`);
98
+ for (const row of mainRows(receipt)) if (row.profile !== undefined && row.profile !== "release") problems.push(`${row.name} was staged with Cargo profile ${row.profile}; a release build needs release`);
99
+ }
100
+ const rows = mainRows(receipt);
101
+ for (const row of rows) { try { verifyRow(root, row, fs); } catch (error) { problems.push(error.message); } }
102
+ const bound = [];
103
+ for (const [file, name] of bind) {
104
+ const row = rows.find((item) => item.name === name);
105
+ if (!row) { problems.push(`${file} is bound to ${name}, which has no row in the receipt`); continue; }
106
+ const full = contained(root, file, "bound file");
107
+ const info = fs.lstatSync(full, { throwIfNoEntry: false });
108
+ if (!info || info.isSymbolicLink() || !info.isFile()) { problems.push(`${file} (bound to ${name}) is missing or not a regular file`); continue; }
109
+ const actual = sha256Of(fs, full);
110
+ if (actual !== row.sha256) problems.push(`${file} (bound to ${name}) has sha256 ${actual}, the receipt says ${row.sha256}: the hand-assembled copy is not the staged file`);
111
+ else bound.push({ file, name, sha256: actual });
112
+ }
113
+ if (problems.length) fail(`the stage receipt guard refused signing:\n${problems.map((line) => `- ${line}`).join("\n")}`, { problems });
114
+ return { rows: rows.length, bound };
115
+ }
package/stage-sidecar.mjs CHANGED
@@ -5,13 +5,13 @@
5
5
  // that script, driven by a `sidecars` list in right-release.config.mjs:
6
6
  //
7
7
  // sidecars: [
8
- // { kind: "cargo-bin", package: "mailright-engine", bin?, name?, profile?: "release" | { dev, release }, features?, manifestPath?, sha256?, dest?, clean?, platforms? },
8
+ // { kind: "cargo-bin", package: "mailright-engine", bin?, name?, profile?: "release" | { dev, release }, features?, manifestPath? (app-relative, or ../.. to a Cargo.toml inside the same repository), sha256?, dest?, clean?, platforms? },
9
9
  // { kind: "ffmpeg", variant?, variants?, tools?, notices: { dir, sourceOfferContact }, catalog, stage?, bundleDir?, resourceDir?, sources?, probe? },
10
10
  // { kind: "onnxruntime", version, catalog, resourceDir?: "src-tauri/resources/runtime", as?, licenseDir?, cacheDir?, companions? }, // the alias of native-library { library: "onnxruntime" }
11
11
  // { kind: "native-library", library: "onnxruntime" | "directml" | "pdfium" | "whisper-cpp" | "ggml" | "sherpa-onnx", version, catalog, resourceDir?, licenseDir?, cacheDir?, as?, files?, companions?, source?: { dir }, platforms? },
12
12
  // { kind: "resource", from, to, sha256?, machO?, clean?, platforms? }, // `from` may be a directory (copied recursively, every file hashed)
13
- // { kind: "command", name, cmd, args?, cwd?, output, externalBin: true | (false with dest), dest?, clean?, platforms? },
14
- // { kind: "remote", name, url (https), sha256, dest | to, size?, extract?, memberSha256?, executable?, clean?, platforms? },
13
+ // { kind: "command", name, cmd, args?, cwd?, output (a file, or a directory with dest), externalBin: true | (false with dest), dest?, sha256? (pins a file output), clean?, platforms? },
14
+ // { kind: "remote", name, url (https), sha256 | latest: { checksums (https), file? } (dev builds only), dest | to, size?, extract? | extractTree? (a whole archive tree into dest: Chrome for Testing), memberSha256?, executable?, clean?, platforms? },
15
15
  // { kind: "cmake", name, repo (https), commit (40 hex), target?, output?, cmakeArgs?, platformArgs?, generator?, platformGenerators?, architecture?, cmakeBin?, smoke?, sha256?, dest?, clean?, platforms? },
16
16
  // { kind: "prebuilt", name, from? (a path, or { aarch64, x86_64 } for universal-apple-darwin), manifest: { file, entry, sha256?, approvalSha256?, approvalAlgorithm? }, dest?, platforms? },
17
17
  // ]
@@ -48,6 +48,7 @@ import {
48
48
  import { ContentDigestError, contentIdentity, digestFor } from "./content-digest.mjs";
49
49
  import { oneOutput } from "./cross-targets.mjs";
50
50
 
51
+ export { readVerifiedStageReceipt, assertStageReceiptGuard } from "./stage-receipt.mjs";
51
52
  export const STAGE_SIDECAR_CONTRACT = "rightkit-stage-sidecar-v1";
52
53
  export const STAGE_SIDECAR_RECEIPT_NAME = "stage-sidecar.json";
53
54
  export const DEFAULT_STAGE_DIR = "src-tauri/binaries";
@@ -113,8 +114,8 @@ const KEYS = Object.freeze({
113
114
  onnxruntime: ["kind", "version", "catalog", "resourceDir", "as", "licenseDir", "cacheDir", "companions", "platforms"],
114
115
  "native-library": ["kind", "library", "version", "catalog", "resourceDir", "licenseDir", "cacheDir", "as", "files", "companions", "source", "platforms"],
115
116
  resource: ["kind", "from", "to", "sha256", "machO", "clean", "platforms"],
116
- command: ["kind", "name", "cmd", "args", "cwd", "output", "externalBin", "dest", "clean", "platforms"],
117
- remote: ["kind", "name", "url", "sha256", "dest", "to", "size", "extract", "extractKind", "memberSha256", "executable", "clean", "platforms"],
117
+ command: ["kind", "name", "cmd", "args", "cwd", "output", "externalBin", "dest", "sha256", "clean", "platforms"],
118
+ remote: ["kind", "name", "url", "sha256", "latest", "dest", "to", "size", "extract", "extractTree", "extractKind", "memberSha256", "executable", "clean", "platforms"],
118
119
  cmake: ["kind", "name", "repo", "commit", "target", "output", "cmakeArgs", "platformArgs", "generator", "platformGenerators", "architecture", "cmakeBin", "smoke", "sha256", "dest", "clean", "platforms"],
119
120
  prebuilt: ["kind", "name", "from", "manifest", "dest", "platforms"],
120
121
  });
@@ -158,6 +159,46 @@ function relativePath(value, label, errors, { allowRoot = false } = {}) {
158
159
  return normalized.replace(/\/+$/, "");
159
160
  }
160
161
 
162
+ /**
163
+ * A cargo-bin `manifestPath`: app-relative like every path here, or (rightkit#1247) a path that climbs out of the app with `..` to the Cargo.toml of
164
+ * a workspace elsewhere in the SAME repository (CodeRight's engine at ../../engine). The latter must name a `Cargo.toml`; whether the climb stays
165
+ * inside the repository is judged against the repository root at stage time (`manifestFileOf`), so a manifest outside it is still refused.
166
+ */
167
+ function manifestPathOf(value, label, errors) {
168
+ if (typeof value === "string" && !path.isAbsolute(value) && !/^[A-Za-z]:/.test(value) && value.replaceAll("\\", "/").split("/").includes("..")) {
169
+ const normalized = path.posix.normalize(value.replaceAll("\\", "/"));
170
+ if (!/(^|\/)Cargo\.toml$/.test(normalized)) { errors.push(`${label} must name a Cargo.toml when it leaves the app: ${value}`); return undefined; }
171
+ return normalized;
172
+ }
173
+ return relativePath(value, label, errors);
174
+ }
175
+
176
+ /** The repository root above the app: the nearest ancestor of `start` holding a `.git` entry (a directory, or a file for a linked checkout). Undefined when there is none. */
177
+ function repositoryRootOf(fs, start) {
178
+ for (let current = path.resolve(start); ; current = path.dirname(current)) {
179
+ if (fs.existsSync(path.join(current, ".git"))) return current;
180
+ if (path.dirname(current) === current) return undefined;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * The absolute manifest of a cargo-bin entry. A path with `..` must resolve inside the repository (the real path, so a link cannot reach outside) and name
186
+ * a file that exists; with no repository root above the app (no `.git`) it is refused rather than guessed.
187
+ */
188
+ function manifestFileOf(ctx, entry) {
189
+ if (!entry.manifestPath) return undefined;
190
+ const file = path.resolve(ctx.appRoot, entry.manifestPath);
191
+ if (!entry.manifestPath.split("/").includes("..")) return file;
192
+ const { fs } = ctx;
193
+ const root = repositoryRootOf(fs, ctx.appRoot) ?? (ctx.cacheRoot ? repositoryRootOf(fs, ctx.cacheRoot) : undefined);
194
+ if (!root) fail("STAGE_SIDECAR_CONFIG_INVALID", `cargo-bin ${entry.package}: manifestPath ${entry.manifestPath} leaves the app, and no repository root (.git) was found above ${ctx.appRoot} to bound it`, { package: entry.package });
195
+ if (!fs.existsSync(file)) fail("STAGE_SIDECAR_CONFIG_INVALID", `cargo-bin ${entry.package}: manifestPath ${entry.manifestPath} does not exist (${file})`, { package: entry.package });
196
+ const real = (value) => (typeof fs.realpathSync === "function" ? fs.realpathSync(value) : value);
197
+ const inside = path.relative(real(root), real(file));
198
+ if (inside === "" || inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) fail("STAGE_SIDECAR_CONFIG_INVALID", `cargo-bin ${entry.package}: manifestPath ${entry.manifestPath} resolves outside the repository ${root}`, { package: entry.package });
199
+ return file;
200
+ }
201
+
161
202
  /** A relative output path in comparison form: no "." or empty segments, lower case (Windows and macOS are case-insensitive). */
162
203
  const canonicalOutput = (value) => String(value).replaceAll("\\", "/").split("/").filter((segment) => segment !== "" && segment !== ".").join("/").toLowerCase();
163
204
  /** The claim in `claimed` that `key` equals, contains or sits inside (outputs may not be nested inside each other). */
@@ -385,7 +426,7 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
385
426
  if (badList(item.features ?? [])) errors.push(`${where}: features must be a list of feature names (package/feature allowed)`);
386
427
  if (badList(devFeatures)) errors.push(`${where}: devFeatures must be a list of feature names (package/feature allowed)`);
387
428
  const features = [...(item.features ?? []), ...(mode === "dev" && Array.isArray(devFeatures) ? devFeatures : [])];
388
- const manifestPath = item.manifestPath === undefined ? undefined : relativePath(item.manifestPath, `${where}: manifestPath`, errors);
429
+ const manifestPath = item.manifestPath === undefined ? undefined : manifestPathOf(item.manifestPath, `${where}: manifestPath`, errors);
389
430
  sha(item.sha256, "sha256");
390
431
  const dest = destOf(item.dest);
391
432
  const clean = cleanOf();
@@ -473,20 +514,49 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
473
514
  const output = relativePath(item.output, `${where}: output`, errors);
474
515
  const dest = destOf(item.dest);
475
516
  const clean = cleanOf();
517
+ sha(item.sha256, "sha256");
476
518
  if (dest) { if (item.externalBin === true) errors.push(`${where}: externalBin must be false or omitted with dest (a dest file is not staged as <name>-<triple>)`); }
477
519
  else if (item.externalBin !== true) errors.push(`${where}: externalBin must be true (the output is staged as <name>-<triple>)`);
478
520
  if (!skipped) { if (dest) claim(dest, where); else if (typeof name === "string" && stageDir) claim(stagedClaim(name), where); }
479
- Object.assign(entry, { name, cmd: item.cmd, args: Array.isArray(args) ? [...args] : [], ...(cwd ? { cwd } : {}), output, ...(dest ? { dest } : {}), ...(clean ? { clean } : {}) });
521
+ Object.assign(entry, { name, cmd: item.cmd, args: Array.isArray(args) ? [...args] : [], ...(cwd ? { cwd } : {}), output, ...(item.sha256 ? { sha256: item.sha256 } : {}), ...(dest ? { dest } : {}), ...(clean ? { clean } : {}) });
480
522
  } else if (item.kind === "remote") {
481
523
  const name = item.name;
482
524
  if (typeof name !== "string" || !NAME.test(name)) errors.push(`${where}: name must be a bare label`);
483
525
  if (typeof item.url !== "string" || !/^https:\/\/[^\s/]+\/\S*$/.test(item.url)) errors.push(`${where}: url must be an https:// URL (no other scheme is fetched)`);
484
- if (typeof item.sha256 !== "string" || !SHA256.test(item.sha256)) errors.push(`${where}: sha256 is required and must be a lowercase 64-hex SHA-256`);
526
+ // `latest` (rightkit#753): for a tool that updates itself (yt-dlp), a DEV stage may follow the publisher's latest release. The digest is not
527
+ // dropped: it is read from the publisher's checksum list (an https file of `<sha256> <name>` lines), compared with the download, and recorded
528
+ // in the receipt, so a release can pin it. A release never stages an unpinned download.
529
+ let latest;
530
+ if (item.latest !== undefined) {
531
+ if (item.sha256 !== undefined) errors.push(`${where}: give sha256 or latest, not both`);
532
+ if (!isObject(item.latest)) errors.push(`${where}: latest must be { checksums, file? }`);
533
+ else {
534
+ for (const key of Object.keys(item.latest)) if (!["checksums", "file"].includes(key)) errors.push(`${where}: latest: unknown key ${JSON.stringify(key)} (allowed: checksums, file)`);
535
+ if (typeof item.latest.checksums !== "string" || !/^https:\/\/[^\s/]+\/\S*$/.test(item.latest.checksums)) errors.push(`${where}: latest.checksums must be an https:// URL of the publisher's SHA-256 list`);
536
+ if (item.latest.file !== undefined && (typeof item.latest.file !== "string" || !item.latest.file || /[\\/\s]/.test(item.latest.file))) errors.push(`${where}: latest.file must be the bare file name listed in the checksum file (default: the last segment of url)`);
537
+ if (item.extract !== undefined || item.extractKind !== undefined) errors.push(`${where}: latest cannot be combined with extract (an archive is pinned by sha256)`);
538
+ if (mode !== "dev" && !skipped) errors.push(`${where}: latest is a dev-only policy (RIGHTKIT_BUILD_MODE=dev); a release build pins sha256 (the dev stage records the resolved digest in the receipt)`);
539
+ latest = { checksums: item.latest.checksums, ...(item.latest.file ? { file: item.latest.file } : {}) };
540
+ }
541
+ } else if (typeof item.sha256 !== "string" || !SHA256.test(item.sha256)) errors.push(`${where}: sha256 is required (or latest, in a dev build) and must be a lowercase 64-hex SHA-256`);
485
542
  if (item.dest !== undefined && item.to !== undefined) errors.push(`${where}: give dest or to, not both`);
486
543
  if (item.dest === undefined && item.to === undefined) errors.push(`${where}: dest (or to) is required`);
487
544
  const dest = destOf(item.dest ?? item.to, item.dest === undefined ? "to" : "dest");
488
545
  if (item.size !== undefined && (!Number.isSafeInteger(item.size) || item.size <= 0)) errors.push(`${where}: size must be a positive integer (bytes)`);
489
546
  if (item.extract !== undefined) { const member = normalizeArchiveMember(item.extract); if (member.error || (!member.byPath && !NAME.test(member.value))) errors.push(`${where}: extract must be the bare file name of one archive member or its archive path (posix, no leading /, no .. segment): ${member.error ?? "invalid file name"}`); }
547
+ let extractTree;
548
+ if (item.extractTree !== undefined) {
549
+ // A whole archive tree (Chrome for Testing, a browser or runtime bundle): the archive digest is the pin, every extracted file is hashed into the receipt.
550
+ if (item.extract !== undefined || item.extractKind !== undefined || item.memberSha256 !== undefined || item.executable !== undefined) errors.push(`${where}: extractTree cannot be combined with extract, extractKind, memberSha256 or executable`);
551
+ if (item.latest !== undefined) errors.push(`${where}: extractTree needs a pinned sha256, not latest`);
552
+ if (item.extractTree === true || item.extractTree === ".") extractTree = ".";
553
+ else if (typeof item.extractTree === "string") {
554
+ const root = normalizeArchiveMember(item.extractTree.replace(/\/+$/, ""));
555
+ if (root.error) errors.push(`${where}: extractTree must be true (the whole archive) or the directory inside the archive to stage (posix, no leading /, no .. segment): ${root.error}`);
556
+ else extractTree = root.value;
557
+ } else errors.push(`${where}: extractTree must be true or an archive directory path`);
558
+ if (item.dest === undefined && item.to === undefined) errors.push(`${where}: extractTree needs dest (the directory the tree is staged into)`);
559
+ }
490
560
  if (item.memberSha256 !== undefined && (item.extract === undefined || !SHA256.test(item.memberSha256 ?? ""))) errors.push(`${where}: memberSha256 must be a lowercase 64-hex SHA-256 and needs extract`);
491
561
  if (item.extractKind !== undefined && item.extractKind !== "nsis") errors.push(`${where}: extractKind must be "nsis" (omit it for tar-readable zip/tgz/nupkg archives)`);
492
562
  if (item.extractKind === "nsis") {
@@ -496,7 +566,7 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
496
566
  if (item.executable !== undefined && typeof item.executable !== "boolean") errors.push(`${where}: executable must be a boolean`);
497
567
  const clean = cleanOf();
498
568
  if (dest && !skipped) claim(dest, where);
499
- Object.assign(entry, { name, url: item.url, sha256: item.sha256, dest, ...(item.extractKind ? { extractKind: item.extractKind } : {}), ...(item.size ? { size: item.size } : {}), ...(item.extract ? { extract: item.extract } : {}), ...(item.memberSha256 ? { memberSha256: item.memberSha256 } : {}), ...(item.executable ? { executable: true } : {}), ...(clean ? { clean } : {}) });
569
+ Object.assign(entry, { name, url: item.url, ...(latest ? { latest } : { sha256: item.sha256 }), dest, ...(item.extractKind ? { extractKind: item.extractKind } : {}), ...(item.size ? { size: item.size } : {}), ...(item.extract ? { extract: item.extract } : {}), ...(extractTree ? { extractTree } : {}), ...(item.memberSha256 ? { memberSha256: item.memberSha256 } : {}), ...(item.executable ? { executable: true } : {}), ...(clean ? { clean } : {}) });
500
570
  } else if (item.kind === "cmake") {
501
571
  const name = item.name;
502
572
  if (typeof name !== "string" || !NAME.test(name) || /\.exe$/i.test(name) || name !== path.basename(name)) errors.push(`${where}: name must be a bare sidecar name (no path, no .exe, no target triple)`);
@@ -574,7 +644,7 @@ export function validateSidecarManifest(raw, { target, mode = "release" } = {})
574
644
  if (hit) errors.push(`${label} writes ${output}, which is or contains ${hit}; stage-sidecar never overwrites or cleans the app's stage directory, receipt, cache, .git, src, src-tauri, node_modules or package.json`);
575
645
  }
576
646
  if (errors.length) fail("STAGE_SIDECAR_CONFIG_INVALID", `invalid sidecars configuration:\n${errors.map((line) => `- ${line}`).join("\n")}`, { errors });
577
- return { target: t, stageDir, receiptPath, wipeStageDir: wrapper.wipeStageDir === true, entries, claims: claimed };
647
+ return { target: t, mode, stageDir, receiptPath, wipeStageDir: wrapper.wipeStageDir === true, entries, claims: claimed };
578
648
  }
579
649
 
580
650
  const sha256Of = (bytes) => createHash("sha256").update(bytes).digest("hex");
@@ -639,6 +709,27 @@ export function defaultExtractMember({ archive, fileName, destDir, run = default
639
709
  return out;
640
710
  }
641
711
 
712
+ /**
713
+ * Extract a whole archive (zip, tgz) into `destDir` and return the directory to stage: `<destDir>/<root>` for an `extractTree` of a sub directory, else `destDir`.
714
+ * The member list is read first and refused when any member is absolute, has a `..` segment or a drive prefix, so nothing can land outside `destDir`.
715
+ */
716
+ export function defaultExtractTree({ archive, root = ".", destDir, run = defaultRun, tar = archiveTar() }) {
717
+ const listing = run(tar, ["-tf", archive], { cwd: path.dirname(archive) });
718
+ if (listing.status !== 0) fail("STAGE_SIDECAR_EXTRACT_FAILED", `cannot list ${archive}`);
719
+ const lines = String(listing.stdout).split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
720
+ if (!lines.length) fail("STAGE_SIDECAR_EXTRACT_FAILED", `${archive} is empty`);
721
+ for (const line of lines) {
722
+ const member = line.startsWith("./") ? line.slice(2) : line;
723
+ if (member.startsWith("/") || /^[A-Za-z]:/.test(member) || member.includes("\\") || member.split("/").includes("..")) fail("STAGE_SIDECAR_EXTRACT_FAILED", `${archive} has an unsafe member ${JSON.stringify(line)}; nothing staged`);
724
+ }
725
+ const extracted = run(tar, ["-xf", archive, "-C", destDir], { cwd: path.dirname(archive) });
726
+ if (extracted.status !== 0) fail("STAGE_SIDECAR_EXTRACT_FAILED", `cannot extract ${archive}`);
727
+ const out = root === "." ? destDir : path.join(destDir, ...root.split("/"));
728
+ const inside = path.relative(path.resolve(destDir), path.resolve(out));
729
+ if (inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside)) fail("STAGE_SIDECAR_EXTRACT_FAILED", `${root} of ${archive} resolves outside the extraction directory`);
730
+ return out;
731
+ }
732
+
642
733
  /** 7-Zip candidates: an explicit path (deps.sevenZip or RIGHTKIT_SEVEN_ZIP), then `7z` on PATH, then 7z.exe under Program Files on win32. */
643
734
  export function sevenZipCandidates({ explicit, env = process.env, platform = process.platform } = {}) {
644
735
  const list = [];
@@ -991,7 +1082,8 @@ function stageCargoSlice(entry, ctx, triple, { dest }) {
991
1082
  function stageCargoBuild(entry, ctx, triple) {
992
1083
  const { run, appRoot, env, fs } = ctx;
993
1084
  // One output directory (oneOutput, cross-targets.mjs): a sidecar always builds with the release profile, whatever profile its entry names.
994
- const args = oneOutput(["cargo", "build", "--locked", ...(entry.manifestPath ? ["--manifest-path", path.resolve(appRoot, entry.manifestPath)] : []),
1085
+ const manifestFile = manifestFileOf(ctx, entry);
1086
+ const args = oneOutput(["cargo", "build", "--locked", ...(manifestFile ? ["--manifest-path", manifestFile] : []),
995
1087
  "-p", entry.package, "--bin", entry.bin, "--target", triple,
996
1088
  ...(entry.features.length ? ["--features", entry.features.join(",")] : []), "--message-format=json-render-diagnostics"]);
997
1089
  ctx.log(`stage-sidecar: rightkit ${args.join(" ")}`);
@@ -1003,7 +1095,7 @@ function stageCargoBuild(entry, ctx, triple) {
1003
1095
  // the directory the binary is read from is the signed receipt's `outputDir`, never a carrier-less `cargo metadata`.
1004
1096
  const carried = Boolean(carriedCargoMapOf(env)?.map);
1005
1097
  if (ctx.split && !carried) {
1006
- const pinned = snapshotTargetDirectory(ctx, env, entry.manifestPath ? path.resolve(appRoot, entry.manifestPath) : null);
1098
+ const pinned = snapshotTargetDirectory(ctx, env, manifestFile ?? null);
1007
1099
  if (!pinned.dir) fail("STAGE_SIDECAR_BUILD_FAILED", `the cargo output directory for ${entry.package} cannot be resolved from the snapshot (${pinned.error}); nothing was built`, { package: entry.package });
1008
1100
  buildEnv = { ...env, CARGO_TARGET_DIR: pinned.dir };
1009
1101
  }
@@ -1017,7 +1109,7 @@ function stageCargoBuild(entry, ctx, triple) {
1017
1109
  source = candidates.find((file) => fs.existsSync(file));
1018
1110
  if (!source) fail("STAGE_SIDECAR_BINARY_NOT_FOUND", `the build did not produce ${entry.bin} (looked in ${candidates.join(", ")})`, { bin: entry.bin, candidates });
1019
1111
  } else if (!source || !fs.existsSync(source)) {
1020
- const meta = run("rustright", ["cargo", "metadata", "--format-version", "1", "--no-deps", ...(entry.manifestPath ? ["--manifest-path", path.resolve(appRoot, entry.manifestPath)] : [])], { cwd: appRoot, env: buildEnv });
1112
+ const meta = run("rustright", ["cargo", "metadata", "--format-version", "1", "--no-deps", ...(manifestFile ? ["--manifest-path", manifestFile] : [])], { cwd: appRoot, env: buildEnv });
1021
1113
  let targetDir;
1022
1114
  try { targetDir = JSON.parse(meta.stdout).target_directory; } catch { /* refused below */ }
1023
1115
  if (meta?.status !== 0 || typeof targetDir !== "string" || !path.isAbsolute(targetDir)) targetDir = undefined;
@@ -1611,6 +1703,25 @@ function stageResource(entry, ctx) {
1611
1703
  return [{ kind: "resource", name: path.basename(dest), path: rel(ctx, dest), ...copied, sourceSha256: actual, from: entry.from, externalBin: false }];
1612
1704
  }
1613
1705
 
1706
+ /** A `command` entry whose output is a directory: needs `dest`, takes no sha256 pin, and stages every file under it (one receipt row each). */
1707
+ function stageCommandDirectory(entry, ctx, source) {
1708
+ const { appRoot, fs } = ctx;
1709
+ if (!entry.dest) fail("STAGE_SIDECAR_CONFIG_INVALID", `command ${entry.name} produced a directory (${entry.output}); a directory output needs dest (it cannot be staged as <name>-<triple>)`, { name: entry.name });
1710
+ if (entry.sha256) fail("STAGE_SIDECAR_CONFIG_INVALID", `command ${entry.name} output ${entry.output} is a directory; sha256 pins one file, so drop it (every file is hashed into the receipt)`, { name: entry.name });
1711
+ if (ctx.target.arch === "universal") fail("STAGE_SIDECAR_CONFIG_INVALID", `command ${entry.name}: a directory output cannot be a universal binary; use a file output`, { name: entry.name });
1712
+ const members = listFilesRecursive(fs, source);
1713
+ if (!members.length) fail("STAGE_SIDECAR_BINARY_NOT_FOUND", `command ${entry.name} output directory ${entry.output} contains no files`, { name: entry.name, output: entry.output });
1714
+ const destRoot = path.resolve(appRoot, entry.dest);
1715
+ cleanDest(ctx, entry, destRoot, { directory: true });
1716
+ return members.map((member) => {
1717
+ const from = path.join(source, ...member.split("/"));
1718
+ const dest = path.join(destRoot, ...member.split("/"));
1719
+ const sourceSha256 = sha256Of(fs.readFileSync(from));
1720
+ const copied = copyInto(ctx, from, dest, { executable: false });
1721
+ return { kind: "command", name: entry.name, path: rel(ctx, dest), ...copied, sourceSha256, output: `${entry.output}/${member}`, externalBin: false };
1722
+ });
1723
+ }
1724
+
1614
1725
  /** Run the entry's command (argv, no shell), then stage its output as <name>-<triple>. */
1615
1726
  function stageCommand(entry, ctx) {
1616
1727
  const { appRoot, fs, run, env } = ctx;
@@ -1620,14 +1731,26 @@ function stageCommand(entry, ctx) {
1620
1731
  const built = runStep(ctx, entry.cmd, entry.args, { cwd, env: splitCommandEnv(ctx) });
1621
1732
  if (built?.error || built?.status !== 0) fail("STAGE_SIDECAR_BUILD_FAILED", `command ${entry.name} (${entry.cmd}) failed (${built?.error?.message ?? `exit ${built?.status}`})`, { name: entry.name, stderr: tail(built?.stderr) });
1622
1733
  const source = path.resolve(appRoot, entry.output);
1734
+ // A directory output (a runtime tree, a browser build) is copied to `dest` file by file, every file hashed into the receipt (rightkit#753).
1735
+ if (fs.existsSync(source) && fs.statSync(source).isDirectory()) return stageCommandDirectory(entry, ctx, source);
1623
1736
  if (!fs.existsSync(source) || !fs.statSync(source).isFile()) fail("STAGE_SIDECAR_BINARY_NOT_FOUND", `command ${entry.name} did not produce ${entry.output}`, { name: entry.name, output: entry.output });
1624
1737
  if (ctx.target.arch === "universal") requireUniversalFile(ctx, source, `command ${entry.name} output ${entry.output}`);
1625
1738
  const sourceSha256 = sha256Of(fs.readFileSync(source));
1739
+ // A pinned output (sha256 declared) is the bytes the command must produce: any other result stages nothing (rightkit#753).
1740
+ if (entry.sha256 && entry.sha256 !== sourceSha256) fail("STAGE_SIDECAR_HASH_MISMATCH", `command ${entry.name} produced ${entry.output} as ${sourceSha256}, expected ${entry.sha256}; nothing staged`, { name: entry.name, expected: entry.sha256, actual: sourceSha256 });
1626
1741
  const dest = destFor(entry, ctx);
1627
1742
  const copied = copyInto(ctx, source, dest, { executable: true });
1628
1743
  return [{ kind: "command", name: entry.name, path: rel(ctx, dest), ...copied, sourceSha256, output: entry.output, externalBin: !entry.dest }];
1629
1744
  }
1630
1745
 
1746
+ /** The shared, host-wide download cache directory (`RIGHT_RELEASE_DOWNLOAD_CACHE`, absolute), or null when none is set. */
1747
+ export function sharedDownloadCache(ctx) {
1748
+ const dir = ctx.env?.RIGHT_RELEASE_DOWNLOAD_CACHE;
1749
+ if (dir === undefined || dir === "") return null;
1750
+ if (typeof dir !== "string" || !path.isAbsolute(dir) || dir.split(/[\\/]/).includes("..")) fail("STAGE_SIDECAR_CONFIG_INVALID", "RIGHT_RELEASE_DOWNLOAD_CACHE must be an absolute directory path with no .. segment");
1751
+ return path.resolve(dir, "remote");
1752
+ }
1753
+
1631
1754
  /**
1632
1755
  * Download `{ url, sha256, size? }` into the content-addressed cache (`.right-release/cache/remote/<sha256>`). The bytes are
1633
1756
  * hashed before anything is written: the cache entry exists only from verified bytes. A mismatch (or a non-https redirect)
@@ -1635,8 +1758,15 @@ function stageCommand(entry, ctx) {
1635
1758
  */
1636
1759
  async function ensureCachedDownload(ctx, { url, sha256, size }) {
1637
1760
  const { fs } = ctx;
1638
- const cached = path.resolve(ctx.cacheRoot, REMOTE_CACHE_DIR, sha256);
1639
- if (fs.existsSync(cached) && sha256Of(fs.readFileSync(cached)) === sha256) return { cached, fromCache: true };
1761
+ // One download cache for every checkout of every app on this host (rightkit#753): RIGHT_RELEASE_DOWNLOAD_CACHE (an absolute directory) is looked up
1762
+ // first and is where a new download lands. The cache is content addressed and every read is re-hashed, so sharing it cannot serve a wrong byte; the
1763
+ // per-checkout `.right-release/cache/remote` stays the fallback and the home of a host with no shared cache set.
1764
+ const shared = sharedDownloadCache(ctx);
1765
+ const local = path.resolve(ctx.cacheRoot, REMOTE_CACHE_DIR, sha256);
1766
+ const cached = shared ? path.join(shared, sha256) : local;
1767
+ for (const candidate of shared ? [cached, local] : [local]) {
1768
+ if (fs.existsSync(candidate) && sha256Of(fs.readFileSync(candidate)) === sha256) return { cached: candidate, fromCache: true };
1769
+ }
1640
1770
  ctx.log(`stage-sidecar: GET ${url}`);
1641
1771
  let response;
1642
1772
  try { response = await ctx.fetch(url, { redirect: "follow" }); } catch (error) { fail("STAGE_SIDECAR_DOWNLOAD_FAILED", `GET ${url} failed: ${error.message}`, { cause: error, url }); }
@@ -1653,15 +1783,52 @@ async function ensureCachedDownload(ctx, { url, sha256, size }) {
1653
1783
  return { cached, fromCache: false };
1654
1784
  }
1655
1785
 
1786
+ /** A pinned archive staged as a directory tree: extract to a scratch directory, require `extractTree` to exist, copy every file into `dest`, one receipt row per file. */
1787
+ async function stageRemoteTree(entry, ctx, { cached, fromCache, dest }) {
1788
+ const { fs } = ctx;
1789
+ const scratch = ctx.makeTempDir();
1790
+ try {
1791
+ const root = await ctx.extractTree({ archive: cached, root: entry.extractTree, destDir: scratch });
1792
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) fail("STAGE_SIDECAR_EXTRACT_FAILED", `${entry.url} has no directory ${entry.extractTree}; nothing staged`, { name: entry.name });
1793
+ const members = listFilesRecursive(fs, root);
1794
+ if (!members.length) fail("STAGE_SIDECAR_EXTRACT_FAILED", `${entry.url} directory ${entry.extractTree} contains no files; nothing staged`, { name: entry.name });
1795
+ // Everything is verified before the destination is touched: a failed extraction never leaves a cleaned or half-staged directory.
1796
+ cleanDest(ctx, entry, dest, { directory: true });
1797
+ return members.map((member) => {
1798
+ const from = path.join(root, ...member.split("/"));
1799
+ const to = path.join(dest, ...member.split("/"));
1800
+ const sourceSha256 = sha256Of(fs.readFileSync(from));
1801
+ const copied = copyInto(ctx, from, to, { executable: false });
1802
+ return { kind: "remote", name: entry.name, path: rel(ctx, to), ...copied, sourceSha256, url: entry.url, cached: fromCache, externalBin: false, archiveSha256: entry.sha256, member: `${entry.extractTree === "." ? "" : `${entry.extractTree}/`}${member}` };
1803
+ });
1804
+ } finally { ctx.removeDir(scratch); }
1805
+ }
1806
+
1807
+ /** The publisher's SHA-256 for a `latest` remote: read from its https checksum list (`<sha256> <name>` or `<sha256> *<name>` lines). Nothing is guessed. */
1808
+ async function resolveLatestDigest(ctx, entry) {
1809
+ const name = entry.latest.file ?? decodeURIComponent(new URL(entry.url).pathname.split("/").filter(Boolean).pop() ?? "");
1810
+ ctx.log(`stage-sidecar: GET ${entry.latest.checksums} (latest digest of ${name})`);
1811
+ let response;
1812
+ try { response = await ctx.fetch(entry.latest.checksums, { redirect: "follow" }); } catch (error) { fail("STAGE_SIDECAR_DOWNLOAD_FAILED", `GET ${entry.latest.checksums} failed: ${error.message}`, { cause: error, url: entry.latest.checksums }); }
1813
+ if (!response?.ok) fail("STAGE_SIDECAR_DOWNLOAD_FAILED", `GET ${entry.latest.checksums} failed with ${response?.status}`, { url: entry.latest.checksums });
1814
+ if (typeof response.url === "string" && response.url && !response.url.startsWith("https://")) fail("STAGE_SIDECAR_DOWNLOAD_FAILED", `${entry.latest.checksums} redirected to a non-https URL: ${response.url}`, { url: entry.latest.checksums });
1815
+ const rows = String(await response.text()).split(/\r?\n/).flatMap((line) => { const match = /^([0-9a-fA-F]{64})\s+\*?(.+?)\s*$/.exec(line); return match ? [{ sha256: match[1].toLowerCase(), file: match[2] }] : []; });
1816
+ const hits = rows.filter((row) => row.file === name);
1817
+ if (hits.length !== 1) fail("STAGE_SIDECAR_HASH_MISMATCH", `${entry.latest.checksums} lists ${hits.length} row(s) for ${name} (exactly one is required); nothing staged`, { name });
1818
+ return hits[0].sha256;
1819
+ }
1820
+
1656
1821
  /**
1657
1822
  * A pinned https download. `dest` is copied only from the verified cache entry. With `extract` the download is an archive
1658
1823
  * (zip, tgz): the one member whose base name is `extract` (or, when `extract` contains `/`, whose archive path equals it) is unpacked (digest-checked against `memberSha256` when given) and
1659
1824
  * only that member is staged, so no `command` entry or shell is needed to unpack it.
1660
1825
  */
1661
- async function stageRemote(entry, ctx) {
1826
+ async function stageRemote(declared, ctx) {
1662
1827
  const { appRoot, fs } = ctx;
1828
+ const entry = declared.latest ? { ...declared, sha256: await resolveLatestDigest(ctx, declared) } : declared;
1663
1829
  const dest = path.resolve(appRoot, entry.dest);
1664
1830
  const { cached, fromCache } = await ensureCachedDownload(ctx, entry);
1831
+ if (entry.extractTree) return stageRemoteTree(entry, ctx, { cached, fromCache, dest });
1665
1832
  let source = cached;
1666
1833
  let scratch;
1667
1834
  try {
@@ -1679,7 +1846,7 @@ async function stageRemote(entry, ctx) {
1679
1846
  const copied = copyInto(ctx, source, dest, { executable: entry.executable === true });
1680
1847
  const expected = entry.extract ? entry.memberSha256 : entry.sha256;
1681
1848
  if (expected && copied.sha256 !== expected) fail("STAGE_SIDECAR_HASH_MISMATCH", `staged ${entry.dest} is ${copied.sha256}, expected ${expected}`, { expected, actual: copied.sha256 });
1682
- return [{ kind: "remote", name: entry.name, path: rel(ctx, dest), ...copied, sourceSha256: memberSha256 ?? entry.sha256, url: entry.url, cached: fromCache, externalBin: false, ...(entry.extract ? { archiveSha256: entry.sha256, member: entry.extract, memberSha256 } : {}), ...(entry.extractKind ? { extractKind: entry.extractKind } : {}) }];
1849
+ return [{ kind: "remote", name: entry.name, path: rel(ctx, dest), ...copied, sourceSha256: memberSha256 ?? entry.sha256, url: entry.url, cached: fromCache, externalBin: false, ...(declared.latest ? { latest: { checksums: declared.latest.checksums, resolvedSha256: entry.sha256 } } : {}), ...(entry.extract ? { archiveSha256: entry.sha256, member: entry.extract, memberSha256 } : {}), ...(entry.extractKind ? { extractKind: entry.extractKind } : {}) }];
1683
1850
  } finally {
1684
1851
  if (scratch) ctx.removeDir(scratch);
1685
1852
  }
@@ -1980,6 +2147,7 @@ export async function stageSidecars({ appRoot, manifest, target, cacheRoot, ifSt
1980
2147
  fetchBytes: deps.fetchBytes ?? defaultFetchBytes,
1981
2148
  fetch: deps.fetch ?? ((...args) => globalThis.fetch(...args)),
1982
2149
  extractMember: deps.extractMember ?? ((args) => defaultExtractMember({ ...args, run })),
2150
+ extractTree: deps.extractTree ?? ((args) => defaultExtractTree({ ...args, run })),
1983
2151
  extractNsisMember: deps.extractNsisMember ?? ((args) => defaultExtractNsisMember({ ...args, run, env, sevenZip: deps.sevenZip, readFile: fs.readFileSync, exists: fs.existsSync })),
1984
2152
  loadMediaCatalog: deps.loadMediaCatalog ?? (() => undefined),
1985
2153
  loadNativeCatalog: deps.loadNativeCatalog ?? (() => undefined),
@@ -2016,6 +2184,7 @@ export async function stageSidecars({ appRoot, manifest, target, cacheRoot, ifSt
2016
2184
  target: plan.target.triple,
2017
2185
  os: plan.target.os,
2018
2186
  arch: plan.target.arch,
2187
+ mode: plan.mode, // the build mode the files were staged in (dev | release): readVerifiedStageReceipt and the release guard read it back (rightkit#1039)
2019
2188
  stagedAt: (deps.now ?? (() => new Date().toISOString()))(),
2020
2189
  files,
2021
2190
  skipped,
@@ -2045,6 +2214,8 @@ function currentStageReceipt(plan, ctx) {
2045
2214
  const receiptFile = path.resolve(appRoot, plan.receiptPath);
2046
2215
  const receipt = validateStageSidecarReceipt(JSON.parse(fs.readFileSync(receiptFile, "utf8")), { target: plan.target.triple });
2047
2216
  const planned = plan.entries.filter((entry) => !entry.skipped);
2217
+ if (receipt.mode !== undefined && receipt.mode !== plan.mode) return null; // staged in another build mode: never reused
2218
+ if (planned.some((entry) => entry.latest)) return null; // a `latest` entry follows the publisher: it is re-resolved every run, never reused
2048
2219
  const skipped = plan.entries.filter((entry) => entry.skipped).map((entry) => ({ kind: entry.kind, index: entry.index, platforms: entry.platforms }));
2049
2220
  if (JSON.stringify(skipped) !== JSON.stringify(receipt.skipped ?? [])) return null;
2050
2221
  if (receipt.files.length < planned.length) return null;