@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
@@ -0,0 +1,241 @@
1
+ // RightKit's half of the Legion frozen-scope broker (bogusyogi/rightkit#799; protocol: Orthic-Labs/legion
2
+ // docs/architecture/frozen-scope-broker.md "Shared consumers & coverage boundary", pinned at 2a6597a7c932b8a636462a08a28ee9a28e7d49c6,
3
+ // implementation engine/bins/legion/src/commands/freeze.rs and freeze_consumer.rs).
4
+ //
5
+ // What this module is: the pure parts a RightKit owner needs to use the broker, with no authority of its own.
6
+ // 1. Broker requests (`legion authority freeze broker`, one JSON request on stdin, one JSON answer): status, check, push, consume.
7
+ // `check` is diagnostic (`deliveryLease: false`) and is never a grant; `push` sends an explicit immutable source object and is
8
+ // the only managed delivery. Enrollment (`admin-enroll`) is root-only and is not reachable from here.
9
+ // 2. The `legion-native-consume-v1` frames a native owner adapter speaks on the broker's private pipes (prepare, prepared, commit,
10
+ // complete), the exact PreparedEffect serialization the broker digests, and a one-transaction state machine that refuses any
11
+ // deviation (an unknown key, a wrong nonce, a second prepare, a commit digest that is not the prepared one).
12
+ // 3. The publication binding: the typed effect for a `Publish` consume is built from the SEALED release that publication already
13
+ // verifies (verifyPublicationRelease: sealed manifest, signing and notarization receipts, ownership evidence) and from the
14
+ // artifact bytes read once, so the artifact digest the broker authorizes is the digest of the bytes that are uploaded.
15
+ //
16
+ // What it is not: no broker is installed, no adapter is enrolled and no native adapter executable exists here. The broker accepts only
17
+ // a native ELF or Mach-O executable pinned by a root-owned enrollment and refuses scripts, so this module cannot be the adapter; a native
18
+ // adapter links this protocol. Nothing in this module runs a build, a push or an upload. See docs/GATE-CONTRACT.md [GC-I23].
19
+ import { createHash } from "node:crypto";
20
+ import { spawnSync } from "./background-process.mjs";
21
+
22
+ export const CONSUME_PROTOCOL = "legion-native-consume-v1";
23
+ /** Every frame, in both directions, is at most this many bytes (the broker's CAP), newline included. */
24
+ export const FRAME_CAP_BYTES = 32 * 1024;
25
+ export const CONSUME_OPERATIONS = Object.freeze(["Build", "Dequeue", "Publish"]);
26
+ const MAX_BROKER_ANSWER_BYTES = 1024 * 1024;
27
+ const DIGEST = /^[0-9a-f]{64}$/;
28
+ const OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
29
+
30
+ export class FreezeConsumerError extends Error {
31
+ constructor(code, message) { super(`[${code}] ${message}`); this.name = "FreezeConsumerError"; this.code = code; }
32
+ }
33
+ const refuse = (code, message) => { throw new FreezeConsumerError(code, message); };
34
+ const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
35
+ const sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
36
+
37
+ /** The broker's text rule: 1 to 1024 bytes, no control character. */
38
+ export const isBrokerText = (value) => typeof value === "string" && value.length > 0 && Buffer.byteLength(value) <= 1024 && !/[\u0000-\u001f\u007f-\u009f]/.test(value);
39
+ export const isDigest = (value) => typeof value === "string" && DIGEST.test(value);
40
+ /** A full object id: 40 or 64 lower-case hex digits and not all zero (an absent object). */
41
+ export const isObjectId = (value) => typeof value === "string" && OID.test(value) && !/^0+$/.test(value);
42
+
43
+ function exactKeys(value, keys, where) {
44
+ if (!isRecord(value)) refuse("FREEZE_FRAME_INVALID", `${where} must be a JSON object`);
45
+ const extra = Object.keys(value).filter((key) => !keys.includes(key));
46
+ const missing = keys.filter((key) => !Object.hasOwn(value, key));
47
+ if (extra.length || missing.length) refuse("FREEZE_FRAME_INVALID", `${where}: unknown key(s) [${extra.join(", ")}] or missing key(s) [${missing.join(", ")}]`);
48
+ }
49
+
50
+ // ---- 1. broker requests ---------------------------------------------------------------------------------------------------------
51
+ const requireId = (id) => { if (!isBrokerText(id)) refuse("FREEZE_REQUEST_INVALID", "the enrollment id must be non-empty text without control characters"); return id; };
52
+ const requireSource = (source) => { if (!isObjectId(source)) refuse("FREEZE_REQUEST_INVALID", "source must be an immutable full object id (40 or 64 lower-case hex digits), never a ref or a short id"); return source; };
53
+ const requireCandidate = (candidate) => { if (candidate !== undefined && candidate !== null && !isBrokerText(candidate)) refuse("FREEZE_REQUEST_INVALID", "candidate must be a prepared candidate key"); return candidate ?? null; };
54
+
55
+ /** The typed requests of `legion authority freeze broker`. Field names are the broker's (serde `op`, snake_case, unknown keys refused). */
56
+ export const brokerRequests = Object.freeze({
57
+ status: ({ id }) => ({ op: "status", id: requireId(id) }),
58
+ /** Diagnostic only: its answer carries `deliveryLease: false` and grants nothing a later upload may rely on. */
59
+ check: ({ id, source, candidate, operation }) => {
60
+ if (!["Build", "Dequeue", "Publish", "Push"].includes(operation)) refuse("FREEZE_REQUEST_INVALID", `operation must be one of Build, Dequeue, Publish, Push, not ${JSON.stringify(operation)}`);
61
+ return { op: "check", id: requireId(id), source: requireSource(source), candidate: requireCandidate(candidate), operation };
62
+ },
63
+ /** Managed delivery: the broker pushes this exact object to its enrolled URL and ref. The caller names no remote, ref or argv. */
64
+ push: ({ id, source, candidate }) => ({ op: "push", id: requireId(id), source: requireSource(source), candidate: requireCandidate(candidate) }),
65
+ /** A native owner transaction: the enrolled adapter, never a caller-chosen executable, prepares and performs the effect. */
66
+ consume: ({ id, operation, nativeRecordId }) => {
67
+ if (!CONSUME_OPERATIONS.includes(operation)) refuse("FREEZE_REQUEST_INVALID", `operation must be one of ${CONSUME_OPERATIONS.join(", ")}, not ${JSON.stringify(operation)}`);
68
+ if (!isBrokerText(nativeRecordId)) refuse("FREEZE_REQUEST_INVALID", "nativeRecordId must be non-empty text without control characters");
69
+ return { op: "consume", id: requireId(id), operation, native_record_id: nativeRecordId };
70
+ },
71
+ });
72
+
73
+ /** One broker answer: bounded JSON. A non-zero exit, a timeout, an unreadable answer or a failed spawn is a refusal; nothing is retried. */
74
+ export function callBroker(request, { launcher, timeoutMs = 120_000, run = spawnSync } = {}) {
75
+ if (!Array.isArray(launcher) || launcher.length === 0 || launcher.some((part) => typeof part !== "string" || part === "")) refuse("FREEZE_LAUNCHER_INVALID", "the restricted broker launcher must be a non-empty argv array (the restricted launcher or the authenticated SSH forced command; never admin-enroll)");
76
+ const body = JSON.stringify(request);
77
+ const result = run(launcher[0], launcher.slice(1), { input: body, encoding: "utf8", timeout: timeoutMs, maxBuffer: MAX_BROKER_ANSWER_BYTES, windowsHide: true });
78
+ if (result.error) refuse("FREEZE_BROKER_UNREACHABLE", `the broker could not be reached: ${result.error.message}; an unreachable broker denies`);
79
+ if (result.status !== 0) refuse("FREEZE_BROKER_DENIED", `the broker refused ${request.op}: ${String(result.stderr || result.stdout || `exit ${result.status}`).trim().slice(0, 500)}`);
80
+ let answer;
81
+ try { answer = JSON.parse(result.stdout); } catch { refuse("FREEZE_BROKER_ANSWER_INVALID", `the broker's ${request.op} answer is not JSON`); }
82
+ if (!isRecord(answer)) refuse("FREEZE_BROKER_ANSWER_INVALID", `the broker's ${request.op} answer is not an object`);
83
+ return answer;
84
+ }
85
+
86
+ /**
87
+ * A `check` answer, read as what it is: a diagnostic. It is refused unless it says `allowed`, names the source that was asked about, and
88
+ * says `deliveryLease: false`; the returned value carries no field a later upload could present as permission.
89
+ */
90
+ export function readCheckAnswer(answer, { source }) {
91
+ if (answer.status !== "allowed") refuse("FREEZE_CHECK_NOT_ALLOWED", `the broker did not allow ${source}: ${JSON.stringify(answer.status)}`);
92
+ if (answer.deliveryLease !== false) refuse("FREEZE_CHECK_LEASE", "a check answer must say deliveryLease false; an answer that does not is not the broker's check");
93
+ if (answer.source !== source) refuse("FREEZE_CHECK_SOURCE", `the broker checked ${answer.source}, not the requested ${source}`);
94
+ return { diagnostic: true, revision: answer.revision, sequence: answer.sequence, source: answer.source, closure: answer.closure };
95
+ }
96
+
97
+ /** A `push` answer: delivered only when the broker says `pushed` for exactly the source that was sent. */
98
+ export function readPushAnswer(answer, { source }) {
99
+ if (answer.status !== "pushed") refuse("FREEZE_PUSH_NOT_DELIVERED", `the broker did not report a push of ${source}: ${JSON.stringify(answer.status)}`);
100
+ if (answer.source !== source) refuse("FREEZE_PUSH_SOURCE", `the broker pushed ${answer.source}, not the requested ${source}`);
101
+ return { source: answer.source, closure: answer.closure, revision: answer.revision, sequence: answer.sequence };
102
+ }
103
+
104
+ /** Broker-mediated push of one enrolled closure: the source is the immutable commit object, the destination is the enrollment's. */
105
+ export function pushThroughBroker({ id, source, candidate, launcher, timeoutMs, run }) {
106
+ const request = brokerRequests.push({ id, source, candidate });
107
+ return readPushAnswer(callBroker(request, { launcher, timeoutMs, run }), { source });
108
+ }
109
+
110
+ // ---- 2. the native consume protocol ---------------------------------------------------------------------------------------------
111
+ /** The PreparedEffect fields, in the order the broker serializes (and digests) them. */
112
+ export const PREPARED_EFFECT_KEYS = Object.freeze(["repository", "operation", "native_record_id", "source_oid", "candidate", "endpoint", "destination", "native_effect_sha256", "provenance_sha256", "artifact_sha256"]);
113
+
114
+ /** Validate a typed effect as the broker does and return it with its keys in the broker's order (optional fields as null). */
115
+ export function normalizeEffect(effect) {
116
+ if (!isRecord(effect)) refuse("FREEZE_EFFECT_INVALID", "the effect must be an object");
117
+ const unknown = Object.keys(effect).filter((key) => !PREPARED_EFFECT_KEYS.includes(key));
118
+ if (unknown.length) refuse("FREEZE_EFFECT_INVALID", `unknown effect key(s): ${unknown.join(", ")}`);
119
+ const out = {
120
+ repository: effect.repository, operation: effect.operation, native_record_id: effect.native_record_id, source_oid: effect.source_oid,
121
+ candidate: effect.candidate ?? null, endpoint: effect.endpoint, destination: effect.destination,
122
+ native_effect_sha256: effect.native_effect_sha256, provenance_sha256: effect.provenance_sha256, artifact_sha256: effect.artifact_sha256 ?? null,
123
+ };
124
+ const bad = (what) => refuse("FREEZE_EFFECT_INVALID", `effect ${what}`);
125
+ if (!isBrokerText(out.repository)) bad("repository must be text");
126
+ if (!CONSUME_OPERATIONS.includes(out.operation)) bad("operation must be Build, Dequeue or Publish");
127
+ if (!isBrokerText(out.native_record_id)) bad("native_record_id must be text");
128
+ if (!isObjectId(out.source_oid)) bad("source_oid must be a full immutable object id");
129
+ if (out.candidate !== null && !isDigest(out.candidate)) bad("candidate must be a sha256 hex digest when present");
130
+ if (!isBrokerText(out.endpoint) || !isBrokerText(out.destination)) bad("endpoint and destination must be text");
131
+ if (!isDigest(out.native_effect_sha256) || !isDigest(out.provenance_sha256)) bad("native_effect_sha256 and provenance_sha256 must be sha256 hex digests");
132
+ if (out.artifact_sha256 !== null && !isDigest(out.artifact_sha256)) bad("artifact_sha256 must be a sha256 hex digest when present");
133
+ if (out.operation === "Publish" && out.artifact_sha256 === null) bad("a Publish effect must carry artifact_sha256");
134
+ return out;
135
+ }
136
+
137
+ /** The compact serialization the broker digests: the effect's fields in struct order, optional fields as null. */
138
+ export const serializeEffect = (effect) => JSON.stringify(normalizeEffect(effect));
139
+ /** The sha256 the broker computes over its own serialization and sends in `commit`; a mismatch means the adapter prepared something else. */
140
+ export const effectDigest = (effect) => sha256Hex(serializeEffect(effect));
141
+
142
+ /** One frame as a line: compact JSON and a newline, never over the cap. */
143
+ export function encodeFrame(frame) {
144
+ const text = `${JSON.stringify(frame)}\n`;
145
+ if (Buffer.byteLength(text) > FRAME_CAP_BYTES) refuse("FREEZE_FRAME_TOO_LARGE", `a frame is at most ${FRAME_CAP_BYTES} bytes`);
146
+ return text;
147
+ }
148
+
149
+ export function decodeFrame(line) {
150
+ if (typeof line !== "string" || Buffer.byteLength(line) > FRAME_CAP_BYTES || !line.endsWith("\n")) refuse("FREEZE_FRAME_INVALID", `a frame is one newline-terminated line of at most ${FRAME_CAP_BYTES} bytes`);
151
+ let frame;
152
+ try { frame = JSON.parse(line); } catch { refuse("FREEZE_FRAME_INVALID", "a frame is not JSON"); }
153
+ if (!isRecord(frame)) refuse("FREEZE_FRAME_INVALID", "a frame is not an object");
154
+ if (frame.protocol !== CONSUME_PROTOCOL) refuse("FREEZE_FRAME_INVALID", `frame protocol must be ${CONSUME_PROTOCOL}`);
155
+ if (frame.phase === "prepare") exactKeys(frame, ["phase", "protocol", "preparation_nonce", "operation", "native_record_id"], "prepare frame");
156
+ else if (frame.phase === "commit") exactKeys(frame, ["phase", "protocol", "transaction_nonce", "prepared_sha256"], "commit frame");
157
+ else refuse("FREEZE_FRAME_INVALID", `unexpected frame phase ${JSON.stringify(frame.phase)}`);
158
+ return frame;
159
+ }
160
+
161
+ /**
162
+ * One consume transaction, as the native owner sees the broker's pipe. The owner supplies:
163
+ * operation, endpoint, destination the adapter's enrolled values (the broker rejects an effect that differs);
164
+ * prepare({ nativeRecordId }) resolves the authoritative record, takes its lock and returns the typed effect, performing no effect;
165
+ * commit(effect) performs the actual effect of exactly the prepared effect, and returns when it has finished.
166
+ * `receive(line)` takes each broker frame in order and returns the line to write back. The order is prepare, then commit; anything else
167
+ * (a second prepare, a commit first, a wrong nonce, an unknown key, a digest that is not the prepared one) throws and ends the session,
168
+ * and a session never answers after it failed. `complete` is returned only after `commit(effect)` has returned.
169
+ */
170
+ export function createConsumeSession({ operation, endpoint, destination, prepare, commit }) {
171
+ if (!CONSUME_OPERATIONS.includes(operation)) refuse("FREEZE_SESSION_INVALID", "operation must be Build, Dequeue or Publish");
172
+ if (!isBrokerText(endpoint) || !isBrokerText(destination)) refuse("FREEZE_SESSION_INVALID", "endpoint and destination must be the adapter's enrolled text");
173
+ let step = "prepare";
174
+ let preparationNonce = null;
175
+ let prepared = null;
176
+ let digest = null;
177
+ const fail = (code, message) => { step = "failed"; throw new FreezeConsumerError(code, message); };
178
+ return {
179
+ get step() { return step; },
180
+ async receive(line) {
181
+ if (step === "failed" || step === "done") fail("FREEZE_SESSION_CLOSED", `the transaction is ${step}; no further frame is answered`);
182
+ let frame;
183
+ try { frame = decodeFrame(line); } catch (error) { step = "failed"; throw error; }
184
+ if (step === "prepare") {
185
+ if (frame.phase !== "prepare") fail("FREEZE_SESSION_ORDER", "the first frame must be prepare");
186
+ if (frame.operation !== operation) fail("FREEZE_SESSION_OPERATION", `the broker asked for ${frame.operation}, this adapter is ${operation}`);
187
+ if (!isBrokerText(frame.preparation_nonce) || !isBrokerText(frame.native_record_id)) fail("FREEZE_FRAME_INVALID", "prepare carries no nonce or record id");
188
+ const effect = normalizeEffect(await prepare({ nativeRecordId: frame.native_record_id }));
189
+ if (effect.operation !== operation || effect.native_record_id !== frame.native_record_id || effect.endpoint !== endpoint || effect.destination !== destination) {
190
+ fail("FREEZE_SESSION_BINDING", "the prepared effect names another operation, record, endpoint or destination than the transaction");
191
+ }
192
+ preparationNonce = frame.preparation_nonce;
193
+ prepared = effect;
194
+ digest = effectDigest(effect);
195
+ step = "commit";
196
+ return encodeFrame({ phase: "prepared", protocol: CONSUME_PROTOCOL, preparation_nonce: preparationNonce, effect });
197
+ }
198
+ if (frame.phase !== "commit") fail("FREEZE_SESSION_ORDER", "the second frame must be commit");
199
+ if (frame.prepared_sha256 !== digest) fail("FREEZE_SESSION_DIGEST", "the broker's commit digest is not the digest of the prepared effect; nothing is committed");
200
+ if (!isBrokerText(frame.transaction_nonce)) fail("FREEZE_FRAME_INVALID", "commit carries no transaction nonce");
201
+ step = "committing";
202
+ try { await commit(prepared); } catch (error) { step = "failed"; throw error; }
203
+ step = "done";
204
+ return encodeFrame({ phase: "complete", protocol: CONSUME_PROTOCOL, transaction_nonce: frame.transaction_nonce, prepared_sha256: digest });
205
+ },
206
+ };
207
+ }
208
+
209
+ // ---- 3. the publication binding -------------------------------------------------------------------------------------------------
210
+ const stable = (value) => (Array.isArray(value) ? `[${value.map(stable).join(",")}]`
211
+ : isRecord(value) ? `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(",")}}`
212
+ : JSON.stringify(value) ?? "null");
213
+
214
+ /**
215
+ * The typed effect for publishing one sealed artifact. `release` is what verifyPublicationRelease returned (the sealed manifest, already
216
+ * checked against its signing, notarization and ownership evidence, and `artifacts`, each read once and hash-checked against the seal);
217
+ * `fileName` names the artifact inside it. The source is the sealed manifest's commit, so the broker authorizes the source whose
218
+ * qualification produced these bytes, and artifact_sha256 is the digest of the bytes this process holds and will upload. Nothing here is
219
+ * taken from the caller except the transaction's names; a caller-supplied digest or commit cannot replace the sealed one.
220
+ */
221
+ export function buildPublishEffect({ release, fileName, repository, nativeRecordId, endpoint, destination, candidate = null }) {
222
+ if (!isRecord(release?.manifest) || !(release.artifacts instanceof Map)) refuse("FREEZE_PUBLISH_UNVERIFIED", "the effect is built from a verified sealed release (verifyPublicationRelease), not from caller values");
223
+ const { manifest } = release;
224
+ const entry = (manifest.files ?? []).find((item) => item?.name === fileName);
225
+ const artifact = release.artifacts.get(fileName);
226
+ if (!entry || !artifact) refuse("FREEZE_PUBLISH_ARTIFACT", `${JSON.stringify(fileName)} is not an artifact of the sealed release`);
227
+ if (artifact.sha256 !== entry.sha256 || !isDigest(artifact.sha256)) refuse("FREEZE_PUBLISH_ARTIFACT", `the verified bytes of ${fileName} do not carry the sealed digest`);
228
+ if (!isObjectId(manifest.commit)) refuse("FREEZE_PUBLISH_SOURCE", "the sealed release names no full commit");
229
+ // The qualification provenance: the sealed manifest's source, ownership evidence, signing policy and every sealed file's identity.
230
+ const provenance = {
231
+ commit: manifest.commit, app: manifest.app ?? null, version: manifest.version ?? null, platform: manifest.platform ?? null, releaseId: manifest.releaseId ?? null,
232
+ ownershipEvidence: manifest.ownershipEvidence ?? null, configSha256: manifest.signing?.configSha256 ?? null,
233
+ signingReceipts: (manifest.signing?.receipts ?? []).map((r) => ({ file: r.file, sha256: r.sha256 })),
234
+ files: (manifest.files ?? []).map((f) => ({ name: f.name, sha256: f.sha256, sizeBytes: f.sizeBytes })),
235
+ };
236
+ const nativeEffect = { operation: "Publish", repository, nativeRecordId, source: manifest.commit, artifact: artifact.sha256, endpoint, destination };
237
+ return normalizeEffect({
238
+ repository, operation: "Publish", native_record_id: nativeRecordId, source_oid: manifest.commit, candidate, endpoint, destination,
239
+ native_effect_sha256: sha256Hex(stable(nativeEffect)), provenance_sha256: sha256Hex(stable(provenance)), artifact_sha256: artifact.sha256,
240
+ });
241
+ }
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ // Private-app Linux publication and presigned URLs (rightkit#1230; Pulse guest link, ADR-0004 I1: a pinned sha256, no signature scheme).
3
+ //
4
+ // right-release linux-publish publish --app <slug> --out-dir <.right-release/linux> --approve <manifest sha256> [--dry-run]
5
+ // right-release linux-publish presign --app <slug> --version <v> --arch <x86_64|aarch64> [--expires <seconds, 60..86400>]
6
+ //
7
+ // publish reads `linux-artifacts.json` (linux-artifacts.mjs: one tarball per native architecture with sha256, size and glibc floor), re-hashes every
8
+ // tarball against it, and uploads tarballs and the manifest to the PRIVATE R2 bucket under `<app>/linux/<version>/`. Each upload is read back
9
+ // through the streamed sha256 and size check (r2-verified-upload.mjs), so a remote object that differs from the manifest is refused.
10
+ // Publication of any build needs Adrian's go naming it: `--approve` takes the sha256 of the manifest file he named, and a manifest with any
11
+ // other digest is refused before anything leaves the host. Only the local release host that built the artifacts runs this.
12
+ // presign prints, as JSON, a time-limited GET URL for ONE artifact together with its pinned sha256, size and glibc floor, so Pulse can put them in a
13
+ // one-use guest pass. The URL is the only place a signature appears; credentials are derived in memory from the Cloudflare token (the
14
+ // credential store, never an environment value printed) and never written anywhere.
15
+ // Native builds only (aarch64 on a Linux VM on the Mac, x86_64 on a Linux VM on the Dell): the manifest holds whichever architectures were packed.
16
+ import { createHash } from "node:crypto";
17
+ import { existsSync, readFileSync, statSync } from "node:fs";
18
+ import path from "node:path";
19
+ import { pathToFileURL } from "node:url";
20
+ import { LINUX_ARCHES, LINUX_ARTIFACTS_SCHEMA } from "./linux-artifacts.mjs";
21
+ import { PublicationError } from "./publication-artifacts.mjs";
22
+ import { resolveCloudflareApiToken } from "./protected-credentials.mjs";
23
+ import { deriveR2S3Credentials, presignGetUrl } from "./r2-s3-multipart.mjs";
24
+ import { uploadVerifiedR2File } from "./r2-verified-upload.mjs";
25
+
26
+ export const PRIVATE_LINUX_BUCKET = "rightapps-updates";
27
+ const SLUG = /^[a-z][a-z0-9-]{1,40}$/;
28
+ const SEMVER = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
29
+ const HEX64 = /^[0-9a-f]{64}$/;
30
+
31
+ export class LinuxPublishError extends Error {
32
+ constructor(message) { super(message); this.name = "LinuxPublishError"; this.code = "RK_LINUX_PUBLISH"; }
33
+ }
34
+ const fail = (message) => { throw new LinuxPublishError(message); };
35
+
36
+ /** The R2 key of one object of a Linux release: `<app>/linux/<version>/<file>`. */
37
+ export function linuxObjectKey(app, version, file) {
38
+ if (!SLUG.test(app ?? "")) fail(`app ${JSON.stringify(app)} is not an app slug`);
39
+ if (!SEMVER.test(version ?? "")) fail(`version ${JSON.stringify(version)} is not semver`);
40
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(file ?? "") || file.includes("..")) fail(`file ${JSON.stringify(file)} is not a plain file name`);
41
+ return `${app}/linux/${version}/${file}`;
42
+ }
43
+
44
+ /** Read and validate `linux-artifacts.json`: its schema, app, version, commit, and every architecture entry. Returns { manifest, manifestPath, sha256 }. */
45
+ export function readLinuxManifest({ outDir, app, fs = { existsSync, readFileSync, statSync } }) {
46
+ const manifestPath = path.resolve(outDir, "linux-artifacts.json");
47
+ if (!fs.existsSync(manifestPath)) fail(`no linux-artifacts.json in ${path.resolve(outDir)}; pack the Linux artifacts first (development.targets.linux.archive)`);
48
+ const bytes = fs.readFileSync(manifestPath);
49
+ let manifest;
50
+ try { manifest = JSON.parse(String(bytes)); } catch (error) { fail(`linux-artifacts.json is not JSON: ${error.message}`); }
51
+ if (manifest?.schema !== LINUX_ARTIFACTS_SCHEMA) fail(`linux-artifacts.json schema is ${JSON.stringify(manifest?.schema)}, expected ${LINUX_ARTIFACTS_SCHEMA}`);
52
+ if (manifest.app !== app) fail(`linux-artifacts.json is for ${JSON.stringify(manifest.app)}, not ${JSON.stringify(app)}`);
53
+ if (!SEMVER.test(manifest.version ?? "") || !/^[0-9a-f]{40}$/.test(manifest.commit ?? "")) fail("linux-artifacts.json has no valid version and commit");
54
+ const arches = Object.keys(manifest.artifacts ?? {});
55
+ if (!arches.length || arches.some((arch) => !LINUX_ARCHES.includes(arch))) fail(`linux-artifacts.json must list one or more of ${LINUX_ARCHES.join(", ")}`);
56
+ for (const arch of arches) {
57
+ const entry = manifest.artifacts[arch];
58
+ if (!entry || typeof entry.file !== "string" || !HEX64.test(entry.sha256 ?? "") || !Number.isSafeInteger(entry.size) || entry.size <= 0) fail(`linux-artifacts.json ${arch} needs file, sha256 and size`);
59
+ }
60
+ return { manifest, manifestPath, sha256: createHash("sha256").update(bytes).digest("hex") };
61
+ }
62
+
63
+ /** Publish every architecture of the manifest. `approve` must equal the manifest's sha256 (Adrian's named build). Returns { keys, version }. */
64
+ export async function publishLinuxArtifacts({ outDir, app, approve, dryRun = false, env = process.env, credentialStore, upload = uploadVerifiedR2File, fs = { existsSync, readFileSync, statSync }, log = (line) => console.log(line) }) {
65
+ if (!HEX64.test(approve ?? "")) fail("--approve must be the sha256 of the linux-artifacts.json Adrian named (publication of any build needs his go naming it)");
66
+ const { manifest, manifestPath, sha256 } = readLinuxManifest({ outDir, app, fs });
67
+ if (sha256 !== approve) fail(`linux-artifacts.json is ${sha256}, not the approved ${approve}; nothing was uploaded`);
68
+ const root = path.resolve(outDir);
69
+ const planned = Object.values(manifest.artifacts).map((entry) => {
70
+ const file = path.join(root, entry.file);
71
+ if (!fs.existsSync(file)) fail(`${entry.file} is missing next to the manifest`);
72
+ const bytes = fs.readFileSync(file);
73
+ const actual = createHash("sha256").update(bytes).digest("hex");
74
+ if (actual !== entry.sha256 || bytes.length !== entry.size) fail(`${entry.file} is ${actual} (${bytes.length} bytes), the manifest says ${entry.sha256} (${entry.size}); nothing was uploaded`);
75
+ return { file, evidence: { sha256: entry.sha256, sizeBytes: entry.size }, key: linuxObjectKey(app, manifest.version, entry.file) };
76
+ });
77
+ planned.push({ file: manifestPath, evidence: { sha256, sizeBytes: statSync(manifestPath).size }, key: linuxObjectKey(app, manifest.version, "linux-artifacts.json") });
78
+ if (dryRun) { for (const item of planned) log(`right-release linux-publish: dry-run ${PRIVATE_LINUX_BUCKET}/${item.key}`); return { version: manifest.version, keys: planned.map((item) => item.key), dryRun: true }; }
79
+ const token = resolveCloudflareApiToken({ env, credentialStore, required: true });
80
+ const uploadEnv = { ...env, CLOUDFLARE_API_TOKEN: token };
81
+ // Tarballs first, the manifest last: a manifest in R2 always names objects that are already there and verified.
82
+ for (const item of planned) {
83
+ await upload(item.file, item.evidence, item.key, "private", { env: uploadEnv });
84
+ log(`right-release linux-publish: ${PRIVATE_LINUX_BUCKET}/${item.key} uploaded and read back (sha256 ${item.evidence.sha256.slice(0, 16)}...)`);
85
+ }
86
+ return { version: manifest.version, keys: planned.map((item) => item.key) };
87
+ }
88
+
89
+ /** A presigned URL for one architecture of a published release, with the digest Pulse pins. The manifest is read back from R2 (not trusted from disk). */
90
+ export async function presignLinuxArtifact({ app, version, arch, expiresSeconds = 3600, env = process.env, credentialStore, fetchImpl = fetch, now = new Date() }) {
91
+ if (!LINUX_ARCHES.includes(arch)) fail(`arch must be one of ${LINUX_ARCHES.join(", ")}`);
92
+ const token = resolveCloudflareApiToken({ env, credentialStore, required: true });
93
+ const credentials = await deriveR2S3Credentials(token, { account: env.CLOUDFLARE_ACCOUNT_ID, fetchImpl });
94
+ const manifestKey = linuxObjectKey(app, version, "linux-artifacts.json");
95
+ const manifestUrl = presignGetUrl({ bucket: PRIVATE_LINUX_BUCKET, key: manifestKey, credentials, account: env.CLOUDFLARE_ACCOUNT_ID || undefined, expiresSeconds: 60, now });
96
+ const response = await fetchImpl(manifestUrl.url);
97
+ if (!response.ok) fail(`the published manifest ${manifestKey} could not be read (HTTP ${response.status}); publish it first`);
98
+ const manifest = JSON.parse(await response.text());
99
+ const entry = manifest?.artifacts?.[arch];
100
+ if (manifest?.schema !== LINUX_ARTIFACTS_SCHEMA || manifest.app !== app || manifest.version !== version || !entry) fail(`the published manifest has no ${arch} artifact for ${app} ${version}`);
101
+ const signed = presignGetUrl({ bucket: PRIVATE_LINUX_BUCKET, key: linuxObjectKey(app, version, entry.file), credentials, account: env.CLOUDFLARE_ACCOUNT_ID || undefined, expiresSeconds, now });
102
+ return { app, version, arch, file: entry.file, sha256: entry.sha256, size: entry.size, glibc: entry.glibc ?? null, url: signed.url, expiresAt: signed.expiresAt };
103
+ }
104
+
105
+ export async function main(argv = process.argv.slice(2)) {
106
+ const [command, ...rest] = argv;
107
+ const flags = {};
108
+ for (let i = 0; i < rest.length; i += 1) {
109
+ const name = rest[i];
110
+ if (name === "--dry-run") { flags.dryRun = true; continue; }
111
+ if (!["--app", "--out-dir", "--approve", "--version", "--arch", "--expires"].includes(name) || rest[i + 1] === undefined) { console.error(`right-release linux-publish: unknown or incomplete argument ${name}`); return 2; }
112
+ flags[name.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = rest[i + 1];
113
+ i += 1;
114
+ }
115
+ try {
116
+ if (command === "publish") {
117
+ if (!flags.app || !flags.outDir) { console.error("usage: right-release linux-publish publish --app <slug> --out-dir <dir> --approve <manifest sha256> [--dry-run]"); return 2; }
118
+ const result = await publishLinuxArtifacts({ outDir: flags.outDir, app: flags.app, approve: flags.approve, dryRun: flags.dryRun === true });
119
+ console.log(JSON.stringify(result));
120
+ return 0;
121
+ }
122
+ if (command === "presign") {
123
+ if (!flags.app || !flags.version || !flags.arch) { console.error("usage: right-release linux-publish presign --app <slug> --version <v> --arch <x86_64|aarch64> [--expires <seconds>]"); return 2; }
124
+ const result = await presignLinuxArtifact({ app: flags.app, version: flags.version, arch: flags.arch, ...(flags.expires ? { expiresSeconds: Number(flags.expires) } : {}) });
125
+ console.log(JSON.stringify(result));
126
+ return 0;
127
+ }
128
+ console.error("usage: right-release linux-publish publish|presign ...");
129
+ return 2;
130
+ } catch (error) {
131
+ console.error(`right-release linux-publish: ${error.message}`);
132
+ return error instanceof LinuxPublishError || error instanceof PublicationError ? 1 : 2;
133
+ }
134
+ }
135
+
136
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main().then((code) => { process.exitCode = code; });
package/local-publish.mjs CHANGED
@@ -20,6 +20,7 @@ import os from "node:os";
20
20
  import path from "node:path";
21
21
  import { fileURLToPath, pathToFileURL } from "node:url";
22
22
  import { spawnSync } from "./background-process.mjs";
23
+ import { locateBrokerClient, spawnBrokerClient } from "./broker-client.mjs";
23
24
  import { runCargoAsync, runCargoSync, spawnCollect } from "./managed-cargo.mjs";
24
25
  import { localBuildGranted, LOCAL_BUILD_FILE } from "./execution-policy.mjs";
25
26
  import { GATE_SCHEMA, MAX_CARGO_JOBS, defaultEvidencePath, enforcePublicationGate, publishGatedTarball } from "./publication-gate.mjs";
@@ -47,11 +48,29 @@ const STEP_TIMEOUT_MS = 30 * 60 * 1000;
47
48
  export const BROKER_COMPILED_ONLY = /^rustright: compiled, ready for testing\b/m;
48
49
 
49
50
  /**
50
- * Run the test executables a broker-compiled `cargo test` step listed, outside the broker (GC-A08), with the run arguments after its `--`.
51
+ * The test executables the broker signed for the compile job `requestId` (receipt.testExecutables, ADR-001 C2, rightkit#1454), read from
52
+ * the broker's status of that job exactly as the gate's class B rows read it. { listed: false } when the receipt carries no such field (an
53
+ * older broker: containment only, as class B); otherwise { listed: true, testExecutables, reason } where a null list names the broker's reason.
54
+ */
55
+ export function brokerTestListOf(requestId, { run = spawnSync, platform = process.platform, env = process.env, readFile } = {}) {
56
+ const r = spawnBrokerClient(run, locateBrokerClient({ platform, env, probe: run }), ["status", requestId], { encoding: "utf8", timeout: 60_000, windowsHide: true, shell: false, maxBuffer: 64 * 1024 * 1024 }, { platform, readFile });
57
+ if (r.error || r.status !== 0) throw new Error(`the broker cannot report job ${requestId} (rustright status failed)`);
58
+ let doc;
59
+ try { doc = JSON.parse(r.stdout); } catch { throw new Error(`the broker's status of job ${requestId} is not JSON`); }
60
+ const receipt = doc?.receipt ?? doc;
61
+ if (receipt?.id !== requestId) throw new Error(`the broker's status is not for job ${requestId}`);
62
+ return Object.hasOwn(receipt, "testExecutables") ? { listed: true, testExecutables: receipt.testExecutables, reason: receipt.testExecutablesReason ?? null } : { listed: false };
63
+ }
64
+
65
+ /**
66
+ * Run the test executables a broker-compiled test step listed, outside the broker (GC-A08), with the run arguments after its `--`.
51
67
  * The listing must have finished and name at least one test executable; every executable must sit inside the compile's output directory
52
- * (the carried receipt's, else cargo metadata's target directory). Returns runTestBinaries' { status, code?, detail?, results }.
68
+ * (the carried receipt's, else the workspace's target directory) and, as in the gate's class B rows, be in the broker's signed test
69
+ * executable list for that compile with the same sha256 (signedTestExecutableProblems; rightkit#1500). A compile that carries no broker job
70
+ * id cannot show its list and runs nothing. Doctests are out of scope: the broker's test build compiles none and end-to-end tests are the
71
+ * only tests (Adrian, 2026-11-03), so a doctest never stops a publish. Returns runTestBinaries' { status, code?, detail?, results }.
53
72
  */
54
- export async function runCompiledTests({ unit, step, result, cwd, env, scans }) {
73
+ export async function runCompiledTests({ unit, step, result, cwd, env, scans, readTestList = brokerTestListOf, platform = process.platform }) {
55
74
  const ds = scans ?? await import("./deterministic-scans.mjs");
56
75
  const { resolveTargetRoot } = await import("./cargo-target.mjs");
57
76
  const listing = ds.parseTestListing(`${result.stdout ?? ""}`);
@@ -60,6 +79,12 @@ export async function runCompiledTests({ unit, step, result, cwd, env, scans })
60
79
  const outputDir = typeof result.outputDir === "string" ? result.outputDir : resolveTargetRoot(path.join(cwd, "Cargo.toml"), { env });
61
80
  const contained = ds.containTestExecutables(listing.binaries, { boundDirs: [outputDir] });
62
81
  if (contained.problems.length) return { status: "fail", code: "TEST_EXECUTABLE_OUTSIDE_OUTPUT", detail: `${unit}: ${contained.problems.slice(0, 5).join("; ")}; nothing was run`, results: null };
82
+ if (typeof result.requestId !== "string" || result.requestId === "") return { status: "fail", code: "TEST_EXECUTABLE_UNSIGNED", detail: `${unit}: the compile carries no broker job id, so the broker's signed test executable list cannot be read; nothing was run`, results: null };
83
+ let signed;
84
+ try { signed = readTestList(result.requestId, { env, platform }); }
85
+ catch (error) { return { status: "fail", code: "TEST_EXECUTABLE_UNSIGNED", detail: `${unit}: ${error.message}; nothing was run`, results: null }; }
86
+ const unsigned = signed.listed ? ds.signedTestExecutableProblems(contained.accepted, signed.testExecutables, signed.reason, platform) : [];
87
+ if (unsigned.length) return { status: "fail", code: "TEST_EXECUTABLE_UNSIGNED", detail: `${unit}: ${unsigned.slice(0, 5).join("; ")}; nothing was run`, results: null };
63
88
  const sep = step.args.indexOf("--");
64
89
  const runArgs = sep >= 0 ? step.args.slice(sep + 1) : [];
65
90
  const scan = { id: `test:${unit}`, runOutside: { args: runArgs } };
@@ -401,12 +426,12 @@ export { CROSS_TARGETS, ZIG_TARGETS, CROSS_CC_ENV, crossTargetsFor, crossCompile
401
426
  /** The CI gate's commands for one unit (scripts/ci/gate.mjs npmGate/rustGate), mirrored exactly. */
402
427
  export function localTestPlan({ kind, unit, dir, config, manifest, batch = false, platform = "darwin" }) {
403
428
  if (kind === "npm") {
404
- if (!manifest?.scripts?.test) refuse(`${unit} has no test script; --local never publishes an untested package`);
429
+ // End-to-end tests only (Adrian, 2026-11-03): an npm unit with no test script has no test step, as a crate with no test qualifies on its other steps.
405
430
  return {
406
431
  id: `npm:${dir}`, featureLabels: ["default"],
407
432
  steps: [
408
433
  { command: "pnpm", args: ["-r", "--workspace-concurrency=1", "run", "build"], test: false },
409
- { command: "pnpm", args: ["--dir", dir, "run", "test"], test: true },
434
+ ...(manifest?.scripts?.test ? [{ command: "pnpm", args: ["--dir", dir, "run", "test"], test: true }] : []),
410
435
  ],
411
436
  };
412
437
  }
@@ -774,10 +799,8 @@ async function* publishUnitStages(parsed, deps, batch) {
774
799
  }
775
800
  steps.push(row);
776
801
  }
777
- const verdict = judgeUnit({ name: unit, steps: steps.map((s) => ({ ...s, unit: plan.id })), allowNoTests: kind === "cargo", allowIgnored: ignoredAllowed ? [unit] : [], allowMissingAssets: isAssetGated ? [unit] : [] });
802
+ const verdict = judgeUnit({ name: unit, steps: steps.map((s) => ({ ...s, unit: plan.id })), allowNoTests: true, allowIgnored: ignoredAllowed ? [unit] : [], allowMissingAssets: isAssetGated ? [unit] : [] });
778
803
  if (verdict.status === "fail" || steps.some((s) => s.failed > 0)) refuse(`${plan.id} not qualified: ${verdict.problems.join("; ") || "failed tests reported"}`);
779
- // End-to-end tests only (Adrian, 2026-11-03): a crate with no test of its own publishes; an npm unit still needs its test script to run.
780
- if (kind !== "cargo" && !(verdict.executed > 0)) refuse(`${plan.id} executed no test`);
781
804
  log(`[right-release] ${plan.id}: ${verdict.executed} passed, 0 failed, ${verdict.skipped} skipped, ${verdict.ignored} ignored${isAssetGated ? " (asset-gated: RIGHTKIT_REQUIRE_ASSETS=0, skips recorded)" : ""}`);
782
805
  const packageEnv = yield { stage: "compile", kind, name: unit, version, commit: head, brokerRequests: brokerRequests.splice(0) };
783
806
  if (packageEnv) Object.assign(env, testEnv({ env: packageEnv }, isAssetGated));
package/nsis-pack.mjs ADDED
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env node
2
+ // `right-release nsis-pack --script <installer.nsi> --payload <dir> --output <Setup.exe> [--define NAME=VALUE]...` (rightkit#428, #871).
3
+ //
4
+ // The packing step of the Windows payload contract (`signingContract: "windows-payload-authenticode-before-nsis-v1"`): an app that is NOT a
5
+ // Tauri bundle (Pulse: eight native executables and its own `.nsi`) signs every payload file, then calls this to compile the installer from the
6
+ // signed bytes. It runs `makensis` with no shell and no network, passes the payload directory and the output file as `PAYLOAD_DIR` and `OUTFILE`
7
+ // defines (the script reads `${PAYLOAD_DIR}` and writes `OutFile "${OUTFILE}"`), adds each `--define`, and then refuses unless the installer
8
+ // exists at `--output` and is newer than the script. Signing and the embedded-bytes proof stay in release.mjs: this step never signs.
9
+ import { existsSync, mkdirSync, rmSync, statSync } from "node:fs";
10
+ import path from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { spawnSync } from "./background-process.mjs";
13
+
14
+ export class NsisPackError extends Error {
15
+ constructor(message) { super(message); this.name = "NsisPackError"; this.code = "RK_NSIS_PACK"; }
16
+ }
17
+ const fail = (message) => { throw new NsisPackError(message); };
18
+ const DEFINE_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
19
+ const RESERVED = new Set(["PAYLOAD_DIR", "OUTFILE"]);
20
+
21
+ const MAKENSIS_CANDIDATES = [
22
+ "C:\\Program Files (x86)\\NSIS\\makensis.exe",
23
+ "C:\\Program Files\\NSIS\\makensis.exe",
24
+ "/opt/homebrew/bin/makensis",
25
+ "/usr/local/bin/makensis",
26
+ "/usr/bin/makensis",
27
+ ];
28
+
29
+ /** `RIGHT_RELEASE_MAKENSIS` (must exist), else the first known install path, else `makensis` on PATH. */
30
+ export function resolveMakensis({ env = process.env, exists = existsSync } = {}) {
31
+ const explicit = env.RIGHT_RELEASE_MAKENSIS;
32
+ if (explicit) {
33
+ if (!exists(explicit)) fail(`RIGHT_RELEASE_MAKENSIS does not exist: ${explicit}`);
34
+ return explicit;
35
+ }
36
+ return MAKENSIS_CANDIDATES.find((candidate) => exists(candidate)) ?? "makensis";
37
+ }
38
+
39
+ export function parseNsisPackArgs(argv) {
40
+ const opts = { script: null, payload: null, output: null, defines: [] };
41
+ for (let i = 0; i < argv.length; i += 1) {
42
+ const flag = argv[i];
43
+ const value = argv[i + 1];
44
+ if (!["--script", "--payload", "--output", "--define"].includes(flag)) fail(`unknown argument: ${flag}`);
45
+ if (value === undefined || value.startsWith("--")) fail(`${flag} needs a value`);
46
+ i += 1;
47
+ if (flag === "--define") {
48
+ const at = value.indexOf("=");
49
+ const name = at < 0 ? value : value.slice(0, at);
50
+ const text = at < 0 ? "1" : value.slice(at + 1);
51
+ if (!DEFINE_NAME.test(name)) fail(`--define name must be UPPER_SNAKE_CASE: ${name}`);
52
+ if (RESERVED.has(name)) fail(`--define ${name} is set by nsis-pack itself`);
53
+ if (/[\r\n\0]/.test(text)) fail(`--define ${name} value must be one line`);
54
+ opts.defines.push([name, text]);
55
+ } else opts[flag.slice(2)] = value;
56
+ }
57
+ for (const key of ["script", "payload", "output"]) if (!opts[key]) fail(`--${key} is required`);
58
+ return opts;
59
+ }
60
+
61
+ /** Compile the installer. Injectable effects: `run`, `exists`, `stat`, `remove`, `makeDir`, `log`, `env`. */
62
+ export function packNsisPayload(opts, { run = spawnSync, exists = existsSync, stat = statSync, remove = rmSync, makeDir = mkdirSync, log = (line) => console.log(line), env = process.env, cwd = process.cwd() } = {}) {
63
+ const script = path.resolve(cwd, opts.script);
64
+ const payload = path.resolve(cwd, opts.payload);
65
+ const output = path.resolve(cwd, opts.output);
66
+ if (!/\.nsi$/i.test(script) || !exists(script)) fail(`NSIS script not found: ${script}`);
67
+ if (!exists(payload) || !stat(payload).isDirectory()) fail(`payload directory not found: ${payload}`);
68
+ if (!/\.exe$/i.test(output)) fail(`output must be an .exe installer path: ${output}`);
69
+ const inside = path.relative(payload, output);
70
+ if (inside === "" || (!inside.startsWith("..") && !path.isAbsolute(inside))) fail("output must not be inside the payload directory (the installer would wrap itself)");
71
+ makeDir(path.dirname(output), { recursive: true });
72
+ remove(output, { force: true }); // a stale installer is never an acceptable result
73
+ const args = ["/V2", `/DPAYLOAD_DIR=${payload}`, `/DOUTFILE=${output}`, ...opts.defines.map(([name, value]) => `/D${name}=${value}`), script];
74
+ const makensis = resolveMakensis({ env, exists });
75
+ log(`right-release nsis-pack: ${path.basename(makensis)} ${path.basename(script)} -> ${output}`);
76
+ const result = run(makensis, args, { cwd: path.dirname(script), stdio: "inherit", shell: false, windowsHide: true, env });
77
+ if (result?.error) fail(`could not start makensis (${result.error.message}); install NSIS or set RIGHT_RELEASE_MAKENSIS`);
78
+ if (result?.status !== 0) fail(`makensis exited ${result?.status ?? "without a status"}`);
79
+ if (!exists(output)) fail(`makensis finished but wrote no installer at ${output}; the script must use OutFile "\${OUTFILE}"`);
80
+ if (stat(output).mtimeMs < stat(script).mtimeMs) fail(`the installer at ${output} is older than its script: it is not this run's output`);
81
+ return { script, payload, output, sizeBytes: stat(output).size };
82
+ }
83
+
84
+ export function main(argv = process.argv.slice(2)) {
85
+ try {
86
+ const result = packNsisPayload(parseNsisPackArgs(argv));
87
+ console.log(`right-release nsis-pack: wrote ${result.output} (${result.sizeBytes} bytes); sign it with the installer signing step`);
88
+ return 0;
89
+ } catch (error) {
90
+ console.error(`right-release nsis-pack: ${error.message}`);
91
+ return error instanceof NsisPackError ? 1 : 2;
92
+ }
93
+ }
94
+
95
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) process.exitCode = main();