@rightkit/release 0.6.39 → 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 (86) 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 +167 -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 -7
  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 +568 -491
  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-ledger.mjs +6 -1
  79. package/stage-receipt.mjs +115 -0
  80. package/stage-sidecar.mjs +188 -17
  81. package/stage-xcframework.mjs +118 -0
  82. package/suite-api.generated.mjs +16 -1
  83. package/unit-gate.mjs +14 -2
  84. package/upload-large.mjs +4 -4
  85. package/upload-release.mjs +6 -0
  86. package/win-package-recipe.mjs +26 -4
package/development.mjs CHANGED
@@ -14,6 +14,7 @@ import { assertReleaseExecutionAllowed } from "./execution-policy.mjs";
14
14
  import { acquireManagedRunLease, directCargoEnv, directPlatform, gateNoBroker, managedRuntimeClient, managedRuntimeCommand, runCargoSync } from "./managed-cargo.mjs";
15
15
  import { BUNDLE_MARKERS, bundleMarkerBuffer, readTauriBundleMarkers } from "./tauri-bundle-marker.mjs";
16
16
  import { installPortableDevelopment } from "./portable-development.mjs";
17
+ import { PAYLOAD_ROOT_KIND, installPayloadRoot, validatePayloadRootDescriptor } from "./payload-root-install.mjs";
17
18
  import { previousPathOf, stagingPathOf, swapInPlace } from "./in-place-install.mjs";
18
19
  import { stageDevelopmentBinaries, validateStageEntries } from "./stage-binary.mjs";
19
20
  import { assertStableDesignatedRequirement, readBundleExecutable, requestedCiAdhocSigning, signMacosDevelopmentBundle } from "./development-signing.mjs";
@@ -27,6 +28,8 @@ import { ASSEMBLED_APP_KIND, installAssembledMac, installAssembledWindows, resol
27
28
  import { assertIosDevelopmentSession, installIosDevelopment, iosDevelopmentApp, iosUiTestCommands, prepareIosDevelopment, prepareIosUiTests, runIosDevelopmentCommands, validateIosDevelopment } from "./ios-dev.mjs";
28
29
  import { packLinuxArtifacts, validateLinuxArchive } from "./linux-artifacts.mjs";
29
30
  import { buildAndEmbedNativeHelpers, nativeHelpersFromConfig } from "./native-helpers.mjs";
31
+ import { devExpectPresentFindings, devSelfCheckSettings } from "./release-switch-scan.mjs";
32
+ import { devWebQaPairing } from "./qa-web-pairing.mjs";
30
33
  import { androidDevelopmentNdkCommand, androidDevelopmentSerial, installAndroidDevelopment, validateAndroidDevelopment } from "./android-dev.mjs";
31
34
 
32
35
  // GATE-CONTRACT GC-A07: the dev installer is the release Cargo profile plus the `qa-native` feature
@@ -89,6 +92,9 @@ export function validateDevelopmentConfig(config, platform, { root = process.cwd
89
92
  for (const key of ["sourceDirectory", "entrypoint"]) {
90
93
  if (typeof descriptor[key] !== "string" || !descriptor[key] || path.isAbsolute(descriptor[key]) || path.win32.isAbsolute(descriptor[key]) || descriptor[key].split(/[\\/]/).includes("..")) throw new Error(`portable development ${key} must be a contained relative path`);
91
94
  }
95
+ } else if (target.install?.kind === PAYLOAD_ROOT_KIND) {
96
+ if (platform === "android" || platform === "ios") throw new Error(`the ${PAYLOAD_ROOT_KIND} development installer is for --platform win, mac or linux`);
97
+ validatePayloadRootDescriptor(target.install, platform);
92
98
  } else if (target.install?.kind === TAURI_DEVID_KIND) {
93
99
  if (platform !== "mac") throw new Error(`the ${TAURI_DEVID_KIND} development installer is for --platform mac`);
94
100
  resolveTauriDevIdDescriptor(target.install, { appRoot: root });
@@ -176,6 +182,8 @@ export function runDevelopment({ root, platform, config, buildOnly = false, dryR
176
182
  // broker's per-generation target folder or a hashed dev-targets folder.
177
183
  const staged = target.stage?.length ? stageDevelopmentBinaries(target.stage, { root, platform: platform === "win" ? "win32" : process.platform, managedOutputDirs: carriedOutputDirsSince(childEnv) }) : [];
178
184
  for (const file of staged) console.log(`right-release dev: staged ${file}`);
185
+ // The web and native QA halves are built together or not at all (rightkit#1480).
186
+ if (!dryRun && (platform === "win" || platform === "mac")) assertDevWebQaPairing({ root, config, commands: target.build });
179
187
  // Linux: the declared files become one tarball per architecture plus the digest manifest a guest link pins (rightkit#1230).
180
188
  // Only from a clean checkout: an artifact others install must name the exact commit it was built from.
181
189
  if (platform === "linux" && target.archive && !dryRun) {
@@ -199,7 +207,7 @@ export function runDevelopment({ root, platform, config, buildOnly = false, dryR
199
207
  }
200
208
  releaseLease = false;
201
209
  return installTauriDevId({ appRoot: root, config: target.install, releaseConfig: config, built, env: childEnv })
202
- .then((outcome) => ({ built: true, installed: true, ...(staged.length ? { staged } : {}), devid: outcome }))
210
+ .then((outcome) => { assertDevSelfCheck({ config, paths: [outcome.installed ?? path.resolve(target.install.destination)] }); return { built: true, installed: true, ...(staged.length ? { staged } : {}), devid: outcome }; })
203
211
  .finally(() => lease.release());
204
212
  }
205
213
  if (target.install.kind === TAURI_AUTHENTICODE_KIND) {
@@ -216,6 +224,7 @@ export function runDevelopment({ root, platform, config, buildOnly = false, dryR
216
224
  install: (installer) => installWindowsDevelopment(descriptor, installer, { root, env: childEnv, run, debugDir }),
217
225
  installedExe: () => path.resolve(root, descriptor.expectedInstalledPath),
218
226
  } });
227
+ assertDevSelfCheck({ config, paths: [path.resolve(root, descriptor.expectedInstalledPath)] });
219
228
  return { built: true, installed: true, ...(staged.length ? { staged } : {}), authenticode };
220
229
  }
221
230
  if (target.install.kind === ASSEMBLED_APP_KIND) {
@@ -231,10 +240,27 @@ export function runDevelopment({ root, platform, config, buildOnly = false, dryR
231
240
  .finally(() => lease.release());
232
241
  }
233
242
  const signing = install(target.install, { root, platform, config, env: childEnv, run, door, sinceMs: startedMs, serial });
243
+ if (target.install.kind === "tauri" && (platform === "win" || platform === "mac")) assertDevSelfCheck({ config, paths: [platform === "win" ? path.resolve(root, target.install.expectedInstalledPath) : path.resolve(target.install.destination)] });
234
244
  return { built: true, installed: true, ...(staged.length ? { staged } : {}), ...(platform === "mac" && target.install.kind === "tauri" ? { signing } : {}) };
235
245
  } finally { if (releaseLease) lease.release(); }
236
246
  }
237
247
 
248
+ // The dev-build self-check (#397): the installed dev copy must carry the strings the release scan refuses, or that scan proves nothing.
249
+ function assertDevSelfCheck({ config, paths }) {
250
+ const settings = devSelfCheckSettings(config?.releaseSwitches?.devSelfCheck);
251
+ if (settings.skip) { console.log(`right-release dev: dev self-check skipped (releaseSwitches.devSelfCheck.optOut: ${settings.skip})`); return; }
252
+ const findings = devExpectPresentFindings({ binaryPaths: paths, expect: settings.expect });
253
+ if (findings.length) throw new DevelopmentInstallError("DEV_SELF_CHECK_FAILED", `dev self-check failed:\n${findings.map((f) => `- ${f.reason}`).join("\n")}\nAn app whose dev build has no QA control server declares releaseSwitches.devSelfCheck: { "optOut": "<reason>" }.`);
254
+ console.log(`right-release dev: dev self-check: the installed dev binary carries ${settings.expect.join(", ")}`);
255
+ }
256
+
257
+ // The web and native QA halves must not drift (qa-web-pairing.mjs): refuses a dev build whose bundle and Cargo features disagree.
258
+ function assertDevWebQaPairing({ root, config, commands }) {
259
+ const result = devWebQaPairing({ root, config, commands });
260
+ if (result.findings.length) throw new DevelopmentInstallError("DEV_WEB_QA_PAIRING", `web/native QA pairing failed:\n${result.findings.map((f) => `- ${f.reason}`).join("\n")}`);
261
+ if (result.checked) console.log(`right-release dev: web/native QA pairing ok (qa-native ${result.nativeQa ? "on" : "off"}, web QA marker ${result.webQa ? "present" : "absent"})`);
262
+ }
263
+
238
264
  /** WSL reports `linux` as its platform under both generations; which one it is decides whether a Linux kernel runs at all. */
239
265
  export function isWsl({ env = process.env, readFile = (f) => readFileSync(f, "utf8") } = {}) {
240
266
  if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true;
@@ -260,6 +286,13 @@ export function assertNativeDevelopmentHost(platform, host = process.platform, {
260
286
  function install(descriptor, { root, platform, config, env, run, door, sinceMs = null, serial }) {
261
287
  if (descriptor.kind === "adb") return installAndroidDevelopment(descriptor, { root, env, run, serial });
262
288
  if (descriptor.kind === "command") return execute(descriptor, { root, env, run, door, label: "install" });
289
+ if (descriptor.kind === PAYLOAD_ROOT_KIND) {
290
+ const checked = validatePayloadRootDescriptor(descriptor, platform);
291
+ const source = path.resolve(root, checked.sourceDirectory);
292
+ const inside = path.relative(path.resolve(root), source);
293
+ if (inside === "" || inside.startsWith("..") || path.isAbsolute(inside)) throw new Error("payload-root sourceDirectory must be a folder inside the repository");
294
+ return installPayloadRoot(checked, { source, log: (line) => console.log(line) });
295
+ }
263
296
  if (descriptor.kind === "portable") return installPortableDevelopment(descriptor, { root, platform: platform === "win" ? "win32" : "darwin", env });
264
297
  if (platform === "win") {
265
298
  if (!descriptor.expectedInstalledPath) throw new Error("Windows Tauri installer requires expectedInstalledPath for installed verification");
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env node
2
+ // `right-release direct-release finalize --config <file> [--output-dir <dir>] [--dry-run]`: the finalize route of a direct (non-store) release
3
+ // (#1142). It composes the owner functions of direct-bootstrap.mjs, so an app keeps no staging or finalize script of its own:
4
+ //
5
+ // 1. optional payload archive: `createPortableArchive` zips `sourceDir` into `archive` for every asset that names a `sourceDir`;
6
+ // 2. `collectReleaseAsset` binds each archive to its SLSA provenance and CycloneDX SBOM (both validated against the archive's sha256);
7
+ // 3. `materializeDirectRelease` writes checksums.json, the release manifest and its detached Azure-signed catalog (Windows signing host);
8
+ // 4. `renderPowerShellBootstrap` writes install.ps1 (the signer the manifest was just signed with is the one it accepts), checked by
9
+ // `validatePowerShellBootstrap`, and `planBootstrapPublication` writes the bootstrap publication plan (publication is its own step).
10
+ //
11
+ // directRelease: {
12
+ // product: "coderight-engine", repository: "owner/repo", // GitHub repository holding the immutable release assets
13
+ // minimumBootstrapVersion: "1.0.0", bootstrapVersion: "1.0.0",
14
+ // outputDir: "dist/direct-release", // optional (default); --output-dir overrides
15
+ // assets: [{ target: "windows-x86_64", name: "engine-win-x64.zip", archive: "dist/engine-win-x64.zip", sourceDir?: "dist/payload",
16
+ // executablePath: "bin/engine.exe", nativeSignaturePolicy: "authenticode-valid",
17
+ // provenance: "dist/engine-win-x64.intoto.jsonl", sbom: "dist/engine-win-x64.cdx.json" }],
18
+ // bootstrap: { installRootSubdir, executablePath, activationArgs, statusArgs, preflightArgs?, expectedStatusKind? | healthAssertions?,
19
+ // expectedStatus?, priorExecutableMinVersion?, allowLocalReleaseRoot? }
20
+ // }
21
+ //
22
+ // The release version is the config's `version`; the source commit is HEAD of a clean checkout. `--dry-run` validates the config and every
23
+ // input file and signs, writes and uploads nothing. Uploads are not part of this route (the R2 upload is its own step).
24
+ import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
25
+ import path from "node:path";
26
+ import { pathToFileURL } from "node:url";
27
+ import { spawnSync } from "./background-process.mjs";
28
+ import { CommandSpecError, loadAppConfig, relativeInside } from "./command-spec.mjs";
29
+ import { collectReleaseAsset, createPortableArchive, materializeDirectRelease, planBootstrapPublication, renderPowerShellBootstrap, validatePowerShellBootstrap } from "./direct-bootstrap.mjs";
30
+ import { defaultReleaseConfigFile } from "./release-config.mjs";
31
+ import { assertCleanSource } from "./source-gate.mjs";
32
+
33
+ const fail = (message) => { throw new CommandSpecError(message); };
34
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
35
+ const KEYS = ["product", "repository", "minimumBootstrapVersion", "bootstrapVersion", "outputDir", "assets", "bootstrap"];
36
+ const ASSET_KEYS = ["target", "name", "archive", "sourceDir", "executablePath", "nativeSignaturePolicy", "provenance", "sbom"];
37
+ const BOOTSTRAP_KEYS = ["installRootSubdir", "executablePath", "activationArgs", "statusArgs", "preflightArgs", "expectedStatusKind", "expectedStatus", "healthAssertions", "priorExecutableMinVersion", "allowLocalReleaseRoot"];
38
+
39
+ /** Validate `directRelease` and return it with every path checked as app-relative. The deeper contracts are the owner functions' own. */
40
+ export function resolveDirectReleaseOptions(config, flags = {}) {
41
+ const declared = config?.directRelease;
42
+ if (!isObject(declared)) fail("no directRelease block in the release config; see right-release direct-release --help");
43
+ const unknown = Object.keys(declared).filter((key) => !KEYS.includes(key));
44
+ if (unknown.length) fail(`directRelease has unknown key(s): ${unknown.join(", ")} (allowed: ${KEYS.join(", ")})`);
45
+ for (const key of ["product", "repository", "minimumBootstrapVersion", "bootstrapVersion"]) if (typeof declared[key] !== "string" || !declared[key]) fail(`directRelease.${key} is required`);
46
+ if (typeof config.version !== "string" || !config.version) fail("the release config has no version");
47
+ const outputDir = relativeInside(flags.outputDir ?? declared.outputDir ?? "dist/direct-release", "directRelease.outputDir");
48
+ if (!Array.isArray(declared.assets) || declared.assets.length === 0) fail("directRelease.assets must list at least one asset");
49
+ const assets = declared.assets.map((asset, index) => {
50
+ const where = `directRelease.assets[${index}]`;
51
+ if (!isObject(asset)) fail(`${where} must be an object`);
52
+ const bad = Object.keys(asset).filter((key) => !ASSET_KEYS.includes(key));
53
+ if (bad.length) fail(`${where} has unknown key(s): ${bad.join(", ")} (allowed: ${ASSET_KEYS.join(", ")})`);
54
+ for (const key of ["target", "name", "archive", "executablePath", "nativeSignaturePolicy", "provenance", "sbom"]) if (typeof asset[key] !== "string" || !asset[key]) fail(`${where}.${key} is required`);
55
+ for (const key of ["archive", "sourceDir", "provenance", "sbom"]) if (asset[key] !== undefined) relativeInside(asset[key], `${where}.${key}`);
56
+ return asset;
57
+ });
58
+ if (!isObject(declared.bootstrap)) fail("directRelease.bootstrap is required (installRootSubdir, executablePath, activationArgs, statusArgs, health)");
59
+ const badBootstrap = Object.keys(declared.bootstrap).filter((key) => !BOOTSTRAP_KEYS.includes(key));
60
+ if (badBootstrap.length) fail(`directRelease.bootstrap has unknown key(s): ${badBootstrap.join(", ")} (allowed: ${BOOTSTRAP_KEYS.join(", ")})`);
61
+ return { ...declared, outputDir, assets, version: config.version };
62
+ }
63
+
64
+ const gitText = (cwd, args) => {
65
+ const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true });
66
+ if (result.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${result.stderr || result.stdout}`);
67
+ return String(result.stdout ?? "");
68
+ };
69
+
70
+ /** Finalize the direct release for the app at `appRoot`. Returns what was written (or would be, under `dryRun`). */
71
+ export function finalizeDirectRelease({ appRoot, config, flags = {}, dryRun = false, repoRoot = gitText(appRoot, ["rev-parse", "--show-toplevel"]).trim() }) {
72
+ const options = resolveDirectReleaseOptions(config, flags);
73
+ const inApp = (relative) => path.join(appRoot, relative);
74
+ for (const asset of options.assets) {
75
+ if (asset.sourceDir !== undefined && !(existsSync(inApp(asset.sourceDir)) && statSync(inApp(asset.sourceDir)).isDirectory())) fail(`${asset.name}: sourceDir ${asset.sourceDir} is not a directory`);
76
+ if (asset.sourceDir === undefined && !existsSync(inApp(asset.archive))) fail(`${asset.name}: archive ${asset.archive} does not exist (name a sourceDir to have it built)`);
77
+ for (const key of ["provenance", "sbom"]) if (!existsSync(inApp(asset[key]))) fail(`${asset.name}: ${key} ${asset[key]} does not exist`);
78
+ }
79
+ if (dryRun) return { dryRun: true, product: options.product, version: options.version, assets: options.assets.map((asset) => asset.name), outputDir: inApp(options.outputDir) };
80
+ assertCleanSource({ status: gitText(repoRoot, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]), commandId: "right-release direct-release finalize" });
81
+ const sourceCommit = gitText(repoRoot, ["rev-parse", "HEAD"]).trim();
82
+ const outputDir = inApp(options.outputDir);
83
+ mkdirSync(outputDir, { recursive: true });
84
+ const tag = `v${options.version}`;
85
+ const assets = options.assets.map((asset) => {
86
+ if (asset.sourceDir !== undefined) createPortableArchive({ sourceDir: inApp(asset.sourceDir), outputPath: inApp(asset.archive) });
87
+ return collectReleaseAsset({
88
+ target: asset.target,
89
+ name: asset.name,
90
+ url: `https://github.com/${options.repository}/releases/download/${tag}/${asset.name}`,
91
+ archivePath: inApp(asset.archive),
92
+ executablePath: asset.executablePath,
93
+ nativeSignaturePolicy: asset.nativeSignaturePolicy,
94
+ provenancePath: inApp(asset.provenance),
95
+ sbomPath: inApp(asset.sbom),
96
+ });
97
+ });
98
+ const release = materializeDirectRelease({
99
+ outputDir,
100
+ manifestInput: { product: options.product, version: options.version, tag, sourceCommit, minimumBootstrapVersion: options.minimumBootstrapVersion, assets },
101
+ });
102
+ const script = renderPowerShellBootstrap({
103
+ product: options.product,
104
+ repository: options.repository,
105
+ bootstrapVersion: options.bootstrapVersion,
106
+ acceptedManifestSigners: [release.signing.signer],
107
+ ...options.bootstrap,
108
+ });
109
+ const validation = validatePowerShellBootstrap(script, { product: options.product, acceptedSignerIds: [release.signing.signer.id] });
110
+ if (!validation.valid) throw new Error(`generated bootstrap violates its own contract: ${validation.errors.join("; ")}`);
111
+ const scriptPath = path.join(outputDir, "install.ps1");
112
+ writeFileSync(scriptPath, script);
113
+ const plan = planBootstrapPublication({ product: options.product, bootstrapVersion: options.bootstrapVersion, scriptPath });
114
+ const planPath = path.join(outputDir, "bootstrap-publication-plan.json");
115
+ writeFileSync(planPath, `${JSON.stringify(plan, null, 2)}\n`);
116
+ return { dryRun: false, product: options.product, version: options.version, sourceCommit, outputDir, manifestPath: release.manifestPath, signaturePath: release.signaturePath, scriptPath, planPath, bootstrapSha256: plan.sha256 };
117
+ }
118
+
119
+ export function parseDirectReleaseArgs(argv) {
120
+ const opts = { config: defaultReleaseConfigFile(), outputDir: undefined, dryRun: false };
121
+ const [operation, ...rest] = argv;
122
+ if (operation !== "finalize") throw new Error("expected: direct-release finalize [--config <file>] [--output-dir <dir>] [--dry-run]");
123
+ for (let i = 0; i < rest.length; i += 1) {
124
+ const arg = rest[i];
125
+ if (arg === "--config" || arg === "--output-dir") {
126
+ const value = rest[i + 1];
127
+ if (!value || value.startsWith("--")) throw new Error(`${arg} needs a value`);
128
+ opts[arg === "--output-dir" ? "outputDir" : "config"] = value;
129
+ i += 1;
130
+ } else if (arg === "--dry-run") opts.dryRun = true;
131
+ else throw new Error(`unknown direct-release argument: ${arg}`);
132
+ }
133
+ return opts;
134
+ }
135
+
136
+ export async function main(argv = process.argv.slice(2)) {
137
+ const opts = parseDirectReleaseArgs(argv);
138
+ const { config, appRoot } = await loadAppConfig(opts.config);
139
+ const outcome = finalizeDirectRelease({ appRoot, config, flags: { outputDir: opts.outputDir }, dryRun: opts.dryRun });
140
+ if (outcome.dryRun) {
141
+ console.log(`right-release direct-release finalize dry-run: ${outcome.product} ${outcome.version}: ${outcome.assets.join(", ")} -> ${outcome.outputDir}; nothing signed or written`);
142
+ return 0;
143
+ }
144
+ console.log(`right-release direct-release finalize: ${outcome.product} ${outcome.version} at ${outcome.sourceCommit.slice(0, 12)}`);
145
+ console.log(`manifest: ${outcome.manifestPath}\nsignature: ${outcome.signaturePath}\nbootstrap: ${outcome.scriptPath} (sha256 ${outcome.bootstrapSha256})\nplan: ${outcome.planPath}`);
146
+ return 0;
147
+ }
148
+
149
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
150
+ main().then((code) => { process.exitCode = code; }, (error) => {
151
+ console.error(`right-release direct-release: ${error.code ? `[${error.code}] ` : ""}${error.message}`);
152
+ process.exitCode = 1;
153
+ });
154
+ }
package/disk-policy.mjs CHANGED
@@ -219,6 +219,22 @@ export function scratchRoots(policy, { platform = process.platform, env = proces
219
219
  return out;
220
220
  }
221
221
 
222
+ /**
223
+ * The run-output folder of one app: `<APP>_SCRATCH` (the app's own override, an absolute path) when set, else `<first existing policy scratch root>/<app>`.
224
+ * Throws when neither exists: no drive is ever hard coded (rightkit#816, the reader Pulse kept as scripts/release/scratch-root.mjs).
225
+ */
226
+ export function appScratchRoot(app, { policy = readDiskPolicy(), platform = process.platform, env = process.env, home = os.homedir() } = {}) {
227
+ if (typeof app !== "string" || !/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(app)) throw new Error(`appScratchRoot: ${JSON.stringify(app)} is not an app name`);
228
+ const override = env[`${app.toUpperCase().replaceAll("-", "_")}_SCRATCH`];
229
+ if (override) {
230
+ if (!path.isAbsolute(override)) throw new Error(`${app.toUpperCase().replaceAll("-", "_")}_SCRATCH must be an absolute path`);
231
+ return override;
232
+ }
233
+ const root = scratchRoots(policy, { platform, env, home }).find((candidate) => existsSync(candidate));
234
+ if (!root) throw new Error(`no scratch root for ${app}: set ${app.toUpperCase().replaceAll("-", "_")}_SCRATCH, or create the disk-policy scratch folder (${scratchRoots(policy, { platform, env, home }).join(", ") || "none declared for this platform"})`);
235
+ return path.join(root, app);
236
+ }
237
+
222
238
  /** Create missing scratch roots (only when their parent volume exists). Returns the roots that exist afterwards. */
223
239
  export function ensureScratchRoots({ policy, platform = process.platform, env = process.env, home = os.homedir() } = {}) {
224
240
  const ready = [];
@@ -0,0 +1,134 @@
1
+ // Cargo feature coverage for the gate's Rust plan (rightkit#1231): feature-gated code is never left unchecked.
2
+ //
3
+ // Reported by RightKit's Pulse D15: pulse 69b649a3 passed the Dell pre-push gate with clippy::needless_return at windows/src/send.rs:2933
4
+ // under #[cfg(feature = "qa-views")]. A crate that declared no `featureSets` in ci/gate.config.json was linted with its default features
5
+ // only, and its QA-gated code was never linted.
6
+ //
7
+ // 1. `effectiveCrateFeatures`: a crate that declares no `featureSets` and whose Cargo.toml declares features beyond `default` is linted
8
+ // twice, with its default features and with `--all-features` (the second also stands in for the `check-features` row, since clippy
9
+ // type-checks everything `cargo check` does). A crate whose features conflict declares its sets explicitly.
10
+ // 2. `featureCoverageProblems`: every feature a crate's Cargo.toml declares must be enabled by at least one set of its plan (the
11
+ // default features, a declared set, or a generated one); FEATURE_UNCOVERED names the crate and the feature.
12
+ //
13
+ // Dependency-free by design: scan-digest.mjs-style callers (the credentialed receipt verifiers) import it.
14
+
15
+ /** The feature table of a Cargo.toml: a Map of feature name to its array of members ("other", "dep:x", "x/feat", "x?/feat"). `default` included. */
16
+ export function manifestFeatures(text) {
17
+ const out = new Map();
18
+ const src = String(text ?? "").replace(/^/, "");
19
+ let i = 0;
20
+ const n = src.length;
21
+ let inFeatures = false;
22
+ // Walk the text once, string- and comment-aware, so a `[features]` mentioned in a string or comment, or a `#` inside a quoted member, is never misread.
23
+ const skipLine = () => { while (i < n && src[i] !== "\n") i += 1; };
24
+ const readString = () => {
25
+ const quote = src[i]; i += 1; let value = "";
26
+ while (i < n && src[i] !== quote && src[i] !== "\n") { if (quote === '"' && src[i] === "\\" && i + 1 < n) { value += src[i + 1]; i += 2; } else { value += src[i]; i += 1; } }
27
+ if (src[i] === quote) i += 1;
28
+ return value;
29
+ };
30
+ const skipSpace = () => { while (i < n && /\s/.test(src[i])) i += 1; };
31
+ while (i < n) {
32
+ skipSpace();
33
+ if (i >= n) break;
34
+ if (src[i] === "#") { skipLine(); continue; }
35
+ if (src[i] === "[") {
36
+ const double = src[i + 1] === "[";
37
+ const close = src.indexOf("]", i);
38
+ const header = close < 0 ? "" : src.slice(i + (double ? 2 : 1), close).trim().replace(/\s+/g, "");
39
+ inFeatures = !double && header === "features";
40
+ i = close < 0 ? n : close + (double ? 2 : 1);
41
+ skipLine();
42
+ continue;
43
+ }
44
+ // A key: bare or quoted, then `=`.
45
+ let key = "";
46
+ if (src[i] === '"' || src[i] === "'") key = readString();
47
+ else { while (i < n && !/[\s=]/.test(src[i])) { key += src[i]; i += 1; } }
48
+ skipSpace();
49
+ if (src[i] !== "=") { skipLine(); continue; }
50
+ i += 1; skipSpace();
51
+ if (src[i] === "[") {
52
+ i += 1; const members = [];
53
+ for (;;) {
54
+ skipSpace();
55
+ if (i >= n) break;
56
+ if (src[i] === "#") { skipLine(); continue; }
57
+ if (src[i] === "]") { i += 1; break; }
58
+ if (src[i] === '"' || src[i] === "'") members.push(readString());
59
+ else i += 1; // a comma
60
+ }
61
+ if (inFeatures && key !== "") out.set(key, members);
62
+ skipLine();
63
+ } else {
64
+ // Any other value (a string, a number, an inline table) is not a feature definition; read to the end of the line.
65
+ if (src[i] === '"' || src[i] === "'") readString();
66
+ skipLine();
67
+ }
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /** The feature names (never `default`) a Cargo.toml declares. */
73
+ export const declaredFeatureNames = (text) => [...manifestFeatures(text).keys()].filter((name) => name !== "default");
74
+
75
+ /** The features one cargo feature-flag set (`--all-features`, `--no-default-features`, `--features a,b`, `--features=a`, `-F a`) enables, closure included. */
76
+ export function featuresEnabledBy(features, set) {
77
+ const names = new Set(features.keys());
78
+ let all = false; let noDefault = false; const asked = [];
79
+ const words = Array.isArray(set) ? set : [];
80
+ for (let k = 0; k < words.length; k += 1) {
81
+ const w = String(words[k]);
82
+ if (w === "--all-features") all = true;
83
+ else if (w === "--no-default-features") noDefault = true;
84
+ else if (w === "--features" || w === "-F") { asked.push(...String(words[k + 1] ?? "").split(/[,\s]+/)); k += 1; }
85
+ else if (w.startsWith("--features=")) asked.push(...w.slice("--features=".length).split(/[,\s]+/));
86
+ else if (w.startsWith("-F") && w.length > 2) asked.push(...w.slice(2).split(/[,\s]+/));
87
+ }
88
+ if (all) return new Set(names);
89
+ const enabled = new Set();
90
+ const queue = [...asked.filter(Boolean)];
91
+ if (!noDefault && names.has("default")) queue.push("default");
92
+ while (queue.length) {
93
+ const name = queue.pop();
94
+ if (enabled.has(name)) continue;
95
+ // `pkg/feature` and `pkg?/feature` name a dependency's feature; `dep:pkg` an optional dependency: none is one of this crate's own features.
96
+ if (name.includes("/") || name.startsWith("dep:")) continue;
97
+ enabled.add(name);
98
+ for (const member of features.get(name) ?? []) queue.push(member);
99
+ }
100
+ return enabled;
101
+ }
102
+
103
+ /** A crate's features that none of `sets` enables: `[]` when every declared feature is covered. */
104
+ export function uncoveredFeatures(manifestText, sets) {
105
+ const features = manifestFeatures(manifestText);
106
+ const declared = [...features.keys()].filter((name) => name !== "default");
107
+ const covered = new Set();
108
+ for (const set of sets) for (const f of featuresEnabledBy(features, set)) covered.add(f);
109
+ return declared.filter((name) => !covered.has(name)).sort();
110
+ }
111
+
112
+ /** The FEATURE_UNCOVERED lines of one crate (`name`, its manifest text, every feature set its plan runs). */
113
+ export function featureCoverageProblems({ name, manifestText, sets }) {
114
+ const missing = uncoveredFeatures(manifestText, sets);
115
+ const planned = sets.map((s) => (s.length ? s.join(" ") : "default features")).join("; ");
116
+ return missing.map((feature) => `FEATURE_UNCOVERED ${name}: feature "${feature}" is enabled by none of the planned feature sets (${planned}); add a set that enables it to ci/gate.config.json rust.${name}.featureSets, or --all-features where the features do not conflict`);
117
+ }
118
+
119
+ /**
120
+ * `crateFeatures` (ci/gate.config.json `rust`) with the generated lint plan for one crate: when the crate declares no `featureSets` and its
121
+ * Cargo.toml declares a feature beyond `default`, `autoAllFeatures: true` is set on its entry. rustCratePlan reads that marker (scan-digest.mjs).
122
+ * `manifestOf(name)` returns the crate's Cargo.toml text or null. Pure.
123
+ */
124
+ export function effectiveCrateFeatures({ crateFeatures = {}, units, manifestOf }) {
125
+ const out = { ...crateFeatures };
126
+ for (const name of units) {
127
+ const own = crateFeatures?.[name] ?? {};
128
+ if (Array.isArray(own.featureSets) && own.featureSets.length) continue;
129
+ let text = null;
130
+ try { text = manifestOf(name); } catch { text = null; }
131
+ if (typeof text === "string" && declaredFeatureNames(text).length) out[name] = { ...own, autoAllFeatures: true };
132
+ }
133
+ return out;
134
+ }
@@ -0,0 +1,38 @@
1
+ // The per-scan coverage report of one gate run (rightkit#1463, ADR-001 section 8): every planned scan is listed as `hit` (answered from the
2
+ // result cache), `ran` (executed, pass or fail) or `skipped` (not run: deferred, not reached, or outside the run's classes), with the cache key
3
+ // it was looked up under and the reason. A cache that never hits is then visible in the report, not only in the timings.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+
7
+ export const COVERAGE_SCHEMA = "rightkit.gate-coverage/1";
8
+
9
+ /**
10
+ * The report for `plan` (the planned scans, `plan.scans`) and `scanResult` (runScans' rows). `keys` is a Map of scan id -> the input key the cache
11
+ * looked the scan up under (null or absent: the scan is never cached or no key could be formed). `classes` are the classes this pass runs.
12
+ */
13
+ export function buildCoverageReport({ plan, scanResult, keys = new Map(), classes = ["A", "B"], commit = null, startedAt = null, endedAt = null }) {
14
+ const rows = new Map((scanResult?.scans ?? []).map((row) => [row.id, row]));
15
+ const scans = (plan?.scans ?? []).map((scan) => {
16
+ const row = rows.get(scan.id);
17
+ const key = keys.get(scan.id) ?? null;
18
+ if (row) {
19
+ if (row.cached === true) return { id: scan.id, class: scan.class, coverage: "hit", status: row.status, key, reason: row.detail ?? "answered from the result cache" };
20
+ if (row.status === "pass" || row.status === "fail") return { id: scan.id, class: scan.class, coverage: "ran", status: row.status, key, reason: key === null ? "no cache key (this scan is never cached, or no key could be formed)" : "no cached result for this key", ...(row.code ? { code: row.code } : {}) };
21
+ return { id: scan.id, class: scan.class, coverage: "skipped", status: row.status, key, reason: row.detail ?? row.status };
22
+ }
23
+ return { id: scan.id, class: scan.class, coverage: "skipped", status: "not-in-pass", key, reason: classes.includes(scan.class) ? "planned but no result was returned" : `class ${scan.class} is not part of this pass (classes ${classes.join("+")})` };
24
+ });
25
+ const count = (what) => scans.filter((s) => s.coverage === what).length;
26
+ return { schema: COVERAGE_SCHEMA, commit, startedAt, endedAt, totals: { planned: scans.length, hit: count("hit"), ran: count("ran"), skipped: count("skipped") }, scans };
27
+ }
28
+
29
+ /** Writes the report as `<dir>/<name>.json` (the directory is created); returns the path. */
30
+ export function writeCoverageReport({ dir, name, report, write = fs.writeFileSync, mkdir = fs.mkdirSync }) {
31
+ mkdir(dir, { recursive: true });
32
+ const file = path.join(dir, `${name}.json`);
33
+ write(file, `${JSON.stringify(report, null, 2)}\n`);
34
+ return file;
35
+ }
36
+
37
+ /** Wall-clock seconds as printed in a log line, one decimal. */
38
+ export const seconds = (ms) => `${(Math.max(0, ms) / 1000).toFixed(1)}s`;
package/gate-stages.mjs CHANGED
@@ -48,6 +48,7 @@ export const STAGE_SOURCES = Object.freeze({
48
48
  release: { compiles: false, packages: false, source: "publisher", basis: "--to release runs only in the trusted publisher on hosted CI with its normal checkout (docs/GATE-CONTRACT.md), and only uploads sealed bytes" },
49
49
  dev: { compiles: true, packages: false, source: "snapshot" },
50
50
  test: { compiles: true, packages: false, source: "snapshot" },
51
+ render: { compiles: true, packages: false, source: "snapshot" },
51
52
  stage: { compiles: false, packages: false, source: "sealed", basis: "stage packs the sealed directory and its receipt into the publisher's draft release; it compiles nothing" },
52
53
  // Row 7.06a: a unit stage builds the selected commit's snapshot on every host (runUnitSnapshot); hosted CI keeps its runner checkout, which is the commit.
53
54
  "unit:check": { compiles: false, packages: false, source: "snapshot" },
package/ghsa-audit.mjs ADDED
@@ -0,0 +1,95 @@
1
+ // Class A `ghsa-audit`: the GitHub advisory database, beside cargo-audit's RustSec (rightkit#1461).
2
+ //
3
+ // cargo-audit and cargo-deny read the pinned RustSec database only. A GitHub advisory RustSec has not yet copied (zip 9.0.4, GHSA-m665-v7pm-7grj,
4
+ // critical, 2026-10-28; Pulse 5d8dac65 passed every cargo-audit scan the week GitHub flagged it) is invisible to both. This scan asks OSV
5
+ // (api.osv.dev, which serves the GitHub advisory database as GHSA-* records for the crates.io ecosystem) about every crates.io package of a
6
+ // workspace's Cargo.lock at the locked version, and a GHSA advisory fails the scan exactly like a RustSec vulnerability does.
7
+ //
8
+ // - A GHSA record that lists a RUSTSEC alias is RustSec's too: cargo-audit and cargo-deny judge it (and the repository's reviewed ignore ledger
9
+ // decides it), so this scan never double-reports it. A withdrawn record is skipped. Every other GHSA record fails.
10
+ // - Cached like the other advisory scans (GATE-CONTRACT GC-A19): by the lockfile's bytes and the UTC day, under the advisory cache root. A
11
+ // run with no cache (the door's `live-scans` refresh) asks again.
12
+ // - Offline follows cargo-audit's rule: no same-day cached answer and no network means the scan fails (code ADVISORY_DB); it never passes
13
+ // unchecked and never falls back to another source.
14
+ import crypto from "node:crypto";
15
+ import fs from "node:fs";
16
+ import path from "node:path";
17
+
18
+ const OSV = "https://api.osv.dev/v1";
19
+ const REGISTRY_SOURCE = "registry+https://github.com/rust-lang/crates.io-index";
20
+ const BATCH = 500;
21
+ const TIMEOUT_MS = 30_000;
22
+
23
+ /** The `[[package]]` entries of a Cargo.lock that come from crates.io: [{ name, version }], sorted and unique. Path and git packages have no advisory here. */
24
+ export function registryPackages(lockText) {
25
+ const out = new Map();
26
+ for (const block of String(lockText ?? "").split(/^\[\[package\]\]\s*$/m).slice(1)) {
27
+ const name = /^name\s*=\s*"([^"]+)"/m.exec(block)?.[1];
28
+ const version = /^version\s*=\s*"([^"]+)"/m.exec(block)?.[1];
29
+ const source = /^source\s*=\s*"([^"]+)"/m.exec(block)?.[1];
30
+ if (name && version && source === REGISTRY_SOURCE) out.set(`${name}@${version}`, { name, version });
31
+ }
32
+ return [...out.values()].sort((a, b) => (a.name === b.name ? (a.version < b.version ? -1 : 1) : a.name < b.name ? -1 : 1));
33
+ }
34
+
35
+ const utcDay = (now) => new Date(now()).toISOString().slice(0, 10);
36
+
37
+ async function osvJson(fetchFn, url, init) {
38
+ const r = await fetchFn(url, { ...init, signal: AbortSignal.timeout(TIMEOUT_MS) });
39
+ if (!r.ok) throw new Error(`${url} answered HTTP ${r.status}`);
40
+ return r.json();
41
+ }
42
+
43
+ /** One OSV batch query over `packages`, following page tokens: a Map of "name@version" to the ids OSV lists for it. */
44
+ async function queryIds(fetchFn, packages) {
45
+ const found = new Map();
46
+ for (let i = 0; i < packages.length; i += BATCH) {
47
+ let pending = packages.slice(i, i + BATCH).map((p) => ({ p, token: null }));
48
+ while (pending.length) {
49
+ const body = { queries: pending.map(({ p, token }) => ({ package: { name: p.name, ecosystem: "crates.io" }, version: p.version, ...(token ? { page_token: token } : {}) })) };
50
+ const answer = await osvJson(fetchFn, `${OSV}/querybatch`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
51
+ if (!Array.isArray(answer?.results) || answer.results.length !== pending.length) throw new Error("OSV returned a batch answer that does not match the query");
52
+ const next = [];
53
+ answer.results.forEach((res, k) => {
54
+ const key = `${pending[k].p.name}@${pending[k].p.version}`;
55
+ for (const v of res?.vulns ?? []) if (typeof v?.id === "string") found.set(key, [...(found.get(key) ?? []), v.id]);
56
+ if (res?.next_page_token) next.push({ p: pending[k].p, token: res.next_page_token });
57
+ });
58
+ pending = next;
59
+ }
60
+ }
61
+ return found;
62
+ }
63
+
64
+ /**
65
+ * The GitHub-advisory findings for a Cargo.lock: `{ findings: ["vulnerable: zip 9.0.4 GHSA-... (summary)", ...], checked }`. Throws when OSV cannot be asked.
66
+ * `fetchFn` is fetch; `cacheDir` (optional) holds the same-UTC-day answer for these exact lock bytes.
67
+ */
68
+ export async function ghsaFindings({ lockText, fetchFn = globalThis.fetch, cacheDir = null, now = () => Date.now() }) {
69
+ const packages = registryPackages(lockText);
70
+ const cacheFile = cacheDir ? path.join(cacheDir, `${crypto.createHash("sha256").update(String(lockText)).digest("hex")}-${utcDay(now)}.json`) : null;
71
+ if (cacheFile) {
72
+ try { const hit = JSON.parse(fs.readFileSync(cacheFile, "utf8")); if (Array.isArray(hit?.findings) && Number.isInteger(hit.checked)) return { findings: hit.findings, checked: hit.checked, cached: true }; } catch { /* a miss */ }
73
+ }
74
+ if (!packages.length) return { findings: [], checked: 0, cached: false };
75
+ if (typeof fetchFn !== "function") throw new Error("no fetch is available to ask the GitHub advisory database");
76
+ const ids = await queryIds(fetchFn, packages);
77
+ const details = new Map();
78
+ const findings = [];
79
+ for (const [key, list] of [...ids.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1))) {
80
+ for (const id of [...new Set(list)].sort()) {
81
+ if (id.startsWith("RUSTSEC-")) continue; // RustSec's own record: cargo-audit and cargo-deny judge it, with the repository's ignore ledger
82
+ if (!details.has(id)) details.set(id, await osvJson(fetchFn, `${OSV}/vulns/${encodeURIComponent(id)}`, { method: "GET" }));
83
+ const v = details.get(id);
84
+ if (v?.withdrawn) continue;
85
+ if ((v?.aliases ?? []).some((a) => String(a).startsWith("RUSTSEC-"))) continue;
86
+ const [name, version] = [key.slice(0, key.lastIndexOf("@")), key.slice(key.lastIndexOf("@") + 1)];
87
+ const summary = typeof v?.summary === "string" ? ` (${v.summary.replace(/\s+/g, " ").trim().slice(0, 120)})` : "";
88
+ findings.push(`vulnerable: ${name} ${version} ${id}${summary}`);
89
+ }
90
+ }
91
+ if (cacheFile) {
92
+ try { fs.mkdirSync(cacheDir, { recursive: true }); fs.writeFileSync(cacheFile, `${JSON.stringify({ findings, checked: packages.length })}\n`); } catch { /* never fails the scan */ }
93
+ }
94
+ return { findings, checked: packages.length, cached: false };
95
+ }