@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
package/release.mjs CHANGED
@@ -13,6 +13,10 @@ import { validateRightKitCargoContract } from "./cargo-contract.mjs";
13
13
  import { assertCargoProfileContract } from "./cargo-profile-contract.mjs";
14
14
  import { assertQaAdoption, assertQaBackdoorContract } from "./qa-contract.mjs";
15
15
  import { assertLegalReleaseContract } from "./legal-contract.mjs";
16
+ import { assertSecurityPolicy } from "./security-policy.mjs";
17
+ import { refreshRuntimeManifests, validateRuntimeManifestPaths } from "./runtime-manifest-refresh.mjs";
18
+ import { assertStageReceiptGuard, validateStageReceiptConfig } from "./stage-receipt.mjs";
19
+ import { assertPluginMatchesApp } from "./plugin-delivery.mjs";
16
20
  import { DECLARED_UNRELATED_POLICY, declaredUnrelatedRefusal, releaseArtifactPaths } from "./hosted-workflow-policy.mjs";
17
21
  import { assertNativeIosPrepareHasManifest, assertPrimaryReleaseCheckout, dirtyBuildInputs, resolveReleaseBuildInputs } from "./release-invocation.mjs";
18
22
  import { gitRootOf, isSnapshotSource, resolveReleaseSource, sourceRootOf } from "./release-source-identity.mjs";
@@ -96,6 +100,9 @@ let rightKitVerifiedNpm = new Map();
96
100
  const FORBIDDEN_RIGHTKIT_SPEC = /^(?:git|file|link|workspace):|github|github\.com/i;
97
101
  const WINDOWS_NSIS_SIGNING_CONTRACT = "windows-raw-exe-authenticode-before-nsis-v1";
98
102
  const WINDOWS_PORTABLE_SIGNING_CONTRACT = "windows-raw-exe-authenticode-before-portable-v1";
103
+ // A native multi-exe payload (no Tauri bundle) packed by its own NSIS script (rightkit#428, #871): every payload file is Authenticode-signed first,
104
+ // the installer is assembled from the signed bytes (`right-release nsis-pack`), each signed file is proved embedded, then the installer is signed.
105
+ const WINDOWS_PAYLOAD_SIGNING_CONTRACT = "windows-payload-authenticode-before-nsis-v1";
99
106
  const DEFAULT_NOTARIZATION_TIMEOUT_MS = 30 * 60 * 1000;
100
107
 
101
108
  // Apple Developer ID and notary secrets: the only secrets the signing jobs of the managed release chain
@@ -367,7 +374,10 @@ await check("split-artifact-paths", ["target"], () => {
367
374
  const legalCheck = await check("legal-contract", [], () => (config.legal
368
375
  ? assertLegalReleaseContract(root, config.legal, config.app ?? path.basename(root), opts.platform)
369
376
  : null));
377
+ // CSP and Tauri capability drift (#1136): files only, the same row in the doctor and the build.
378
+ await check("security-policy", [], () => (config.security ? assertSecurityPolicy(root, config.security, config.app ?? path.basename(root)) : null));
370
379
  const legalContract = legalCheck.ok ? legalCheck.value : null;
380
+ let runtimeManifests = []; // validated sign.runtimeManifests: refreshed after nested/sidecar signing, before the app is sealed (rightkit#722)
371
381
  let macSigning; // validated macOS sign.prePackageFiles / sign.nestedCode (mac only)
372
382
  let mediaSidecarConfig = null; // validated targets.<mac|win>.mediaSidecar (rightkit-ffmpeg decode sidecar)
373
383
  let externalBinConfig = null; // validated targets.<mac|win>.externalBin (generic Tauri externalBin sidecars, #270)
@@ -390,11 +400,24 @@ if (!rejectBlocked("target-checks", ["target"], "the target checks (signed, medi
390
400
  try { externalBinConfig = validateExternalBinConfig(target.externalBin, { platform: opts.platform, reservedNames: mediaSidecarConfig?.tools ?? [] }); } catch (error) { throw new Error(`${app} ${opts.platform} ${error.message}`); }
391
401
  });
392
402
  }
403
+ if (target.sign?.runtimeManifests !== undefined) {
404
+ if (opts.platform !== "mac" && opts.platform !== "win") reject("runtime-manifests", `${app} ${opts.platform} does not support sign.runtimeManifests (mac and win only)`);
405
+ else await check("runtime-manifests", [], () => { try { runtimeManifests = validateRuntimeManifestPaths(target.sign.runtimeManifests); } catch (error) { throw new Error(`${app} ${opts.platform} ${error.message}`); } });
406
+ }
407
+ if (target.plugin !== undefined) {
408
+ // The app's agent plugin ships with it and carries exactly the app's version (rightkit#1442).
409
+ await check("plugin", [], () => { try { assertPluginMatchesApp({ root, plugin: target.plugin, version: config.version }); } catch (error) { throw new Error(`${app} ${opts.platform} ${error.message}`); } });
410
+ }
411
+ if (target.sign?.stageReceipt !== undefined) {
412
+ if (opts.platform !== "mac" && opts.platform !== "win") reject("stage-receipt-guard", `${app} ${opts.platform} does not support sign.stageReceipt (mac and win only)`);
413
+ else await check("stage-receipt-guard", [], () => { try { validateStageReceiptConfig(target.sign.stageReceipt); } catch (error) { throw new Error(`${app} ${opts.platform} ${error.message}`); } });
414
+ }
393
415
  if (opts.platform === "win") {
394
416
  const isNsis = target.signingContract === WINDOWS_NSIS_SIGNING_CONTRACT;
395
417
  const isPortable = target.signingContract === WINDOWS_PORTABLE_SIGNING_CONTRACT;
418
+ const isPayload = target.signingContract === WINDOWS_PAYLOAD_SIGNING_CONTRACT;
396
419
  const isMsix = target.signingContract === MSIX_SIGNING_CONTRACT;
397
- if (!isNsis && !isPortable && !isMsix) reject("win-signing-contract", `${app} win must declare signingContract: ${WINDOWS_NSIS_SIGNING_CONTRACT}, ${WINDOWS_PORTABLE_SIGNING_CONTRACT} or ${MSIX_SIGNING_CONTRACT}`);
420
+ if (!isNsis && !isPortable && !isPayload && !isMsix) reject("win-signing-contract", `${app} win must declare signingContract: ${WINDOWS_NSIS_SIGNING_CONTRACT}, ${WINDOWS_PAYLOAD_SIGNING_CONTRACT}, ${WINDOWS_PORTABLE_SIGNING_CONTRACT} or ${MSIX_SIGNING_CONTRACT}`);
398
421
  if (isMsix) {
399
422
  await check("win-msix", [], () => assertValidMsixTarget(target, app));
400
423
  } else {
@@ -409,6 +432,12 @@ if (!rejectBlocked("target-checks", ["target"], "the target checks (signed, medi
409
432
  }
410
433
  if (isNsis && !target.sign?.files?.length) reject("win-nsis-sign-files", `${app} win NSIS must declare sign.files for installer signing`);
411
434
  if (isNsis && rawFiles?.length && target.sign?.files?.length && rawFiles.some((file) => target.sign.files.includes(file))) reject("win-distinct-files", `${app} win raw EXE and installer signing files must be distinct`);
435
+ if (isPayload) {
436
+ if (!target.package?.cmd) reject("win-payload-package", `${app} win payload must declare package (the NSIS packing command, for example right-release nsis-pack)`);
437
+ if (!target.sign?.files?.length) reject("win-payload-sign-files", `${app} win payload must declare sign.files for installer signing`);
438
+ else if (rawFiles?.some((file) => target.sign.files.includes(file))) reject("win-distinct-files", `${app} win payload files and installer signing files must be distinct`);
439
+ if (rawFiles?.length && new Set(rawFiles.map((file) => path.basename(String(file)).toLowerCase())).size !== rawFiles.length) reject("win-payload-names", `${app} win payload sign.prePackageFiles must have distinct file names (each is proved embedded in the installer by its name)`);
440
+ }
412
441
  if (isPortable && target.sign?.files?.length) reject("win-portable-sign-files", `${app} win portable release must sign every executable through sign.prePackageFiles and omit sign.files`);
413
442
  }
414
443
  }
@@ -613,7 +642,7 @@ let prePackScanned = false; // set once a pre-pack payload scan has seen a nativ
613
642
  // prebuild-gates.mjs so `doctor --gates` runs the exact same code in the same order. They read the expanded target (and the
614
643
  // iOS spec), so a failed one of those blocks them.
615
644
  const prebuildBlocker = ["target", ...(opts.platform === "ios" ? ["ios-target"] : [])].find((name) => failedChecks.has(name));
616
- const { findings: prebuildFindings, devtoolsAllowance, inventoryText: releaseSwitchInventoryText } = prebuildBlocker
645
+ const { findings: prebuildFindings, devtoolsAllowance, inventoryText: releaseSwitchInventoryText, presenceAccepted: releasePresenceAccepted } = prebuildBlocker
617
646
  ? { findings: [{ name: "prebuild-gates", detail: `BLOCKED by ${prebuildBlocker}` }], devtoolsAllowance: { mode: "denied" }, inventoryText: null }
618
647
  : evaluatePrebuildGates({ root, config, target, platform: opts.platform, iosSpec, nativeIos, nativeAssembly, nativeFinalizer, strict: !opts.dryRun });
619
648
  if (problems.length || prebuildFindings.length) {
@@ -674,6 +703,8 @@ if (opts.platform === "win" && target.signingContract === MSIX_SIGNING_CONTRACT)
674
703
  const externalPlan = await prepareExternalBin(root);
675
704
  await runCommand(target.prePackage, root);
676
705
  for (const file of rawFiles) await mustExist(file, `missing raw EXE signing artifact: ${file}`);
706
+ // Opt-in (sign.stageReceipt): the staged files and every hand-assembled payload copy must still be the bytes the stage receipt recorded, and the receipt a release one.
707
+ if (target.sign?.stageReceipt && !opts.dryRun) { try { assertStageReceiptGuard({ root, config: target.sign.stageReceipt, mode: "release" }); } catch (error) { fail(error.message); } }
677
708
  const sidecarPre = sidecarPlan && !opts.dryRun ? verifyStagedSidecars(sidecarPlan) : [];
678
709
  const externalPre = externalPlan && !opts.dryRun ? verifyExternalBins(externalPlan) : [];
679
710
  const sidecarFiles = [...sidecarPre, ...externalPre].map((file) => file.stagedPath);
@@ -690,6 +721,10 @@ if (opts.platform === "win" && target.signingContract === MSIX_SIGNING_CONTRACT)
690
721
  console.log(`right-release: bundle marker ${receipt.bundle} ${receipt.alreadyPatched ? "already applied" : "applied"} at offset ${receipt.offset} in ${path.basename(receipt.file)}`);
691
722
  }
692
723
  await signWindows([...rawFiles, ...sidecarFiles], "raw-exe", root);
724
+ // Re-signed runtime files changed bytes: re-describe the bundled runtime manifest(s) before the installer wraps them (rightkit#722).
725
+ if (runtimeManifests.length && !opts.dryRun) {
726
+ try { refreshRuntimeManifests({ base: root, manifests: runtimeManifests, log: (line) => console.log(line) }); } catch (error) { fail(error.message); }
727
+ }
693
728
  if (sidecarPlan && !opts.dryRun) {
694
729
  const signed = Object.fromEntries(sidecarPre.map((file) => [file.tool, sidecarFileEvidence(file.stagedPath)]));
695
730
  writeMediaSidecarReceipt(root, buildMediaSidecarReceipt(sidecarPlan, sidecarPre, signed));
@@ -717,6 +752,8 @@ if (opts.platform === "win" && target.signingContract === MSIX_SIGNING_CONTRACT)
717
752
  // Resolve after prePackage: with storage governance the artifact may live only in RIGHT_RELEASE_ARTIFACT_DIR.
718
753
  const signingEntries = macSigning.entries.map((entry) => ({ ...entry, file: resolveReleaseArtifactPath(root, entry.file) }));
719
754
  for (const { file } of signingEntries) await mustExist(file, `missing macOS Developer ID signing artifact: ${file}`);
755
+ // Opt-in (sign.stageReceipt): refuse a dev receipt or a drifted staged / hand-assembled file before anything is signed.
756
+ if (target.sign?.stageReceipt && !opts.dryRun) { try { assertStageReceiptGuard({ root, config: target.sign.stageReceipt, mode: "release" }); } catch (error) { fail(error.message); } }
720
757
  assertNoQaControlBinaries("macOS signing set", signingEntries.map(({ file }) => file), { requireBinary: true, prePack: true });
721
758
  // The DMG is built from the .app (notarize.app / the signing set); a compressed DMG cannot be scanned afterwards.
722
759
  if (target.notarize.app) {
@@ -801,6 +838,18 @@ for (const rel of target.artifacts ?? []) {
801
838
 
802
839
  if (nativeFinalization) await completeNativeFinalization(nativeFinalization, { root, target, nativeAssembly });
803
840
 
841
+ if (opts.platform === "win" && target.signingContract === WINDOWS_PAYLOAD_SIGNING_CONTRACT) {
842
+ const files = target.sign.files.map((p) => resolveReleaseArtifactPath(root, p));
843
+ for (const file of files) await mustExist(file, `missing signing artifact: ${file}`);
844
+ await verifyWindowsPayloadEmbedding({ root, target, files });
845
+ await signWindows(files, "installer", root);
846
+ if (target.postSign) await runCommands(target.postSign, root);
847
+ if (target.updater?.artifacts?.length) {
848
+ const updaterFiles = [...new Set(target.updater.artifacts.map((artifact) => resolveReleaseArtifactPath(root, artifact.file)))];
849
+ await run("node", [SIGN_UPDATER, ...(opts.dryRun ? ["--dry-run"] : []), ...updaterFiles.flatMap((file) => ["--file", file])], root);
850
+ }
851
+ }
852
+
804
853
  if (opts.platform === "win" && target.signingContract === WINDOWS_NSIS_SIGNING_CONTRACT) {
805
854
  const files = target.sign.files.map((p) => resolveReleaseArtifactPath(root, p));
806
855
  for (const file of files) await mustExist(file, `missing signing artifact: ${file}`);
@@ -888,7 +937,7 @@ function assertNoQaControlBinaries(label, files, { requireBinary = false, prePac
888
937
  try {
889
938
  const stats = assertNoQaControl(files, label, { requireBinary, allowContentOnlyDevtools: devtoolsAllowance.mode === "content-only" });
890
939
  // D4 binary layer, same inputs: no test-mode marker and no S1-S4 selector name in any native binary.
891
- assertNoReleaseSwitches({ binaryPaths: files, devtools: devtoolsAllowance, inventoryText: releaseSwitchInventoryText ?? undefined, appForbid: config.releaseSwitches?.forbid ?? [], requireBinary: false }, `${label} (release switches)`);
940
+ assertNoReleaseSwitches({ binaryPaths: files, devtools: devtoolsAllowance, inventoryText: releaseSwitchInventoryText ?? undefined, appForbid: config.releaseSwitches?.forbid ?? [], requireBinary: false, presenceAccepted: releasePresenceAccepted ?? [] }, `${label} (release switches)`);
892
941
  if (prePack && stats.binaries > 0) prePackScanned = true;
893
942
  for (const opaque of stats.opaque) {
894
943
  console.log(`right-release: ${label}: ${opaque.kind.toUpperCase()} payload is compressed and cannot be scanned (${opaque.file}); the raw payload was scanned before packing`);
@@ -1188,11 +1237,14 @@ async function runInstall(pm, cwd) {
1188
1237
  else fail(`unsupported package manager: ${pm}`);
1189
1238
  }
1190
1239
 
1191
- async function runPackageScript(pm, script, cwd) {
1192
- if (script === false) return;
1240
+ async function runPackageScript(pm, script, cwd, options = {}) {
1241
+ if (script === false) return null;
1193
1242
  // A package script (a check or a web build) goes through the one door (build-launch.mjs): a broker job on a managed host.
1194
1243
  const target = buildLaunch(pm, ["run", script], { cwd, exists: existsSync });
1195
- await run(target.command, target.args, cwd, target.env ?? {});
1244
+ const output = await run(target.command, target.args, cwd, target.env ?? {}, options.captureStdout ? { captureStdout: true } : {});
1245
+ if (!options.captureStdout || opts.dryRun) return null; // a dry run captures nothing, so it asserts nothing (release-checks.mjs)
1246
+ if (output) process.stdout.write(output); // the captured output is still the build log
1247
+ return output;
1196
1248
  }
1197
1249
 
1198
1250
  // A hook may be one command object or an ordered array of them (e.g. create-mac-updater then lsclean).
@@ -1865,6 +1917,12 @@ async function signMacos(entries, root, phase = "signing", nestedCode = [], nest
1865
1917
  await run("node", macSignInvocation(nested, nestedReceipt), root);
1866
1918
  verifyMacosSigningSettings(nestedReceipt, nested);
1867
1919
  }
1920
+ // The re-signed nested runtime binaries changed bytes: re-describe the bundled runtime manifest(s) BEFORE the app seal (rightkit#722).
1921
+ if (runtimeManifests.length && !opts.dryRun) {
1922
+ const apps = entries.filter((entry) => /\.app\/?$/.test(entry.file));
1923
+ if (!apps.length) fail("sign.runtimeManifests needs a .app entry in sign.prePackageFiles to resolve its paths against");
1924
+ try { for (const entry of apps) refreshRuntimeManifests({ base: entry.file, manifests: runtimeManifests, log: (line) => console.log(line) }); } catch (error) { fail(error.message); }
1925
+ }
1868
1926
  const args = macSignInvocation(entries, receipt, opts.dryRun ? ["--dry-run"] : []);
1869
1927
  if (!opts.dryRun && existsSync(receipt)) unlinkSync(receipt);
1870
1928
  console.log("right-release: signing macOS Developer ID files");
@@ -1994,6 +2052,39 @@ async function verifyWindowsEmbedding({ root, target, files, markers }) {
1994
2052
  }, null, 2)}\n`);
1995
2053
  }
1996
2054
 
2055
+ /**
2056
+ * Multi-file counterpart of verifyWindowsEmbedding (payload contract): every signed payload file is still byte-identical to its signing
2057
+ * receipt row, still Authenticode-valid, and the file extracted back out of each installer matches it byte for byte.
2058
+ */
2059
+ async function verifyWindowsPayloadEmbedding({ root, target, files }) {
2060
+ if (opts.dryRun) {
2061
+ console.log("dry-run: verify the installer embeds every signed payload file");
2062
+ return;
2063
+ }
2064
+ const payloadFiles = target.sign.prePackageFiles.map((p) => resolveDeclaredPath(root, p));
2065
+ const rawReceiptPath = windowsReceiptPath(root, "raw-exe");
2066
+ let rawReceipt;
2067
+ try { rawReceipt = JSON.parse(readFileSync(rawReceiptPath, "utf8")); } catch { fail(`missing payload signing receipt: ${rawReceiptPath}`); }
2068
+ const embedded = [];
2069
+ for (const file of payloadFiles) {
2070
+ const signedSha256 = rawReceipt.files?.find((item) => path.resolve(item.file) === file)?.after?.sha256;
2071
+ if (!signedSha256) fail(`payload signing receipt does not record a signed digest for ${file}`);
2072
+ await mustExist(file, `signed payload file disappeared before packaging completed: ${file}`);
2073
+ const currentSha256 = createHash("sha256").update(readFileSync(file)).digest("hex");
2074
+ if (currentSha256 !== signedSha256) fail(`packaging rewrote the signed payload file ${file}: signed sha256 ${signedSha256}, on-disk sha256 ${currentSha256}. Its Authenticode signature is now invalid.`);
2075
+ await run("node", [SIGN_WINDOWS, "--verify-only", file], root);
2076
+ for (const installer of files) {
2077
+ let receipt;
2078
+ try { receipt = verifyNsisEmbeddedBinary({ installer, entryName: path.basename(file), expectedSha256: signedSha256 }); } catch (error) { fail(error.message); }
2079
+ console.log(`right-release: ${path.basename(installer)} embeds the signed ${receipt.entry} (sha256 ${receipt.sha256.slice(0, 16)}…)`);
2080
+ embedded.push(receipt);
2081
+ }
2082
+ }
2083
+ const receiptPath = windowsReceiptPath(root, "embedding");
2084
+ mkdirSync(path.dirname(receiptPath), { recursive: true });
2085
+ writeFileSync(receiptPath, `${JSON.stringify({ schema: 1, payload: payloadFiles, embedded, verifiedAt: new Date().toISOString() }, null, 2)}\n`);
2086
+ }
2087
+
1997
2088
  function verifyWindowsReceipt(receipt, files, phase) {
1998
2089
  if (!existsSync(receipt)) fail(`missing ${phase} Windows signing receipt: ${receipt}`);
1999
2090
  let evidence;
@@ -0,0 +1,141 @@
1
+ // `rightkit-gate --to render`: build an app's declared view-render target through the broker and run it headless, storing the images and hashes as
2
+ // evidence (rightkit#1288; Pulse's notch long-text cases, bogusyogi/pulse#558). The app declares the target in the commit's own `ci/gate.config.json`:
3
+ //
4
+ // "renderViews": {
5
+ // "<app dir relative to the repository root, \".\" for the root>": {
6
+ // "cargoDir": "src-tauri", // the Cargo workspace directory that holds the package (repository-relative; default ".")
7
+ // "package": "pulse-app", // cargo package that builds the render binary
8
+ // "bin": "pulse-app", // the binary (default: the package name)
9
+ // "features": ["render-views"], // optional: features the render target needs
10
+ // "args": ["--render-views"], // optional: fixed arguments placed before each case's
11
+ // "caseFlag": "--case", "outFlag": "--out", // optional: the flags that name one case and the output directory (these defaults)
12
+ // "cases": ["send-message-long", "tooltip-send-long-text"],
13
+ // "timeoutMs": 300000 // optional: the limit for each case (default 5 minutes)
14
+ // }
15
+ // }
16
+ //
17
+ // The binary is run once per case as `<exe> <args...> <caseFlag> <case> <outFlag> <dir>` and must write `<dir>/<case>.png`. The compile is a carried
18
+ // build (the broker on Mac and Dell, the runtime cargo wrapper direct on Linux); the executable it reports must lie inside the output directory that
19
+ // build's verified receipt names, and it runs OUTSIDE the broker, like a test executable (GATE-CONTRACT GC-A08). The receipt `render-receipt.json`
20
+ // (schema rightkit.render-views/1) lists every case's PNG with its sha256, size and dimensions, the executable's sha256, the commit and tree, and
21
+ // the host. Nothing is mocked: the target renders the app's real views.
22
+ import crypto from "node:crypto";
23
+ import fs from "node:fs";
24
+ import path from "node:path";
25
+
26
+ export const RENDER_RECEIPT_SCHEMA = "rightkit.render-views/1";
27
+ export const RENDER_RECEIPT_FILE = "render-receipt.json";
28
+ export const DEFAULT_RENDER_TIMEOUT_MS = 5 * 60 * 1000;
29
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
30
+ const FEATURE = /^[A-Za-z0-9][A-Za-z0-9_/.-]*$/;
31
+ const FLAG = /^--?[A-Za-z][A-Za-z0-9-]*$/;
32
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
33
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
34
+ const sha256 = (bytes) => crypto.createHash("sha256").update(bytes).digest("hex");
35
+
36
+ /**
37
+ * The declared render target of the app at `appDir` in a parsed `ci/gate.config.json`, normalised, or `{ none: true }` when it declares none, or
38
+ * `{ problems }` when the block is malformed (every problem at once; nothing is guessed).
39
+ */
40
+ export function renderViewsOf(gateConfig, appDir = ".") {
41
+ const block = gateConfig?.renderViews;
42
+ if (block === undefined) return { none: true };
43
+ if (!isObject(block)) return { problems: ["ci/gate.config.json renderViews must be an object keyed by app directory"] };
44
+ const spec = block[appDir];
45
+ if (spec === undefined) return { none: true };
46
+ const where = `renderViews[${JSON.stringify(appDir)}]`;
47
+ const problems = [];
48
+ if (!isObject(spec)) return { problems: [`${where} must be an object`] };
49
+ const known = ["cargoDir", "package", "bin", "features", "args", "caseFlag", "outFlag", "cases", "timeoutMs"];
50
+ for (const key of Object.keys(spec)) if (!known.includes(key)) problems.push(`${where}: unknown key ${JSON.stringify(key)} (allowed: ${known.join(", ")})`);
51
+ const cargoDir = spec.cargoDir ?? ".";
52
+ if (typeof cargoDir !== "string" || !cargoDir || cargoDir.startsWith("/") || cargoDir.includes("\\") || cargoDir.split("/").includes("..") || /^[A-Za-z]:/.test(cargoDir)) problems.push(`${where}.cargoDir must be a repository-relative directory`);
53
+ if (typeof spec.package !== "string" || !NAME.test(spec.package)) problems.push(`${where}.package must be a cargo package name`);
54
+ const bin = spec.bin ?? spec.package;
55
+ if (typeof bin !== "string" || !NAME.test(bin)) problems.push(`${where}.bin must be a binary name`);
56
+ const features = spec.features ?? [];
57
+ if (!Array.isArray(features) || !features.every((f) => typeof f === "string" && FEATURE.test(f))) problems.push(`${where}.features must be a list of feature names`);
58
+ const args = spec.args ?? [];
59
+ if (!Array.isArray(args) || !args.every((a) => typeof a === "string" && a !== "" && !/[\0\r\n]/.test(a))) problems.push(`${where}.args must be a list of non-empty strings`);
60
+ const caseFlag = spec.caseFlag ?? "--case"; const outFlag = spec.outFlag ?? "--out";
61
+ for (const [key, value] of [["caseFlag", caseFlag], ["outFlag", outFlag]]) if (typeof value !== "string" || !FLAG.test(value)) problems.push(`${where}.${key} must be a command-line flag`);
62
+ const cases = spec.cases;
63
+ if (!Array.isArray(cases) || !cases.length || !cases.every((c) => typeof c === "string" && NAME.test(c)) || new Set(cases).size !== cases.length) problems.push(`${where}.cases must be a non-empty list of distinct case names ([A-Za-z0-9._-])`);
64
+ const timeoutMs = spec.timeoutMs ?? DEFAULT_RENDER_TIMEOUT_MS;
65
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 60 * 60 * 1000) problems.push(`${where}.timeoutMs must be 1000 to 3600000`);
66
+ if (problems.length) return { problems };
67
+ return { appDir, cargoDir, package: spec.package, bin, features: [...features], args: [...args], caseFlag, outFlag, cases: [...cases], timeoutMs };
68
+ }
69
+
70
+ /** The cargo argv that builds the render binary (the carried seam adds `--locked`). */
71
+ export const renderBuildArgs = (target) => ["build", "-p", target.package, "--bin", target.bin, "--message-format=json", ...(target.features.length ? ["--features", target.features.join(",")] : [])];
72
+
73
+ /** The executable cargo's JSON build output reports for `bin` of `package`, or null. */
74
+ export function builtExecutable(stdout, { package: pkg, bin }) {
75
+ let found = null;
76
+ for (const line of String(stdout ?? "").split("\n")) {
77
+ if (!line.startsWith("{")) continue;
78
+ let rec; try { rec = JSON.parse(line); } catch { continue; }
79
+ if (rec?.reason !== "compiler-artifact" || typeof rec.executable !== "string" || !rec.executable) continue;
80
+ const kinds = Array.isArray(rec.target?.kind) ? rec.target.kind : [];
81
+ if (rec.target?.name === bin && kinds.includes("bin") && (typeof rec.package_id !== "string" || rec.package_id.includes(pkg))) found = rec.executable;
82
+ }
83
+ return found;
84
+ }
85
+
86
+ const within = (dir, file) => { const r = path.relative(dir, file); return r !== "" && !r.startsWith("..") && !path.isAbsolute(r); };
87
+
88
+ /** Width and height from a PNG's IHDR, or null when `bytes` is not a PNG. */
89
+ export function pngSize(bytes) {
90
+ if (bytes.length < 24 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE) || bytes.subarray(12, 16).toString("latin1") !== "IHDR") return null;
91
+ return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
92
+ }
93
+
94
+ /**
95
+ * Build and run the declared render target, then write the evidence. `targetDir` is the checkout's pinned target directory of the workspace on a direct host
96
+ * (a broker host's is the verified receipt's). Injected: `runCargo(args, { cwd, env })` (the carried seam: a spawnSync-shaped result
97
+ * with `outputDir` and `requestId` when the call verified), `runExecutable(exe, args, { cwd, env, timeoutMs })` (a spawnSync-shaped result, started hidden)
98
+ * and the file system. Returns `{ ok, problems, receiptFile?, receipt? }`; every failure is a problem, nothing is partial-passed.
99
+ */
100
+ export function renderViews({ target, snapshotRoot, commit, tree, outDir, env, platform, arch, targetDir = null, runCargo, runExecutable, fsOps = fs, now = () => new Date(), log = () => {} }) {
101
+ const problems = [];
102
+ const startedAt = now().toISOString();
103
+ const cwd = path.join(snapshotRoot, ...(target.cargoDir === "." ? [] : target.cargoDir.split("/")));
104
+ const built = runCargo(renderBuildArgs(target), { cwd, env });
105
+ if (built.error || built.status !== 0) return { ok: false, problems: [`the render target's build failed (${built.error?.message ?? `exit ${built.status}`}): cargo ${renderBuildArgs(target).join(" ")}\n${String(built.stderr ?? "").trim().split("\n").slice(-40).join("\n")}`] };
106
+ const exe = builtExecutable(built.stdout, target);
107
+ if (!exe) return { ok: false, problems: [`the build reported no executable for ${target.package}'s binary ${target.bin}`] };
108
+ // The binary runs outside the broker, so it must be the one the verified build wrote: inside that receipt's output directory (a direct host: the pinned target directory).
109
+ const outputDir = typeof built.outputDir === "string" ? built.outputDir : (typeof targetDir === "string" && targetDir ? targetDir : null);
110
+ if (!outputDir) return { ok: false, problems: ["the build has no verified output directory to contain its executable (no carried receipt names one and the gate pinned no target directory); nothing was run"] };
111
+ let real = exe; let realOut = outputDir;
112
+ try { real = fsOps.realpathSync(exe); realOut = fsOps.realpathSync(outputDir); } catch { /* judged as given below */ }
113
+ if (!within(realOut, real) && !within(outputDir, exe)) return { ok: false, problems: [`the executable ${exe} is outside the build's output directory ${outputDir}; nothing was run`] };
114
+ let exeBytes;
115
+ try { exeBytes = fsOps.readFileSync(real); } catch (error) { return { ok: false, problems: [`cannot read the built executable ${exe} (${error.message})`] }; }
116
+ const exeSha256 = sha256(exeBytes);
117
+ fsOps.mkdirSync(outDir, { recursive: true });
118
+ const cases = [];
119
+ for (const name of target.cases) {
120
+ const caseDir = path.join(outDir, name);
121
+ fsOps.mkdirSync(caseDir, { recursive: true });
122
+ log(`render case ${name}`);
123
+ const ran = runExecutable(real, [...target.args, target.caseFlag, name, target.outFlag, caseDir], { cwd: snapshotRoot, env, timeoutMs: target.timeoutMs });
124
+ if (ran.error || ran.status !== 0) { problems.push(`case ${name}: the render target ${ran.error ? `did not finish (${ran.error.message})` : `exited ${ran.status}`}\n${String(ran.stderr ?? "").trim().split("\n").slice(-20).join("\n")}`); continue; }
125
+ const file = path.join(caseDir, `${name}.png`);
126
+ let bytes;
127
+ try { bytes = fsOps.readFileSync(file); } catch { problems.push(`case ${name}: the target wrote no ${name}.png in ${caseDir}`); continue; }
128
+ const size = pngSize(bytes);
129
+ if (!size || size.width < 1 || size.height < 1) { problems.push(`case ${name}: ${file} is not a PNG image`); continue; }
130
+ cases.push({ name, png: path.relative(outDir, file).split(path.sep).join("/"), sha256: sha256(bytes), bytes: bytes.length, width: size.width, height: size.height });
131
+ }
132
+ if (problems.length) return { ok: false, problems };
133
+ const receipt = {
134
+ schema: RENDER_RECEIPT_SCHEMA, commit, tree, appDir: target.appDir, package: target.package, bin: target.bin, features: target.features,
135
+ executable: { path: exe, sha256: exeSha256 }, buildOutputDir: outputDir, ...(typeof built.requestId === "string" ? { buildRequestId: built.requestId } : {}),
136
+ host: { platform, arch }, startedAt, endedAt: now().toISOString(), cases,
137
+ };
138
+ const receiptFile = path.join(outDir, RENDER_RECEIPT_FILE);
139
+ fsOps.writeFileSync(receiptFile, `${JSON.stringify(receipt, null, 2)}\n`);
140
+ return { ok: true, problems: [], receiptFile, receipt };
141
+ }
@@ -49,7 +49,7 @@ const EXACT_SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
49
49
  const USER_AGENT = "right-release-resolver/1 (https://github.com/bogusyogi/rightkit)";
50
50
  // The updater is @rightkit/outdated, a dependency of this package; `right-release update` runs its bin (pnpm links only an
51
51
  // app's direct dependencies' bins, so `pnpm exec right-update` does not exist in an app that has just @rightkit/release).
52
- export const FIX = `run \`${UPDATE_COMMAND}\` (the pinned @rightkit/outdated updater; it reads .rightkit/update.json) to move the pin`;
52
+ export const FIX = `run \`${UPDATE_COMMAND}\` (the pinned @rightkit/outdated updater; it reads .rightkit/update.json, and says how to create it when the app has none) to move the pin, or set the exact version by hand and refresh the lock`;
53
53
  const DEFAULT_ATTEMPTS = 3;
54
54
  const DEFAULT_TIMEOUT_MS = 15000;
55
55
  const CONCURRENCY = 6;