@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.
- package/README.md +110 -11
- package/admission-files.mjs +40 -0
- package/admission-host.mjs +2 -1
- package/app-check.mjs +303 -16
- package/app-closure.mjs +6 -4
- package/bin/rightkit-gate.mjs +177 -32
- package/cargo-contract.mjs +17 -31
- package/cargo-license-notices.mjs +129 -19
- package/cargo-target-shim.mjs +14 -0
- package/carried-cargo.mjs +2 -4
- package/cli/right-release.mjs +24 -2
- package/cross-targets.mjs +24 -0
- package/deterministic-scans.mjs +167 -58
- package/development-signing.mjs +25 -2
- package/development.mjs +34 -1
- package/direct-release-command.mjs +154 -0
- package/disk-policy.mjs +16 -0
- package/feature-coverage.mjs +134 -0
- package/gate-coverage.mjs +38 -0
- package/gate-stages.mjs +1 -0
- package/ghsa-audit.mjs +95 -0
- package/install-app.mjs +33 -5
- package/install-channels.mjs +301 -0
- package/interactive-session-run.mjs +105 -0
- package/legal-contract.mjs +10 -1
- package/legion-freeze-consumer.mjs +241 -0
- package/linux-publish.mjs +136 -0
- package/local-publish.mjs +31 -7
- package/nsis-pack.mjs +95 -0
- package/nsis-upgrade-template.mjs +93 -0
- package/outdated-command.mjs +19 -0
- package/ownership-class-rules.mjs +32 -10
- package/ownership-mandatory-set.json +23 -0
- package/ownership-mandatory-set.mjs +66 -8
- package/package-recipe-targets.mjs +54 -19
- package/package.json +1 -1
- package/payload-root-install.mjs +123 -0
- package/plugin-delivery.mjs +141 -0
- package/prebuild-gates.mjs +8 -4
- package/preflight.mjs +6 -1
- package/provision-model-bundle.mjs +172 -0
- package/pub-upload.mjs +1 -1
- package/publish-local-npm.mjs +34 -9
- package/publish-retention.mjs +106 -0
- package/publish-update.mjs +15 -8
- package/qa-build-features.mjs +24 -15
- package/qa-contract.mjs +5 -6
- package/qa-control-scan.mjs +14 -0
- package/qa-web-pairing.mjs +76 -0
- package/r2-s3-multipart.mjs +190 -0
- package/r2-verified-upload.mjs +28 -16
- package/recipe-build.mjs +53 -3
- package/release-checks.mjs +53 -2
- package/release-config.mjs +8 -3
- package/release-invocation.mjs +12 -2
- package/release-pin-floor.mjs +44 -0
- package/release-qa-audit.mjs +18 -2
- package/release-qa-command.mjs +17 -1
- package/release-qa-policy.mjs +30 -3
- package/release-switch-cfg.mjs +271 -0
- package/release-switch-registry.json +60 -1
- package/release-switch-scan.mjs +398 -23
- package/release.mjs +97 -6
- package/render-views.mjs +141 -0
- package/rightkit-registry-resolver.mjs +1 -1
- package/rightkit-versions.json +568 -491
- package/runtime-artifact-manifest.mjs +9 -0
- package/runtime-manifest-refresh.mjs +88 -0
- package/rustright-stage.mjs +197 -0
- package/scan-digest.mjs +15 -9
- package/scan-tool-enrolment.mjs +1 -1
- package/security-policy.mjs +196 -0
- package/shell-contract.mjs +32 -0
- package/snapshot-broker.mjs +8 -1
- package/snapshot-check.mjs +58 -0
- package/snapshot-request.mjs +25 -2
- package/stage-commands.mjs +33 -4
- package/stage-ledger.mjs +6 -1
- package/stage-receipt.mjs +115 -0
- package/stage-sidecar.mjs +188 -17
- package/stage-xcframework.mjs +118 -0
- package/suite-api.generated.mjs +16 -1
- package/unit-gate.mjs +14 -2
- package/upload-large.mjs +4 -4
- package/upload-release.mjs +6 -0
- package/win-package-recipe.mjs +26 -4
|
@@ -9,7 +9,10 @@ export const RUNTIME_ARTIFACT_KINDS = Object.freeze([
|
|
|
9
9
|
"media-runtime",
|
|
10
10
|
"tokenizer",
|
|
11
11
|
"preprocessing",
|
|
12
|
+
// Ember's own trained image models (denoise, culling, auto-edit) (#1161): delivered through the same pinned-digest lane, public and free.
|
|
13
|
+
"image-model",
|
|
12
14
|
]);
|
|
15
|
+
// The apps that may promote runtime artifacts (the Right Suite apps plus Ember, a public and free app with its own models).
|
|
13
16
|
export const RIGHT_SUITE_APP_KEYS = Object.freeze([
|
|
14
17
|
"viewright",
|
|
15
18
|
"heardright",
|
|
@@ -19,6 +22,7 @@ export const RIGHT_SUITE_APP_KEYS = Object.freeze([
|
|
|
19
22
|
"screenright",
|
|
20
23
|
"genright",
|
|
21
24
|
"voiceright",
|
|
25
|
+
"ember",
|
|
22
26
|
]);
|
|
23
27
|
|
|
24
28
|
const TARGET_OSES = new Set(["windows", "darwin", "linux", "ios", "any"]);
|
|
@@ -122,6 +126,11 @@ export function validateRuntimeArtifactManifest(value) {
|
|
|
122
126
|
&& (value.distribution.delivery !== "private-r2" || value.entitlement.tier !== "pro")) {
|
|
123
127
|
fail("model artifacts must use private-r2 with Pro entitlement");
|
|
124
128
|
}
|
|
129
|
+
// An image model is the free lane's artifact: private-r2 with Pro entitlement or public-r2 with the public tier (no entitlement), never bundled
|
|
130
|
+
// here; the pinned digest and verified load apply to both lanes alike (#1161).
|
|
131
|
+
if (value.artifactKind === "image-model" && value.distribution.delivery === "bundled") {
|
|
132
|
+
fail("image-model artifacts are delivered from R2: private-r2 with Pro entitlement or public-r2 with the public tier");
|
|
133
|
+
}
|
|
125
134
|
|
|
126
135
|
assertPlainObject(value.target, "target");
|
|
127
136
|
assertExactKeys(value.target, ["os", "arch"], "target");
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Refresh a bundled runtime manifest after nested code was re-signed (rightkit#722).
|
|
2
|
+
//
|
|
3
|
+
// An app that ships native runtime libraries or models (ffmpeg, ffprobe, onnxruntime, DirectML, ONNX models) describes them in a
|
|
4
|
+
// bundled `runtime/manifest.json`: { schema, ..., files: [{ path, sha256, bytes }] } with every `path` relative to the manifest's
|
|
5
|
+
// directory. Signing rewrites a binary's bytes, so a manifest written before signing no longer matches, and the app's fail-closed
|
|
6
|
+
// runtime check rejects the shipped files. The sign step therefore calls this between "nested code signed" and "app sealed": it
|
|
7
|
+
// re-hashes every listed file in full and rewrites ONLY `sha256` and `bytes` of the rows (every other field, and the row order,
|
|
8
|
+
// stay as the app wrote them). A listed file that is missing, outside the manifest directory, a symlink or a directory refuses.
|
|
9
|
+
//
|
|
10
|
+
// Config: `sign.runtimeManifests: ["<path to manifest.json>", ...]`. On macOS each path is relative to the signed .app bundle
|
|
11
|
+
// (`Contents/Resources/runtime/manifest.json`); on Windows it is relative to the app root (the staged resource folder that the
|
|
12
|
+
// installer wraps). The check is `validateRuntimeManifestPaths`; the effect is `refreshRuntimeManifest`.
|
|
13
|
+
import { createHash } from "node:crypto";
|
|
14
|
+
import { lstatSync, readFileSync, renameSync, writeFileSync, rmSync } from "node:fs";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
|
|
17
|
+
export class RuntimeManifestError extends Error {
|
|
18
|
+
constructor(message) { super(message); this.name = "RuntimeManifestError"; this.code = "RK_RUNTIME_MANIFEST"; }
|
|
19
|
+
}
|
|
20
|
+
const fail = (message) => { throw new RuntimeManifestError(message); };
|
|
21
|
+
const SHA256 = /^[0-9a-f]{64}$/;
|
|
22
|
+
|
|
23
|
+
/** `sign.runtimeManifests`: a non-empty list of unique relative .json paths with no `..`. Returns the normalized list (empty when absent). */
|
|
24
|
+
export function validateRuntimeManifestPaths(value, label = "sign.runtimeManifests") {
|
|
25
|
+
if (value === undefined) return [];
|
|
26
|
+
if (!Array.isArray(value) || value.length === 0) fail(`${label} must be a non-empty array of relative manifest.json paths`);
|
|
27
|
+
const seen = new Set();
|
|
28
|
+
return value.map((entry, index) => {
|
|
29
|
+
if (typeof entry !== "string" || !entry.trim() || entry !== entry.trim() || entry.includes("\0")) fail(`${label}[${index}] must be a non-empty path string`);
|
|
30
|
+
const normalized = entry.replaceAll("\\", "/");
|
|
31
|
+
if (path.posix.isAbsolute(normalized) || /^[A-Za-z]:/.test(normalized) || normalized.split("/").includes("..")) fail(`${label}[${index}] must be relative and stay inside the bundle: ${entry}`);
|
|
32
|
+
if (!/\.json$/i.test(normalized)) fail(`${label}[${index}] must be a .json file: ${entry}`);
|
|
33
|
+
if (seen.has(normalized)) fail(`${label}[${index}] duplicates an earlier entry: ${entry}`);
|
|
34
|
+
seen.add(normalized);
|
|
35
|
+
return normalized;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const sha256Of = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Re-describe every file of one manifest. Returns { manifest, changed: [paths whose sha256 or bytes changed], files: n }.
|
|
43
|
+
* The file is rewritten (temp file beside it, then rename) only when a row changed.
|
|
44
|
+
*/
|
|
45
|
+
export function refreshRuntimeManifest({ manifest, fs = {} }) {
|
|
46
|
+
const lstat = fs.lstatSync ?? lstatSync;
|
|
47
|
+
const read = fs.readFileSync ?? readFileSync;
|
|
48
|
+
const write = fs.writeFileSync ?? writeFileSync;
|
|
49
|
+
const rename = fs.renameSync ?? renameSync;
|
|
50
|
+
const remove = fs.rmSync ?? rmSync;
|
|
51
|
+
let parsed;
|
|
52
|
+
try { parsed = JSON.parse(String(read(manifest))); } catch (error) { fail(`cannot read runtime manifest ${manifest}: ${error.message}`); }
|
|
53
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed) || !Array.isArray(parsed.files) || parsed.files.length === 0) fail(`${manifest} must be an object with a non-empty files array`);
|
|
54
|
+
const dir = path.dirname(manifest);
|
|
55
|
+
const changed = [];
|
|
56
|
+
const seen = new Set();
|
|
57
|
+
const files = parsed.files.map((row, index) => {
|
|
58
|
+
if (row === null || typeof row !== "object" || Array.isArray(row) || typeof row.path !== "string" || !row.path) fail(`${manifest} files[${index}] needs a path`);
|
|
59
|
+
const rel = row.path.replaceAll("\\", "/");
|
|
60
|
+
if (path.posix.isAbsolute(rel) || /^[A-Za-z]:/.test(rel) || rel.split("/").includes("..")) fail(`${manifest} files[${index}].path must stay inside the manifest directory: ${row.path}`);
|
|
61
|
+
if (seen.has(rel.toLowerCase())) fail(`${manifest} lists ${row.path} twice`);
|
|
62
|
+
seen.add(rel.toLowerCase());
|
|
63
|
+
const file = path.join(dir, ...rel.split("/"));
|
|
64
|
+
let stat;
|
|
65
|
+
try { stat = lstat(file); } catch { fail(`${manifest} lists ${row.path} but ${file} does not exist`); }
|
|
66
|
+
if (stat.isSymbolicLink() || !stat.isFile()) fail(`${manifest} lists ${row.path}, which is not a regular file`);
|
|
67
|
+
const bytes = read(file);
|
|
68
|
+
const sha256 = sha256Of(bytes);
|
|
69
|
+
if (row.sha256 !== undefined && !SHA256.test(String(row.sha256))) fail(`${manifest} files[${index}].sha256 is not a lowercase sha256`);
|
|
70
|
+
if (row.sha256 !== sha256 || row.bytes !== bytes.length) changed.push(row.path);
|
|
71
|
+
return { ...row, sha256, bytes: bytes.length };
|
|
72
|
+
});
|
|
73
|
+
if (changed.length) {
|
|
74
|
+
const next = `${JSON.stringify({ ...parsed, files }, null, 2)}\n`;
|
|
75
|
+
const temp = path.join(dir, `.${path.basename(manifest)}.refresh-${process.pid}.tmp`);
|
|
76
|
+
try { write(temp, next); rename(temp, manifest); } finally { remove(temp, { force: true }); }
|
|
77
|
+
}
|
|
78
|
+
return { manifest, changed, files: files.length };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Refresh every declared manifest under `base` (the signed .app on macOS, the app root on Windows). */
|
|
82
|
+
export function refreshRuntimeManifests({ base, manifests, fs = {}, log = () => {} }) {
|
|
83
|
+
return manifests.map((relative) => {
|
|
84
|
+
const result = refreshRuntimeManifest({ manifest: path.join(base, ...relative.split("/")), fs });
|
|
85
|
+
log(`right-release: runtime manifest ${relative}: ${result.files} file(s), ${result.changed.length} re-described${result.changed.length ? ` (${result.changed.join(", ")})` : ""}`);
|
|
86
|
+
return result;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `right-release rustright-stage [--repo <rustright checkout>] [--scratch <dir>] [--cutover] [--apply]` (rightkit#1465, rustright#125).
|
|
3
|
+
//
|
|
4
|
+
// RustRight's two stage scripts (tools/install/mac-local-stage.sh, tools/install/xps-stage.ps1) folded into right-release: one tool takes the broker, client and
|
|
5
|
+
// installer binaries from the gate's compile output for HEAD, signs them with RightKit's own signing, stages and approves them, writes the cutover script, and
|
|
6
|
+
// calls `rustright-install cutover` ONLY for the swap. It never runs Cargo and never compiles: the bytes it signs are the bytes `rightkit-gate --to compile`
|
|
7
|
+
// built for the commit at HEAD, proved by RustRight's own `tools/install/gate-output.mjs` (read here, never edited) against the gate's receipt.
|
|
8
|
+
//
|
|
9
|
+
// Order (both hosts): HEAD commit (the checkout must be clean on macOS) -> gate-output proves and copies the three binaries -> their digests are compared with the
|
|
10
|
+
// gate's -> macOS: `rustright-install expected-identity`, `rustright-install bundle`, helpers copied in, digests compared again, Developer ID codesign through
|
|
11
|
+
// RightKit's signing session, designated-requirement and identifier/team checks; Windows: Authenticode through sign-windows.mjs and a Valid / Damned Ventures
|
|
12
|
+
// LLC check -> `rustright-install stage` -> `rustright-install approve` -> the cutover script is written -> with `--cutover`, `rustright-install cutover` runs
|
|
13
|
+
// (a dry run that prints the `drain:` line unless `--apply`).
|
|
14
|
+
//
|
|
15
|
+
// Not done here, and why: the root-owned adapter install and Legion enrollment on the Mac need elevation, which is Adrian's host step (rustright#119); this tool
|
|
16
|
+
// runs unelevated. Typed PIPELINE admission stays under rightkit#824.
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, copyFileSync, writeFileSync } from "node:fs";
|
|
19
|
+
import os from "node:os";
|
|
20
|
+
import path from "node:path";
|
|
21
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
22
|
+
import { spawnSync } from "./background-process.mjs";
|
|
23
|
+
import { resolveMacosDeveloperIdIdentity } from "./macos-signing-identity.mjs";
|
|
24
|
+
import { runMacCodesignCommands } from "./macos-signing-session.mjs";
|
|
25
|
+
|
|
26
|
+
export class RustrightStageError extends Error {
|
|
27
|
+
constructor(message) { super(message); this.name = "RustrightStageError"; this.code = "RK_RUSTRIGHT_STAGE"; }
|
|
28
|
+
}
|
|
29
|
+
const fail = (message) => { throw new RustrightStageError(message); };
|
|
30
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
31
|
+
const NAMES = ["rustright-broker", "rustright", "rustright-install"];
|
|
32
|
+
const sha256File = (file) => createHash("sha256").update(readFileSync(file)).digest("hex");
|
|
33
|
+
const text = (result) => String(result?.stdout ?? "");
|
|
34
|
+
|
|
35
|
+
/** `key=value` lines (gate-output, expected-identity) as a Map. */
|
|
36
|
+
export function parseKeyValueLines(output) {
|
|
37
|
+
const map = new Map();
|
|
38
|
+
for (const line of String(output).split(/\r?\n/)) { const at = line.indexOf("="); if (at > 0) map.set(line.slice(0, at), line.slice(at + 1)); }
|
|
39
|
+
return map;
|
|
40
|
+
}
|
|
41
|
+
const need = (map, key, what) => { const value = map.get(key); if (value === undefined || value === "") fail(`${what} reported no ${key}`); return value; };
|
|
42
|
+
|
|
43
|
+
export function parseRustrightStageArgs(argv, { platform = process.platform } = {}) {
|
|
44
|
+
const opts = { repo: process.cwd(), scratch: platform === "win32" ? "D:\\scratch\\rustright-install" : "/Volumes/D/scratch/rustright-install", cutover: false, apply: false, configNext: null, splitControlRoot: false };
|
|
45
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
46
|
+
const flag = argv[i];
|
|
47
|
+
if (flag === "--cutover") opts.cutover = true;
|
|
48
|
+
else if (flag === "--apply") opts.apply = true;
|
|
49
|
+
else if (flag === "--split-control-root") opts.splitControlRoot = true;
|
|
50
|
+
else if (["--repo", "--scratch", "--config-next"].includes(flag)) {
|
|
51
|
+
if (argv[i + 1] === undefined || argv[i + 1].startsWith("--")) fail(`${flag} needs a value`);
|
|
52
|
+
opts[flag === "--config-next" ? "configNext" : flag.slice(2)] = argv[i + 1]; i += 1;
|
|
53
|
+
} else fail(`unknown argument: ${flag}`);
|
|
54
|
+
}
|
|
55
|
+
if (opts.apply && !opts.cutover) fail("--apply belongs to --cutover");
|
|
56
|
+
if (opts.configNext && !path.isAbsolute(opts.configNext)) fail("--config-next must be an absolute candidate config file");
|
|
57
|
+
return opts;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Stage HEAD of `repo`. `deps` injects: run (spawnSync-shaped), platform, env, sign (macOS: (bundle, identity) => void; Windows: (files) => void), fs pieces, log.
|
|
62
|
+
* Returns { commit, version, staged, cutoverScript, cutoverStatus }.
|
|
63
|
+
*/
|
|
64
|
+
export function stageRustright(opts, deps = {}) {
|
|
65
|
+
const { run = spawnSync, platform = process.platform, env = process.env, log = (line) => console.log(line), home = os.userInfo().homedir, now = () => new Date() } = deps;
|
|
66
|
+
const checked = (command, args, what, options = {}) => {
|
|
67
|
+
const result = run(command, args, { encoding: "utf8", windowsHide: true, shell: false, ...options });
|
|
68
|
+
if (result?.error || result?.status !== 0) fail(`${what} failed (${result?.error?.message ?? `exit ${result?.status}`})${result?.stderr ? `: ${String(result.stderr).trim().slice(0, 400)}` : ""}`);
|
|
69
|
+
return result;
|
|
70
|
+
};
|
|
71
|
+
const repo = path.resolve(opts.repo);
|
|
72
|
+
const commit = text(checked("git", ["-C", repo, "rev-parse", "HEAD"], "git rev-parse HEAD")).trim();
|
|
73
|
+
if (!/^[0-9a-f]{40}$/.test(commit)) fail(`HEAD of ${repo} is not a commit id: ${commit}`);
|
|
74
|
+
if (platform === "darwin" && text(checked("git", ["-C", repo, "status", "--porcelain"], "git status")).trim()) fail("the primary checkout is not clean");
|
|
75
|
+
const short = commit.slice(0, 7);
|
|
76
|
+
const version = `rustright-${short}`;
|
|
77
|
+
const gateOutput = path.join(repo, "tools", "install", "gate-output.mjs");
|
|
78
|
+
if (!existsSync(gateOutput)) fail(`${gateOutput} is missing: this is not a RustRight checkout`);
|
|
79
|
+
const scratch = path.resolve(opts.scratch);
|
|
80
|
+
mkdirSync(scratch, { recursive: true });
|
|
81
|
+
const exe = (name) => (platform === "win32" ? `${name}.exe` : name);
|
|
82
|
+
|
|
83
|
+
// 1. The gate's compile output for HEAD, proved against the gate's receipt and copied out so later writes to the output cannot change what is staged.
|
|
84
|
+
const bins = path.join(scratch, `gate-bin-${short}`);
|
|
85
|
+
rmSync(bins, { recursive: true, force: true });
|
|
86
|
+
let gate;
|
|
87
|
+
try { gate = parseKeyValueLines(text(checked(process.execPath, [gateOutput, "--repo", repo, "--bins", NAMES.join(","), "--copy-to", bins], "gate-output"))); }
|
|
88
|
+
catch (error) { fail(`no gate compile output vouched for HEAD ${short}: run rightkit-gate --to compile in ${repo}, then rerun this (${error.message})`); }
|
|
89
|
+
if (need(gate, "commit", "gate-output") !== commit) fail(`gate-output vouched for ${gate.get("commit")}, HEAD is ${commit}`);
|
|
90
|
+
const gateSha = Object.fromEntries(NAMES.map((name) => [name, need(gate, `sha256.${name}`, "gate-output")]));
|
|
91
|
+
log(`gate compile: receipt=${gate.get("receipt")} executor=${gate.get("executor")} exception=${gate.get("exception")} outputs=${gate.get("outputs.digest")}`);
|
|
92
|
+
const sameAsGate = (file, name) => { const got = sha256File(file); if (got !== gateSha[name]) fail(`${file} is not the gate's compiled bytes (sha256 ${got}, gate ${gateSha[name]}); nothing was signed`); };
|
|
93
|
+
for (const name of NAMES) sameAsGate(path.join(bins, exe(name)), name);
|
|
94
|
+
|
|
95
|
+
let brokerBinary; let clientBinary; let installer; let staged; let cutoverArgs; let cutoverScript; let bundle = null;
|
|
96
|
+
const control = deps.controlRoot ?? opts.controlRoot ?? (platform === "win32" ? "D:\\.rightkit-managed" : path.join(home, "Library", "Application Support", "RightKit", "build-control"));
|
|
97
|
+
if (platform === "darwin") {
|
|
98
|
+
// 2. Bundle, helpers, digest re-check, Developer ID signature.
|
|
99
|
+
const dir = path.join(scratch, `local-${short}`);
|
|
100
|
+
bundle = path.join(dir, "RustRight Broker.app");
|
|
101
|
+
const riBin = path.join(bins, "rustright-install");
|
|
102
|
+
const expected = parseKeyValueLines(text(checked(riBin, ["expected-identity"], "rustright-install expected-identity")));
|
|
103
|
+
const team = need(expected, "team", "the installer's expected identity");
|
|
104
|
+
const bundleId = need(expected, "bundle.identifier", "the installer's expected identity");
|
|
105
|
+
const requirement = need(expected, "bundle.requirement", "the installer's expected identity");
|
|
106
|
+
let identity;
|
|
107
|
+
try { identity = (deps.identity ?? (() => resolveMacosDeveloperIdIdentity({ env, run })))(); } catch (error) { fail(error.message); }
|
|
108
|
+
if (!identity.endsWith(`(${team})`)) fail(`signing identity: its team is not the canonical team ${team}`);
|
|
109
|
+
rmSync(dir, { recursive: true, force: true });
|
|
110
|
+
mkdirSync(dir, { recursive: true });
|
|
111
|
+
checked(riBin, ["bundle", "--broker-binary", path.join(bins, "rustright-broker"), "--version", version, "--out", bundle, "--apply"], "rustright-install bundle");
|
|
112
|
+
mkdirSync(path.join(bundle, "Contents", "Helpers"), { recursive: true });
|
|
113
|
+
for (const name of ["rustright", "rustright-install"]) { copyFileSync(path.join(bins, name), path.join(bundle, "Contents", "Helpers", name)); chmodSync(path.join(bundle, "Contents", "Helpers", name), 0o755); }
|
|
114
|
+
sameAsGate(path.join(bundle, "Contents", "MacOS", "rustright-broker"), "rustright-broker");
|
|
115
|
+
sameAsGate(path.join(bundle, "Contents", "Helpers", "rustright"), "rustright");
|
|
116
|
+
sameAsGate(path.join(bundle, "Contents", "Helpers", "rustright-install"), "rustright-install");
|
|
117
|
+
(deps.sign ?? ((app, who) => {
|
|
118
|
+
const results = runMacCodesignCommands([["--force", "--deep", "--options", "runtime", "--timestamp", "--sign", who, app]], { env, run });
|
|
119
|
+
if (!results.length || results.some((r) => r?.error || r?.status !== 0)) fail(`codesign failed: ${String(results.at(-1)?.stderr ?? results.at(-1)?.error?.message ?? "").trim().slice(0, 300)}`);
|
|
120
|
+
}))(bundle, identity);
|
|
121
|
+
checked("codesign", ["--verify", "--deep", "--strict", `-R=${requirement}`, bundle], "codesign --verify against the canonical designated requirement");
|
|
122
|
+
const signature = `\n${String(checked("codesign", ["-dv", "--verbose=2", bundle], "codesign -dv").stderr ?? "")}\n`;
|
|
123
|
+
if (!signature.includes(`\nIdentifier=${bundleId}\n`)) fail(`bundle identifier is not ${bundleId}`);
|
|
124
|
+
if (!signature.includes(`\nTeamIdentifier=${team}\n`)) fail(`team identifier is not ${team}`);
|
|
125
|
+
brokerBinary = path.join(bundle, "Contents", "MacOS", "rustright-broker");
|
|
126
|
+
clientBinary = path.join(bundle, "Contents", "Helpers", "rustright");
|
|
127
|
+
installer = path.join(bundle, "Contents", "Helpers", "rustright-install");
|
|
128
|
+
const bs = sha256File(brokerBinary);
|
|
129
|
+
const cs = sha256File(clientBinary);
|
|
130
|
+
// 3. Stage and approve.
|
|
131
|
+
const out = text(checked(installer, ["stage", "--control-root", control, "--source-checkout", repo, "--commit", commit, "--version", version, "--broker-bundle", bundle, "--broker-sha256", bs, "--client-binary", clientBinary, "--client-sha256", cs, "--apply"], "rustright-install stage"));
|
|
132
|
+
staged = out.split(/\r?\n/).map((line) => /^staged (.*) \((?:reused|version) .*/.exec(line)?.[1]).find(Boolean);
|
|
133
|
+
if (!staged) fail("rustright-install stage printed no staged path");
|
|
134
|
+
checked(installer, ["approve", "--control-root", control, "--staged", staged, "--commit", commit, "--approved-by", `${os.userInfo().username} ran right-release rustright-stage for ${version}`, "--approved-at", now().toISOString().replace(/\.\d+Z$/, ".000Z"), "--apply"], "rustright-install approve");
|
|
135
|
+
const external = deps.externalRoot ?? "/Volumes/D/.rightkit-managed";
|
|
136
|
+
cutoverArgs = ["cutover", "--platform", "darwin", "--control-root", control, "--config", path.join(control, "config.json"), "--external-root", external, "--source-revision", commit, "--source-checkout", repo, "--version", version, "--label", "dev.rustright.broker", "--uid", String(process.getuid?.() ?? 501), "--endpoint", path.join(control, "broker.sock"), "--plist", path.join(home, "Library", "LaunchAgents", "dev.rustright.broker.plist"), "--health-workspace", deps.healthWorkspace ?? "/Volumes/D/claude/cutright", "--broker-bundle", bundle, "--client-binary", clientBinary, "--broker-sha256", bs, "--client-sha256", cs, "--drain-timeout-ms", "1800000", "--timeout-ms", "600000", "--preflight-timeout-ms", "240000", "--agent-bin", path.join(control, "agent-bin")];
|
|
137
|
+
cutoverScript = path.join(scratch, `mac-cutover-${short}.sh`);
|
|
138
|
+
const quote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
139
|
+
writeFileSync(cutoverScript, `#!/bin/bash\n# Written by right-release rustright-stage for ${version} (commit ${commit}). Extra arguments pass through: --apply, and --config-next <absolute candidate config file>.\n${quote(installer)} ${cutoverArgs.map(quote).join(" ")} "$@"\n`);
|
|
140
|
+
chmodSync(cutoverScript, 0o755);
|
|
141
|
+
} else if (platform === "win32") {
|
|
142
|
+
// 2. Authenticode through RightKit's own signer, then require Valid and the product signer on each.
|
|
143
|
+
const dir = path.join(scratch, `activate-${short}`);
|
|
144
|
+
rmSync(dir, { recursive: true, force: true });
|
|
145
|
+
mkdirSync(dir, { recursive: true });
|
|
146
|
+
for (const name of NAMES) copyFileSync(path.join(bins, exe(name)), path.join(dir, exe(name)));
|
|
147
|
+
brokerBinary = path.join(dir, exe("rustright-broker"));
|
|
148
|
+
clientBinary = path.join(dir, exe("rustright"));
|
|
149
|
+
installer = path.join(dir, exe("rustright-install"));
|
|
150
|
+
const files = [brokerBinary, clientBinary, installer];
|
|
151
|
+
(deps.sign ?? ((list) => { checked(process.execPath, [path.join(HERE, "sign-windows.mjs"), ...list], "sign-windows"); }))(files);
|
|
152
|
+
for (const file of files) {
|
|
153
|
+
const probe = checked("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", `$s = Get-AuthenticodeSignature -LiteralPath '${file.replaceAll("'", "''")}'; "$($s.Status)|$($s.SignerCertificate.Subject)"`], `Authenticode check of ${file}`);
|
|
154
|
+
const [status, subject = ""] = text(probe).trim().split("|");
|
|
155
|
+
if (status !== "Valid" || !subject.startsWith("CN=Damned Ventures LLC,")) fail(`${file} is not validly signed by Damned Ventures LLC (status ${status}, signer ${subject})`);
|
|
156
|
+
}
|
|
157
|
+
const bs = sha256File(brokerBinary);
|
|
158
|
+
const cs = sha256File(clientBinary);
|
|
159
|
+
// The cutover's source checkout is a clone of exactly HEAD, so the primary checkout moving on does not move what the cutover reads.
|
|
160
|
+
const src = path.join(scratch, `src-${short}`);
|
|
161
|
+
rmSync(src, { recursive: true, force: true });
|
|
162
|
+
checked("git", ["clone", "-q", "--no-checkout", "-c", "core.autocrlf=false", repo, src], "git clone of HEAD");
|
|
163
|
+
checked("git", ["-C", src, "fetch", "-q", repo, "+refs/remotes/origin/main:refs/remotes/origin/main"], "git fetch origin/main");
|
|
164
|
+
checked("git", ["-C", src, "-c", "advice.detachedHead=false", "checkout", "-q", commit], "git checkout of HEAD");
|
|
165
|
+
if (text(checked("git", ["-C", src, "rev-parse", "HEAD"], "git rev-parse")).trim() !== commit) fail(`the source clone is not at ${commit}`);
|
|
166
|
+
const runtimeRoot = deps.runtimeRoot ?? "D:\\.rustright";
|
|
167
|
+
checked(installer, ["stage", "--platform", "windows", "--control-root", control, "--broker-binary", brokerBinary, "--client-binary", clientBinary, "--broker-sha256", bs, "--client-sha256", cs, "--commit", commit, "--source-checkout", src, "--version", version, "--apply"], "rustright-install stage");
|
|
168
|
+
staged = path.join(runtimeRoot, "runtime.next");
|
|
169
|
+
checked(installer, ["approve", "--platform", "windows", "--control-root", control, "--staged", staged, "--commit", commit, "--approved-by", `${os.userInfo().username} ran right-release rustright-stage for ${version}`, "--approved-at", now().toISOString().replace(/\.\d+Z$/, ".000Z"), "--apply"], "rustright-install approve");
|
|
170
|
+
cutoverArgs = ["cutover", "--platform", "win32", "--control-root", control, "--config", path.join(control, "config.json"), "--external-root", control, "--source-revision", commit, "--source-checkout", src, "--version", version, "--task-name", "RustRightBroker", "--endpoint", "\\\\.\\pipe\\rustright-broker", "--health-workspace", deps.healthWorkspace ?? "D:\\Claude\\cutright", "--broker-binary", brokerBinary, "--client-binary", clientBinary, "--broker-sha256", bs, "--client-sha256", cs, "--drain-timeout-ms", "600000", "--agent-bin", path.join(control, "agent-bin")];
|
|
171
|
+
if (opts.splitControlRoot) fail("--split-control-root is not folded in yet: run the split migration with xps-stage.ps1 -SplitControlRoot (rustright#54)");
|
|
172
|
+
cutoverScript = path.join(scratch, `xps-cutover-${short}.ps1`);
|
|
173
|
+
const literal = (value) => `'${String(value).replaceAll("'", "''")}'`;
|
|
174
|
+
writeFileSync(cutoverScript, `# Written by right-release rustright-stage for ${version} (commit ${commit}). Without -Apply it is a dry run that prints the drain: line.\nparam([switch]$Apply, [string]$ConfigNext = '')\nSet-StrictMode -Version Latest\n$ErrorActionPreference = 'Stop'\n$cutover = @(${cutoverArgs.map(literal).join(", ")})\nif ($ConfigNext) { $cutover += @('--config-next', $ConfigNext) }\nif ($Apply) { $cutover += '--apply' }\n& ${literal(installer)} @$cutover\nexit $LASTEXITCODE\n`);
|
|
175
|
+
} else fail(`rustright-stage runs on macOS or Windows, not ${platform}`);
|
|
176
|
+
|
|
177
|
+
log(`staged=${staged}`);
|
|
178
|
+
log(`cutover=${cutoverScript}`);
|
|
179
|
+
// 4. The swap is rustright-install's: this tool calls it only when asked, a dry run unless --apply.
|
|
180
|
+
let cutoverStatus = null;
|
|
181
|
+
if (opts.cutover) {
|
|
182
|
+
const args = [...cutoverArgs, ...(opts.configNext ? ["--config-next", opts.configNext] : []), ...(opts.apply ? ["--apply"] : [])];
|
|
183
|
+
const result = run(installer, args, { stdio: "inherit", windowsHide: true, shell: false });
|
|
184
|
+
cutoverStatus = result?.status ?? 1;
|
|
185
|
+
if (cutoverStatus !== 0) fail(`rustright-install cutover exited ${cutoverStatus}`);
|
|
186
|
+
}
|
|
187
|
+
return { commit, version, staged, cutoverScript, cutoverStatus };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export function main(argv = process.argv.slice(2)) {
|
|
191
|
+
try { stageRustright(parseRustrightStageArgs(argv)); return 0; } catch (error) {
|
|
192
|
+
console.error(`right-release rustright-stage: ${error.message}`);
|
|
193
|
+
return error instanceof RustrightStageError ? 1 : 2;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) process.exitCode = main();
|
package/scan-digest.mjs
CHANGED
|
@@ -43,15 +43,21 @@ export const rustScanId = Object.freeze({
|
|
|
43
43
|
});
|
|
44
44
|
|
|
45
45
|
/**
|
|
46
|
-
* A crate's compile feature plan
|
|
47
|
-
*
|
|
48
|
-
*
|
|
46
|
+
* A crate's compile feature plan (ci/gate.config.json rust.<crate>): `lintSets` (clippy; the declared sets, default features when none,
|
|
47
|
+
* and default plus --all-features for a crate that declares none but has Cargo features, `autoAllFeatures`), `baseSets` (the declared sets
|
|
48
|
+
* alone: tests, rustdoc and the other-OS-target lints), whether a default `check` is needed (no lint set covers default features), and the
|
|
49
|
+
* `checkSets` that remain (none when a lint set already uses --all-features).
|
|
49
50
|
*/
|
|
50
51
|
export function rustCratePlan(own = {}) {
|
|
51
|
-
const
|
|
52
|
+
const declaredSets = Array.isArray(own?.featureSets) && own.featureSets.length ? own.featureSets : [[]];
|
|
53
|
+
// rightkit#1231 (feature-coverage.mjs effectiveCrateFeatures): a crate with no declared `featureSets` whose Cargo.toml declares features is linted with its default
|
|
54
|
+
// features and with --all-features, so feature-gated code is never left unlinted. Its tests, the rustdoc check and the other-OS-target lints keep the declared
|
|
55
|
+
// (here: default) sets, `baseSets`: more configurations than the declared ones would double every test run and cross-compile features nobody declared.
|
|
56
|
+
const auto = own?.autoAllFeatures === true && !(Array.isArray(own?.featureSets) && own.featureSets.length);
|
|
57
|
+
const lintSets = auto ? [[], ["--all-features"]] : declaredSets;
|
|
52
58
|
const defaultCheck = !lintSets.some((set) => set.length === 0);
|
|
53
59
|
const checkSets = (lintSets.some((set) => set.includes("--all-features")) ? [] : (Array.isArray(own?.checkFeatureSets) ? own.checkFeatureSets : [["--all-features"]])).filter((set) => set.length);
|
|
54
|
-
return { lintSets, defaultCheck, checkSets };
|
|
60
|
+
return { lintSets, baseSets: declaredSets, defaultCheck, checkSets };
|
|
55
61
|
}
|
|
56
62
|
|
|
57
63
|
// ---- Clippy batching (GATE-CONTRACT §1 "Clippy route & batching"; item 8 rows 8.6, 8.8, 8.15) -----------------------------------------
|
|
@@ -134,7 +140,7 @@ export function requiredScanIds({ units, crateFeatures = {}, exists, includeTest
|
|
|
134
140
|
const clippyEntries = [];
|
|
135
141
|
for (const name of units) {
|
|
136
142
|
const own = crateFeatures?.[name] ?? {};
|
|
137
|
-
const { lintSets, defaultCheck, checkSets } = rustCratePlan(own);
|
|
143
|
+
const { lintSets, baseSets, defaultCheck, checkSets } = rustCratePlan(own);
|
|
138
144
|
if (perCrate) {
|
|
139
145
|
for (const id of ["cargo-metadata", "cargo-deny", "cargo-audit"]) ids.add(`${id}:${name}`);
|
|
140
146
|
if (exists(`crates/${name}/.rightkit/advisory-exceptions.json`)) ids.add(`advisory-exceptions:${name}`);
|
|
@@ -147,9 +153,9 @@ export function requiredScanIds({ units, crateFeatures = {}, exists, includeTest
|
|
|
147
153
|
else lintSets.forEach((_set, i) => ids.add(rustScanId.clippy(name, lintSets.length, i)));
|
|
148
154
|
if (exists(`crates/${name}/src/lib.rs`)) ids.add(rustScanId.doc(name));
|
|
149
155
|
if (includeTests) {
|
|
150
|
-
|
|
151
|
-
ids.add(rustScanId.testRust(name,
|
|
152
|
-
if (own.alsoSerial) ids.add(rustScanId.testRustSerial(name,
|
|
156
|
+
baseSets.forEach((_set, i) => {
|
|
157
|
+
ids.add(rustScanId.testRust(name, baseSets.length, i));
|
|
158
|
+
if (own.alsoSerial) ids.add(rustScanId.testRustSerial(name, baseSets.length, i));
|
|
153
159
|
});
|
|
154
160
|
}
|
|
155
161
|
}
|
package/scan-tool-enrolment.mjs
CHANGED
|
@@ -25,7 +25,7 @@ import { spawnSync } from "./background-process.mjs";
|
|
|
25
25
|
export const SCAN_TOOLS_SCHEMA = "rightkit.scan-tools/1";
|
|
26
26
|
export const SCAN_TOOLS_DIR = "scan-tools";
|
|
27
27
|
/** The analyzers class A accepts only from an enrolment (deterministic-scans.mjs TRUSTED_SCAN_TOOLS; kept in step by the tests). */
|
|
28
|
-
export const SCAN_TOOL_NAMES = Object.freeze(["actionlint", "shellcheck", "cargo-deny", "cargo-audit"]);
|
|
28
|
+
export const SCAN_TOOL_NAMES = Object.freeze(["actionlint", "shellcheck", "oxlint", "cargo-deny", "cargo-audit"]);
|
|
29
29
|
export const SCAN_TOOL_PLATFORMS = Object.freeze(["darwin", "win32", "linux"]);
|
|
30
30
|
|
|
31
31
|
export class ScanToolEnrolmentError extends Error {
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// `security` in the release config: the Content Security Policy and the Tauri capability set the app ships must not drift from the approved
|
|
2
|
+
// values (#1136). Read-only: it reads `tauri.conf.json` and the capability files and writes nothing, so the doctor and the build report the
|
|
3
|
+
// same rows (`security-policy` in release.mjs).
|
|
4
|
+
//
|
|
5
|
+
// security: {
|
|
6
|
+
// tauriConfig: "src-tauri/tauri.conf.json", // optional (this is the default)
|
|
7
|
+
// csp: { exact: "default-src 'self'; connect-src 'self' https://api.example.com" } // the policy equals this, directive by directive
|
|
8
|
+
// | { allow: { "connect-src": ["'self'", "https://api.example.com"], "default-src": ["'self'"] }, // an allow-list: every directive and source
|
|
9
|
+
// require?: { "connect-src": ["https://api.example.com"] } }, // the app's policy uses must be listed; `require` must be present
|
|
10
|
+
// capabilities: {
|
|
11
|
+
// dir: "src-tauri/capabilities", // optional (this is the default)
|
|
12
|
+
// expected: { main: { exact?: ["core:default", "process:allow-restart"], require?: ["process:allow-restart"], forbid?: ["updater:"] } }
|
|
13
|
+
// } // `forbid` entries are permission identifier prefixes
|
|
14
|
+
// }
|
|
15
|
+
//
|
|
16
|
+
// Every capability file in `dir` must be named in `expected` (a new, unreviewed capability is drift), and every `expected` capability must exist.
|
|
17
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
18
|
+
import { createRequire } from "node:module";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
|
|
21
|
+
const KEYS = ["tauriConfig", "csp", "capabilities"];
|
|
22
|
+
const CSP_KEYS = ["exact", "allow", "require"];
|
|
23
|
+
const CAPABILITY_RULE_KEYS = ["exact", "require", "forbid"];
|
|
24
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
25
|
+
const stringList = (value) => Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim() !== "");
|
|
26
|
+
|
|
27
|
+
let smolTomlParse;
|
|
28
|
+
const parseToml = (text) => (smolTomlParse ??= createRequire(import.meta.url)("smol-toml").parse)(text);
|
|
29
|
+
|
|
30
|
+
function insideApp(root, relative, label) {
|
|
31
|
+
if (typeof relative !== "string" || !relative.trim() || path.isAbsolute(relative) || /^[A-Za-z]:/.test(relative) || relative.replaceAll("\\", "/").split("/").includes("..")) {
|
|
32
|
+
throw new Error(`${label} must be a relative path inside the app: ${relative}`);
|
|
33
|
+
}
|
|
34
|
+
return path.join(root, relative);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** { directive: [sources] } of a CSP given as a string, or as the object/array form Tauri accepts. */
|
|
38
|
+
export function parseCsp(value) {
|
|
39
|
+
const directives = {};
|
|
40
|
+
const add = (name, sources) => {
|
|
41
|
+
const key = String(name).trim().toLowerCase();
|
|
42
|
+
if (!key) return;
|
|
43
|
+
// The first occurrence of a directive wins in a browser; a repeat is ignored, so it is ignored here too.
|
|
44
|
+
if (!(key in directives)) directives[key] = [...new Set(sources)].sort();
|
|
45
|
+
};
|
|
46
|
+
if (typeof value === "string") {
|
|
47
|
+
for (const part of value.split(";")) {
|
|
48
|
+
const [name, ...sources] = part.trim().split(/\s+/).filter(Boolean);
|
|
49
|
+
if (name) add(name, sources);
|
|
50
|
+
}
|
|
51
|
+
} else if (isObject(value)) {
|
|
52
|
+
for (const [name, sources] of Object.entries(value)) add(name, Array.isArray(sources) ? sources.map(String) : String(sources).split(/\s+/).filter(Boolean));
|
|
53
|
+
} else throw new Error("the Content Security Policy must be a string or a directive map");
|
|
54
|
+
return directives;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const describe = (directives) => Object.entries(directives).map(([name, sources]) => `${name} ${sources.join(" ")}`.trim()).join("; ");
|
|
58
|
+
|
|
59
|
+
/** Problems (empty when the policy is as approved) of one app CSP against `security.csp`. */
|
|
60
|
+
export function cspProblems(actual, rule) {
|
|
61
|
+
const problems = [];
|
|
62
|
+
if (rule.exact !== undefined) {
|
|
63
|
+
const expected = parseCsp(rule.exact);
|
|
64
|
+
for (const name of new Set([...Object.keys(expected), ...Object.keys(actual)])) {
|
|
65
|
+
const want = expected[name], have = actual[name];
|
|
66
|
+
if (!have) problems.push(`CSP directive ${name} is approved (${want.join(" ")}) but the app's policy has none`);
|
|
67
|
+
else if (!want) problems.push(`CSP directive ${name} (${have.join(" ")}) is not in the approved policy`);
|
|
68
|
+
else if (want.join(" ") !== have.join(" ")) problems.push(`CSP ${name} is ${have.join(" ")}, the approved policy has ${want.join(" ")}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (rule.allow !== undefined) {
|
|
72
|
+
const allowed = Object.fromEntries(Object.entries(rule.allow).map(([name, sources]) => [name.toLowerCase(), new Set(sources)]));
|
|
73
|
+
for (const [name, sources] of Object.entries(actual)) {
|
|
74
|
+
if (!allowed[name]) { problems.push(`CSP directive ${name} (${sources.join(" ")}) is not on the approved allow-list`); continue; }
|
|
75
|
+
const extra = sources.filter((source) => !allowed[name].has(source));
|
|
76
|
+
if (extra.length) problems.push(`CSP ${name} allows ${extra.join(" ")}, which the approved allow-list does not`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
for (const [name, sources] of Object.entries(rule.require ?? {})) {
|
|
80
|
+
const have = new Set(actual[name.toLowerCase()] ?? []);
|
|
81
|
+
const missing = sources.filter((source) => !have.has(source));
|
|
82
|
+
if (missing.length) problems.push(`CSP ${name} must allow ${missing.join(" ")} (the app's API hosts)`);
|
|
83
|
+
}
|
|
84
|
+
return problems;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Permission identifiers of a capability document ("core:default" or { identifier, allow, deny }). */
|
|
88
|
+
export function capabilityPermissions(capability) {
|
|
89
|
+
return [...new Set((capability.permissions ?? []).map((entry) => (typeof entry === "string" ? entry : entry?.identifier)).filter((id) => typeof id === "string"))].sort();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Validate the `security` block's shape. Throws on the first malformed value. */
|
|
93
|
+
export function validateSecurityConfig(security) {
|
|
94
|
+
if (!isObject(security)) throw new Error("security must be an object");
|
|
95
|
+
const unknown = Object.keys(security).filter((key) => !KEYS.includes(key));
|
|
96
|
+
if (unknown.length) throw new Error(`security has unknown key(s): ${unknown.join(", ")} (allowed: ${KEYS.join(", ")})`);
|
|
97
|
+
if (security.csp !== undefined) {
|
|
98
|
+
const csp = security.csp;
|
|
99
|
+
if (!isObject(csp)) throw new Error("security.csp must be an object with exact, allow and/or require");
|
|
100
|
+
const bad = Object.keys(csp).filter((key) => !CSP_KEYS.includes(key));
|
|
101
|
+
if (bad.length) throw new Error(`security.csp has unknown key(s): ${bad.join(", ")} (allowed: ${CSP_KEYS.join(", ")})`);
|
|
102
|
+
if (csp.exact === undefined && csp.allow === undefined && csp.require === undefined) throw new Error("security.csp needs exact, allow or require");
|
|
103
|
+
if (csp.exact !== undefined && csp.allow !== undefined) throw new Error("security.csp: give exact or allow, not both");
|
|
104
|
+
if (csp.exact !== undefined) parseCsp(csp.exact);
|
|
105
|
+
for (const key of ["allow", "require"]) {
|
|
106
|
+
if (csp[key] === undefined) continue;
|
|
107
|
+
if (!isObject(csp[key]) || Object.values(csp[key]).some((sources) => !stringList(sources))) throw new Error(`security.csp.${key} must map directive names to lists of sources`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (security.capabilities !== undefined) {
|
|
111
|
+
const capabilities = security.capabilities;
|
|
112
|
+
if (!isObject(capabilities)) throw new Error("security.capabilities must be an object");
|
|
113
|
+
const bad = Object.keys(capabilities).filter((key) => !["dir", "expected"].includes(key));
|
|
114
|
+
if (bad.length) throw new Error(`security.capabilities has unknown key(s): ${bad.join(", ")} (allowed: dir, expected)`);
|
|
115
|
+
if (!isObject(capabilities.expected) || Object.keys(capabilities.expected).length === 0) throw new Error("security.capabilities.expected must name at least one capability");
|
|
116
|
+
for (const [id, rule] of Object.entries(capabilities.expected)) {
|
|
117
|
+
if (!isObject(rule)) throw new Error(`security.capabilities.expected.${id} must be an object`);
|
|
118
|
+
const badRule = Object.keys(rule).filter((key) => !CAPABILITY_RULE_KEYS.includes(key));
|
|
119
|
+
if (badRule.length) throw new Error(`security.capabilities.expected.${id} has unknown key(s): ${badRule.join(", ")} (allowed: ${CAPABILITY_RULE_KEYS.join(", ")})`);
|
|
120
|
+
if (CAPABILITY_RULE_KEYS.every((key) => rule[key] === undefined)) throw new Error(`security.capabilities.expected.${id} needs exact, require or forbid`);
|
|
121
|
+
for (const key of CAPABILITY_RULE_KEYS) if (rule[key] !== undefined && !stringList(rule[key])) throw new Error(`security.capabilities.expected.${id}.${key} must be a list of permission identifiers`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (security.csp === undefined && security.capabilities === undefined) throw new Error("security needs csp and/or capabilities");
|
|
125
|
+
return security;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function readCapabilityFiles(dir) {
|
|
129
|
+
const found = new Map();
|
|
130
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
131
|
+
if (!entry.isFile() || !/\.(json|toml)$/i.test(entry.name)) continue;
|
|
132
|
+
const file = path.join(dir, entry.name);
|
|
133
|
+
let document;
|
|
134
|
+
try {
|
|
135
|
+
const text = readFileSync(file, "utf8");
|
|
136
|
+
document = /\.toml$/i.test(entry.name) ? parseToml(text) : JSON.parse(text);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
throw new Error(`capability file ${entry.name} is not valid ${/\.toml$/i.test(entry.name) ? "TOML" : "JSON"}: ${error.message}`);
|
|
139
|
+
}
|
|
140
|
+
// Tauri names a capability by its `identifier`; a file without one is named by its file stem.
|
|
141
|
+
const id = typeof document.identifier === "string" && document.identifier ? document.identifier : path.basename(entry.name, path.extname(entry.name));
|
|
142
|
+
if (found.has(id)) throw new Error(`capability ${id} is defined twice (${found.get(id).file} and ${entry.name})`);
|
|
143
|
+
found.set(id, { file: entry.name, permissions: capabilityPermissions(document) });
|
|
144
|
+
}
|
|
145
|
+
return found;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Every drift of the app's CSP and capability set from `security`; throws a single Error naming them all, returns the checked summary otherwise. */
|
|
149
|
+
export function assertSecurityPolicy(root, security, label = path.basename(root)) {
|
|
150
|
+
validateSecurityConfig(security);
|
|
151
|
+
const problems = [];
|
|
152
|
+
const checked = [];
|
|
153
|
+
const tauriConfigPath = insideApp(root, security.tauriConfig ?? "src-tauri/tauri.conf.json", "security.tauriConfig");
|
|
154
|
+
if (security.csp !== undefined) {
|
|
155
|
+
if (!existsSync(tauriConfigPath)) throw new Error(`${label} security.csp: ${path.relative(root, tauriConfigPath)} does not exist`);
|
|
156
|
+
let tauriConfig;
|
|
157
|
+
try { tauriConfig = JSON.parse(readFileSync(tauriConfigPath, "utf8")); } catch (error) { throw new Error(`${label} ${path.relative(root, tauriConfigPath)} is not valid JSON: ${error.message}`); }
|
|
158
|
+
// Tauri 2 keeps the policy at app.security.csp, Tauri 1 at tauri.security.csp.
|
|
159
|
+
const raw = tauriConfig?.app?.security?.csp ?? tauriConfig?.tauri?.security?.csp;
|
|
160
|
+
if (raw === undefined || raw === null || raw === "") problems.push(`the app has no Content Security Policy in ${path.relative(root, tauriConfigPath)} (app.security.csp); security.csp requires one`);
|
|
161
|
+
else {
|
|
162
|
+
let actual;
|
|
163
|
+
try { actual = parseCsp(raw); } catch (error) { throw new Error(`${label} ${path.relative(root, tauriConfigPath)}: ${error.message}`); }
|
|
164
|
+
problems.push(...cspProblems(actual, security.csp).map((problem) => `${problem} (policy: ${describe(actual)})`));
|
|
165
|
+
checked.push("csp");
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (security.capabilities !== undefined) {
|
|
169
|
+
const dir = insideApp(root, security.capabilities.dir ?? "src-tauri/capabilities", "security.capabilities.dir");
|
|
170
|
+
if (!existsSync(dir)) throw new Error(`${label} security.capabilities: ${path.relative(root, dir)} does not exist`);
|
|
171
|
+
const present = readCapabilityFiles(dir);
|
|
172
|
+
const expected = security.capabilities.expected;
|
|
173
|
+
for (const id of present.keys()) if (!(id in expected)) problems.push(`capability ${id} (${present.get(id).file}) is not in security.capabilities.expected: a new capability needs review`);
|
|
174
|
+
for (const [id, rule] of Object.entries(expected)) {
|
|
175
|
+
const entry = present.get(id);
|
|
176
|
+
if (!entry) { problems.push(`capability ${id} is expected but ${path.relative(root, dir)} has no such capability`); continue; }
|
|
177
|
+
const have = new Set(entry.permissions);
|
|
178
|
+
if (rule.exact !== undefined) {
|
|
179
|
+
const want = new Set(rule.exact);
|
|
180
|
+
const extra = [...have].filter((permission) => !want.has(permission));
|
|
181
|
+
const missing = [...want].filter((permission) => !have.has(permission));
|
|
182
|
+
if (extra.length) problems.push(`capability ${id} (${entry.file}) grants ${extra.join(", ")}, which is not in the approved set`);
|
|
183
|
+
if (missing.length) problems.push(`capability ${id} (${entry.file}) lacks ${missing.join(", ")} from the approved set`);
|
|
184
|
+
}
|
|
185
|
+
const missingRequired = (rule.require ?? []).filter((permission) => !have.has(permission));
|
|
186
|
+
if (missingRequired.length) problems.push(`capability ${id} (${entry.file}) must grant ${missingRequired.join(", ")}`);
|
|
187
|
+
for (const prefix of rule.forbid ?? []) {
|
|
188
|
+
const hit = [...have].filter((permission) => permission.startsWith(prefix));
|
|
189
|
+
if (hit.length) problems.push(`capability ${id} (${entry.file}) grants ${hit.join(", ")}, forbidden by ${prefix}`);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
checked.push("capabilities");
|
|
193
|
+
}
|
|
194
|
+
if (problems.length) throw new Error(`${label} security policy drifted from the approved values:\n - ${problems.join("\n - ")}`);
|
|
195
|
+
return { checked };
|
|
196
|
+
}
|