toolcrib 0.11.1 → 0.12.0

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.
@@ -0,0 +1,232 @@
1
+ import path from 'node:path';
2
+ import { readTextIfExists, fileExists } from './project.js';
3
+ import { resolveDependencyDecisions, buildProposedPackageJson } from './deps.js';
4
+
5
+ // Must match init.js's TOOLKIT_DIR ('./toolcrib'). The CLI can't import from
6
+ // eslint-rules/ (a separate package that ships in the release zip), so the
7
+ // rule names are mirrored here; cli/test/lintConfig.test.js checks the list
8
+ // against the real files in the repo's eslint-rules/ directory.
9
+ export const PLUGIN_SPECIFIER = './toolcrib/eslint-rules/index.js';
10
+ export const PLUGIN_MARKER = 'toolcrib/eslint-rules';
11
+ export const OXLINT_FILE = '.oxlintrc.json';
12
+ export const OXLINT_RANGE = '^1.95.0';
13
+ export const RULE_NAMES = [
14
+ 'no-unexplained-zindex',
15
+ 'no-computed-prop-before-spread',
16
+ 'no-missing-use-client',
17
+ 'no-frozen-controlled-prop',
18
+ 'prefer-toolcrib-component',
19
+ 'no-literal-style-values',
20
+ ];
21
+ const OVERRIDE_GLOB = 'toolcrib/**';
22
+ const OXLINT_SCHEMA = './node_modules/oxlint/configuration_schema.json';
23
+ const ESLINT_FLAT_FILES = ['js', 'mjs', 'cjs', 'ts', 'mts', 'cts'].map((ext) => `eslint.config.${ext}`);
24
+ const ESLINT_LEGACY_FILES = ['.eslintrc', '.eslintrc.js', '.eslintrc.cjs', '.eslintrc.json', '.eslintrc.yaml', '.eslintrc.yml'];
25
+
26
+ /**
27
+ * Which lint setup the project already has. `.oxlintrc.json` wins over an
28
+ * ESLint config when both exist (oxlint is what Vite's template ships).
29
+ */
30
+ export function detectLintSetup(projectRoot, userPkg) {
31
+ if (fileExists(path.join(projectRoot, OXLINT_FILE))) return { kind: 'oxlint', file: OXLINT_FILE };
32
+ for (const file of ESLINT_FLAT_FILES) {
33
+ if (fileExists(path.join(projectRoot, file))) return { kind: 'eslint', file };
34
+ }
35
+ for (const file of ESLINT_LEGACY_FILES) {
36
+ if (fileExists(path.join(projectRoot, file))) return { kind: 'eslint-legacy', file };
37
+ }
38
+ if (userPkg && userPkg.eslintConfig) return { kind: 'eslint-legacy', file: 'package.json' };
39
+ return { kind: 'none' };
40
+ }
41
+
42
+ function pluginEntrySpecifier(entry) {
43
+ if (typeof entry === 'string') return entry;
44
+ if (entry && typeof entry === 'object') return entry.specifier;
45
+ return undefined;
46
+ }
47
+
48
+ function isPlainObject(value) {
49
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
50
+ }
51
+
52
+ function ruleKey(name) {
53
+ return `toolcrib/${name}`;
54
+ }
55
+
56
+ /**
57
+ * Add toolcrib's plugin, rules and the `toolcrib/**` override to an existing
58
+ * .oxlintrc.json's text. Never overwrites something the consumer set: an
59
+ * existing severity (including "off", the documented opt-out) is kept.
60
+ * Returns `{ unparseable: true }` for text JSON.parse rejects (JSONC
61
+ * comments, say), otherwise `{ changed, proposed }`.
62
+ */
63
+ export function proposeOxlintConfig(currentText) {
64
+ let obj;
65
+ try {
66
+ const text = currentText.charCodeAt(0) === 0xfeff ? currentText.slice(1) : currentText;
67
+ obj = JSON.parse(text);
68
+ } catch {
69
+ return { unparseable: true };
70
+ }
71
+ if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) return { unparseable: true };
72
+
73
+ let changed = false;
74
+
75
+ if (obj.jsPlugins !== undefined && !Array.isArray(obj.jsPlugins)) return { unparseable: true };
76
+ const jsPlugins = obj.jsPlugins ?? [];
77
+ const hasPlugin = jsPlugins.some((entry) => (pluginEntrySpecifier(entry) ?? '').includes(PLUGIN_MARKER));
78
+ if (!hasPlugin) {
79
+ jsPlugins.push(PLUGIN_SPECIFIER);
80
+ changed = true;
81
+ }
82
+ obj.jsPlugins = jsPlugins;
83
+
84
+ // Any shape we can't safely edit goes back to the caller as a hand-edit note.
85
+ if (obj.rules !== undefined && !isPlainObject(obj.rules)) return { unparseable: true };
86
+ if (obj.overrides !== undefined && !Array.isArray(obj.overrides)) return { unparseable: true };
87
+ const match = (o) => Array.isArray(o?.files) && o.files.includes(OVERRIDE_GLOB);
88
+ const matching = obj.overrides?.find(match);
89
+ if (matching && matching.rules !== undefined && !isPlainObject(matching.rules)) return { unparseable: true };
90
+
91
+ obj.rules ??= {};
92
+ for (const name of RULE_NAMES) {
93
+ if (!(ruleKey(name) in obj.rules)) {
94
+ obj.rules[ruleKey(name)] = 'error';
95
+ changed = true;
96
+ }
97
+ }
98
+
99
+ obj.overrides ??= [];
100
+ const existing = obj.overrides.find(match);
101
+ if (existing) {
102
+ existing.rules ??= {};
103
+ for (const name of RULE_NAMES) {
104
+ if (!(ruleKey(name) in existing.rules)) {
105
+ existing.rules[ruleKey(name)] = 'off';
106
+ changed = true;
107
+ }
108
+ }
109
+ } else {
110
+ obj.overrides.push({ files: [OVERRIDE_GLOB], rules: offRules() });
111
+ changed = true;
112
+ }
113
+
114
+ return { changed, proposed: changed ? JSON.stringify(obj, null, 2) + '\n' : currentText };
115
+ }
116
+
117
+ function offRules() {
118
+ return Object.fromEntries(RULE_NAMES.map((name) => [ruleKey(name), 'off']));
119
+ }
120
+
121
+ /** Full .oxlintrc.json text for a project with no lint config. */
122
+ export function newOxlintConfig() {
123
+ const config = {
124
+ $schema: OXLINT_SCHEMA,
125
+ jsPlugins: [PLUGIN_SPECIFIER],
126
+ rules: Object.fromEntries(RULE_NAMES.map((name) => [ruleKey(name), 'error'])),
127
+ overrides: [{ files: [OVERRIDE_GLOB], rules: offRules() }],
128
+ };
129
+ return JSON.stringify(config, null, 2) + '\n';
130
+ }
131
+
132
+ /**
133
+ * For a project with no lint setup: add the oxlint devDependency and a
134
+ * `lint` script (only when absent). An existing incompatible oxlint is
135
+ * reported as a conflict, never overwritten. Returns
136
+ * `{ pkg, changed, conflicts }`.
137
+ */
138
+ export function proposePackageJsonLint(pkg) {
139
+ const decisions = resolveDependencyDecisions(pkg, { oxlint: OXLINT_RANGE });
140
+ let proposed = decisions.toAdd.length > 0 ? buildProposedPackageJson(pkg, decisions.toAdd, 'devDependencies') : pkg;
141
+ let changed = decisions.toAdd.length > 0;
142
+ if (!proposed.scripts?.lint) {
143
+ proposed = structuredClone(proposed);
144
+ proposed.scripts = { ...(proposed.scripts || {}), lint: 'oxlint' };
145
+ changed = true;
146
+ }
147
+ return { pkg: proposed, changed, conflicts: decisions.conflicts };
148
+ }
149
+
150
+ /** For kind `oxlint`: only reports an oxlint version the rules can't run on. */
151
+ export function checkOxlintDependency(pkg) {
152
+ const userRange = pkg.dependencies?.oxlint ?? pkg.devDependencies?.oxlint;
153
+ if (!userRange) return [];
154
+ return resolveDependencyDecisions(pkg, { oxlint: OXLINT_RANGE }).conflicts;
155
+ }
156
+
157
+ /** Text printed for an ESLint flat-config project (nothing is changed). */
158
+ export function eslintSnippet() {
159
+ return (
160
+ `Add toolcrib's lint rules to your ESLint flat config:\n` +
161
+ ` import toolcrib from './toolcrib/eslint-rules/index.js';\n` +
162
+ ` ...toolcrib.configs.recommended // append to the exported array\n` +
163
+ `The rules need a parser for TS/TSX, which your config already supplies. typescript-eslint currently ` +
164
+ `requires TypeScript below 6.1, so on TypeScript 7 use oxlint instead (see toolcrib/eslint-rules/README.md).`
165
+ );
166
+ }
167
+
168
+ /** Text printed for a legacy .eslintrc project (nothing is changed). */
169
+ export function eslintLegacyNote() {
170
+ return (
171
+ `Your ESLint config is the legacy .eslintrc format, which can't load local rule files. Migrate to flat ` +
172
+ `config (then add toolcrib.configs.recommended) or use oxlint; see toolcrib/eslint-rules/README.md.`
173
+ );
174
+ }
175
+
176
+ /** Text printed when an existing .oxlintrc.json can't be edited automatically. */
177
+ export function oxlintManualSnippet() {
178
+ return (
179
+ `Couldn't edit ${OXLINT_FILE} automatically (it isn't plain JSON, e.g. it has comments). Add this by hand:\n` +
180
+ ` "jsPlugins": ["${PLUGIN_SPECIFIER}"],\n` +
181
+ ` "rules": { ${RULE_NAMES.map((n) => `"${ruleKey(n)}": "error"`).join(', ')} },\n` +
182
+ ` "overrides": [{ "files": ["${OVERRIDE_GLOB}"], "rules": { ${RULE_NAMES.map((n) => `"${ruleKey(n)}": "off"`).join(', ')} } }]`
183
+ );
184
+ }
185
+
186
+ /**
187
+ * Everything init/merge need to wire the lint rules, in one place so the two
188
+ * commands behave identically. `pkg` is the package.json object so far (deps
189
+ * already merged); the returned `pkg` builds on it, so the caller folds it
190
+ * into its single package.json patch.
191
+ *
192
+ * Returns `{ setup, pkg, pkgChanged, configChange, conflicts, notes }`:
193
+ * `configChange` is `{ relPath, current, proposed }` or null; `notes` are
194
+ * messages to print (hand-edit instructions) when nothing can be staged.
195
+ */
196
+ export function planLintWiring(projectRoot, pkg) {
197
+ const setup = detectLintSetup(projectRoot, pkg);
198
+ const plan = { setup, pkg, pkgChanged: false, configChange: null, conflicts: [], notes: [] };
199
+
200
+ if (setup.kind === 'none') {
201
+ const lint = proposePackageJsonLint(pkg);
202
+ plan.pkg = lint.pkg;
203
+ plan.pkgChanged = lint.changed;
204
+ plan.conflicts = lint.conflicts;
205
+ plan.configChange = { relPath: OXLINT_FILE, current: '', proposed: newOxlintConfig() };
206
+ } else if (setup.kind === 'oxlint') {
207
+ plan.conflicts = checkOxlintDependency(pkg);
208
+ const current = readTextIfExists(path.join(projectRoot, OXLINT_FILE));
209
+ const result = proposeOxlintConfig(current);
210
+ if (result.unparseable) plan.notes.push(oxlintManualSnippet());
211
+ else if (result.changed) plan.configChange = { relPath: OXLINT_FILE, current, proposed: result.proposed };
212
+ } else if (!readTextIfExists(path.join(projectRoot, setup.file)).includes(PLUGIN_MARKER)) {
213
+ // An ESLint project that already references the plugin needs no hint.
214
+ plan.notes.push(setup.kind === 'eslint' ? eslintSnippet() : eslintLegacyNote());
215
+ }
216
+ return plan;
217
+ }
218
+
219
+ /** For doctor: is toolcrib's plugin referenced from the detected config? */
220
+ export function isLintWired(projectRoot) {
221
+ const pkgText = readTextIfExists(path.join(projectRoot, 'package.json'));
222
+ let pkg = null;
223
+ try {
224
+ pkg = pkgText ? JSON.parse(pkgText.charCodeAt(0) === 0xfeff ? pkgText.slice(1) : pkgText) : null;
225
+ } catch {
226
+ pkg = null;
227
+ }
228
+ const setup = detectLintSetup(projectRoot, pkg);
229
+ if (setup.kind === 'none') return { ...setup, wired: false };
230
+ const text = readTextIfExists(path.join(projectRoot, setup.file)) ?? '';
231
+ return { ...setup, wired: text.includes(PLUGIN_MARKER) };
232
+ }
@@ -48,6 +48,9 @@ export function applyPatchFallback(patchPath, projectRoot) {
48
48
  }
49
49
 
50
50
  const isNewFile = parsed.oldFileName === '/dev/null';
51
+ if (!isNewFile && !fs.existsSync(targetPath)) {
52
+ return { success: false, error: `Target file "${targetRelPath}" does not exist.` };
53
+ }
51
54
  const currentContent = isNewFile ? '' : fs.readFileSync(targetPath, 'utf-8');
52
55
 
53
56
  const result = applyPatch(currentContent, parsed);
@@ -26,6 +26,56 @@ export function readJsonIfExists(filePath) {
26
26
  return JSON.parse(stripBOM(fs.readFileSync(filePath, 'utf-8')));
27
27
  }
28
28
 
29
+ /**
30
+ * Remove // and /* *\/ comments and trailing commas from JSONC text (e.g.
31
+ * tsconfig.json). String-aware: comment markers inside string literals are
32
+ * left alone.
33
+ */
34
+ export function stripJsonComments(text) {
35
+ let out = '';
36
+ let i = 0;
37
+ while (i < text.length) {
38
+ const ch = text[i];
39
+ if (ch === '"') {
40
+ let j = i + 1;
41
+ while (j < text.length && text[j] !== '"') j += text[j] === '\\' ? 2 : 1;
42
+ out += text.slice(i, j + 1);
43
+ i = j + 1;
44
+ } else if (ch === '/' && text[i + 1] === '/') {
45
+ while (i < text.length && text[i] !== '\n') i++;
46
+ } else if (ch === '/' && text[i + 1] === '*') {
47
+ const end = text.indexOf('*/', i + 2);
48
+ i = end === -1 ? text.length : end + 2;
49
+ } else {
50
+ out += ch;
51
+ i++;
52
+ }
53
+ }
54
+ // Trailing commas: a comma followed only by whitespace then } or ].
55
+ // Strings were already passed through above, but re-scan string-aware.
56
+ let result = '';
57
+ for (let k = 0; k < out.length; k++) {
58
+ const c = out[k];
59
+ if (c === '"') {
60
+ let j = k + 1;
61
+ while (j < out.length && out[j] !== '"') j += out[j] === '\\' ? 2 : 1;
62
+ result += out.slice(k, j + 1);
63
+ k = j;
64
+ } else if (c === ',' && /^\s*[}\]]/.test(out.slice(k + 1))) {
65
+ // drop it
66
+ } else {
67
+ result += c;
68
+ }
69
+ }
70
+ return result;
71
+ }
72
+
73
+ /** Like readJsonIfExists, but tolerates JSONC comments and trailing commas. */
74
+ export function readJsoncIfExists(filePath) {
75
+ if (!fs.existsSync(filePath)) return null;
76
+ return JSON.parse(stripJsonComments(stripBOM(fs.readFileSync(filePath, 'utf-8'))));
77
+ }
78
+
29
79
  // Deliberately does NOT strip a BOM, unlike readJsonIfExists above --
30
80
  // confirmed as a real, previously-shipped bug (found via
31
81
  // cli/integration-test/run-windows-integration.mjs, not assumed): every
@@ -75,10 +125,11 @@ export function readLock(projectRoot) {
75
125
 
76
126
  /**
77
127
  * `extra` is merged into the written lock JSON alongside `version` —
78
- * today, used only for `testsVersion` (recorded when `toolcrib init
79
- * --with-tests` vendors the optional test-suite artifact, see
80
- * lib/release.js's fetchTestsRelease). Omitted (the default), the output
81
- * is exactly `{ version }`, unchanged from before this existed.
128
+ * used for `testsVersion` (recorded when `toolcrib init --with-tests`
129
+ * vendors the optional test-suite artifact, see lib/release.js's
130
+ * fetchTestsRelease) and `provenance` ('sigstore' | 'sha256', how the core
131
+ * zip was verified, see lib/github.js's downloadReleaseZip). Omitted (the
132
+ * default), the output is exactly `{ version }`.
82
133
  *
83
134
  * Deliberately no implicit "preserve testsVersion unless told otherwise"
84
135
  * behavior in here — a caller that wants to carry an existing testsVersion
@@ -0,0 +1,161 @@
1
+ import fs from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import semver from 'semver';
4
+ import * as p from '@clack/prompts';
5
+ import { bundleFromJSON } from '@sigstore/bundle';
6
+ import { Verifier, toSignedEntity, toTrustMaterial } from '@sigstore/verify';
7
+ import { getTrustedRoot } from '@sigstore/tuf';
8
+ import { TrustedRoot } from '@sigstore/protobuf-specs';
9
+
10
+ // Sigstore provenance verification for release downloads (#961).
11
+ //
12
+ // A release's `.sha256` sibling lives in the same GitHub release as the zip,
13
+ // so anyone able to replace release assets can replace both. The Sigstore
14
+ // bundle is different: it carries a signature from a short-lived certificate
15
+ // that Fulcio issued to release.yml's own GitHub Actions identity, plus a
16
+ // Rekor transparency-log entry, so replacing the zip means forging a
17
+ // signature, not just uploading a file. See cli/README.md.
18
+
19
+ export const PROVENANCE_ASSET_NAME = 'toolcrib-release.sigstore.json';
20
+
21
+ // First toolkit release whose release.yml published PROVENANCE_ASSET_NAME.
22
+ // Anything older has no bundle to fetch and is verified by SHA-256 only.
23
+ export const SIGNED_SINCE = '0.17.0';
24
+
25
+ const REPO = 'escape-llc/toolcrib';
26
+ const OIDC_ISSUER = 'https://token.actions.githubusercontent.com';
27
+ const PAYLOAD_TYPE = 'application/vnd.in-toto+json';
28
+ const PREDICATE_TYPE = 'https://slsa.dev/provenance/v1';
29
+
30
+ // Bounded so a blocked network fails over to the bundled root quickly
31
+ // instead of hanging `init`/`merge`/`doctor` on a TUF fetch.
32
+ const TUF_TIMEOUT_MS = 10_000;
33
+ const TUF_RETRIES = 1;
34
+
35
+ const BUNDLED_ROOT_PATH = fileURLToPath(new URL('./sigstore-trusted-root.json', import.meta.url));
36
+
37
+ /**
38
+ * Whether `version`'s release is expected to carry a Sigstore bundle. Pure
39
+ * semver comparison, so a prerelease of SIGNED_SINCE itself
40
+ * (`0.17.0-beta.1`) sorts below it and counts as unsigned.
41
+ */
42
+ export function isSignedRelease(version) {
43
+ return semver.gte(version, SIGNED_SINCE);
44
+ }
45
+
46
+ /** The Sigstore public-good trusted root snapshot that ships inside this CLI. */
47
+ export function loadBundledTrustMaterial() {
48
+ const root = TrustedRoot.fromJSON(JSON.parse(fs.readFileSync(BUNDLED_ROOT_PATH, 'utf8')));
49
+ return toTrustMaterial(root);
50
+ }
51
+
52
+ // One trust-material load per process: `merge` verifies up to four assets
53
+ // (two versions, core + tests), and each shouldn't repeat a TUF round trip.
54
+ let trustMaterialPromise = null;
55
+
56
+ /** Test seam: forget the cached trust material. */
57
+ export function resetTrustMaterialCache() {
58
+ trustMaterialPromise = null;
59
+ }
60
+
61
+ /**
62
+ * Load the trust material verification needs: Sigstore's trusted root,
63
+ * fetched over TUF (https://tuf-repo-cdn.sigstore.dev) so key rotations
64
+ * reach this CLI without a release of it. If that fetch fails (offline, a
65
+ * firewall blocking the host), fall back to the snapshot bundled with this
66
+ * CLI and say so, rather than failing every install on a network the
67
+ * release download itself got through.
68
+ *
69
+ * `fetchTrustedRoot` is a test seam so tests never touch the network.
70
+ * Resolves to `{ trustMaterial, source }` where source is 'tuf' or 'bundled'.
71
+ */
72
+ export function loadTrustMaterial({ fetchTrustedRoot = getTrustedRoot } = {}) {
73
+ if (!trustMaterialPromise) {
74
+ trustMaterialPromise = (async () => {
75
+ try {
76
+ const root = await fetchTrustedRoot({ timeout: TUF_TIMEOUT_MS, retry: TUF_RETRIES });
77
+ return { trustMaterial: toTrustMaterial(root), source: 'tuf' };
78
+ } catch (err) {
79
+ p.log.warn(
80
+ `Couldn't reach Sigstore's TUF repository (${err.message}); ` +
81
+ `verifying against the trust root bundled with this CLI instead.`
82
+ );
83
+ return { trustMaterial: loadBundledTrustMaterial(), source: 'bundled' };
84
+ }
85
+ })();
86
+ }
87
+ return trustMaterialPromise;
88
+ }
89
+
90
+ function decodeStatement(bundleJson) {
91
+ const envelope = bundleJson?.dsseEnvelope;
92
+ if (!envelope) {
93
+ throw new Error('the bundle has no DSSE envelope');
94
+ }
95
+ return { envelope, statement: JSON.parse(Buffer.from(envelope.payload, 'base64').toString('utf8')) };
96
+ }
97
+
98
+ /**
99
+ * Verify that `bundleJson` (a Sigstore bundle) proves `assetName`, whose
100
+ * SHA-256 is `digestHex`, was built by this repo's release.yml for tag
101
+ * `v${version}`. Throws a specific Error on the first check that fails.
102
+ *
103
+ * `trustMaterial` comes from loadTrustMaterial(); `trustSource` ('tuf' or
104
+ * 'bundled') only shapes the error message.
105
+ */
106
+ export function verifyProvenance({ bundleJson, assetName, digestHex, version, trustMaterial, trustSource }) {
107
+ const refuse = (reason) =>
108
+ new Error(`Provenance check failed for ${assetName} v${version}: ${reason}. Refusing to install an unverified download.`);
109
+
110
+ // (a) Cryptographic: the DSSE signature, the certificate chain to Fulcio,
111
+ // the Rekor inclusion proof, and that the certificate was issued to a
112
+ // GitHub Actions OIDC identity. Throws if the payload was altered.
113
+ let signer;
114
+ try {
115
+ signer = new Verifier(trustMaterial).verify(toSignedEntity(bundleFromJSON(bundleJson)), {
116
+ extensions: { issuer: OIDC_ISSUER },
117
+ });
118
+ } catch (err) {
119
+ const stale =
120
+ trustSource === 'bundled'
121
+ ? '; the trust root bundled with this CLI may be out of date, so update the toolcrib CLI'
122
+ : '';
123
+ throw refuse(`the Sigstore signature did not verify (${err.message})${stale}`);
124
+ }
125
+
126
+ // (b) The signer must be release.yml running for THIS version's own tag,
127
+ // not any `refs/tags/v*`. A looser match would allow a downgrade: an
128
+ // attacker who can replace release assets could serve an older release's
129
+ // zip together with that older release's (validly signed) bundle in place
130
+ // of the requested version's, and every signature check would still pass.
131
+ const expectedSan = `https://github.com/${REPO}/.github/workflows/release.yml@refs/tags/v${version}`;
132
+ const actualSan = signer.identity?.subjectAlternativeName;
133
+ if (actualSan !== expectedSan) {
134
+ throw refuse(`the bundle was signed by ${actualSan ?? 'an unknown identity'}, expected ${expectedSan}`);
135
+ }
136
+
137
+ // (c) Shape of what was signed.
138
+ let envelope, statement;
139
+ try {
140
+ ({ envelope, statement } = decodeStatement(bundleJson));
141
+ } catch (err) {
142
+ throw refuse(`couldn't read the signed statement (${err.message})`);
143
+ }
144
+ if (envelope.payloadType !== PAYLOAD_TYPE) {
145
+ throw refuse(`payload type is ${envelope.payloadType}, expected ${PAYLOAD_TYPE}`);
146
+ }
147
+ if (statement.predicateType !== PREDICATE_TYPE) {
148
+ throw refuse(`predicate type is ${statement.predicateType}, expected ${PREDICATE_TYPE}`);
149
+ }
150
+
151
+ // (d) The signed statement must name exactly this asset, with exactly the
152
+ // bytes we downloaded.
153
+ const subject = (statement.subject ?? []).find((s) => s.name === assetName);
154
+ if (!subject) {
155
+ throw refuse(`the signed statement has no subject named ${assetName}`);
156
+ }
157
+ const signedDigest = subject.digest?.sha256;
158
+ if (signedDigest?.toLowerCase() !== digestHex.toLowerCase()) {
159
+ throw refuse(`the signed SHA-256 for ${assetName} is ${signedDigest}, but the download hashes to ${digestHex}`);
160
+ }
161
+ }
@@ -23,7 +23,7 @@ function stripBOM(text) {
23
23
  */
24
24
  export async function fetchRelease(version) {
25
25
  const resolvedVersion = await resolveVersion(version);
26
- const zipBuffer = await downloadReleaseZip(resolvedVersion);
26
+ const { zipBuffer, provenance } = await downloadReleaseZip(resolvedVersion);
27
27
 
28
28
  const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'toolcrib-release-'));
29
29
 
@@ -43,6 +43,8 @@ export async function fetchRelease(version) {
43
43
 
44
44
  return {
45
45
  version: resolvedVersion,
46
+ // 'sigstore' or 'sha256': how downloadReleaseZip verified this download.
47
+ provenance,
46
48
  config,
47
49
  tempDir,
48
50
  readFile: (relPath) => stripBOM(fs.readFileSync(path.join(tempDir, relPath), 'utf-8')),
@@ -75,7 +77,7 @@ export async function fetchRelease(version) {
75
77
  * tests zip from another.
76
78
  */
77
79
  export async function fetchTestsRelease(version) {
78
- const zipBuffer = await downloadReleaseZip(version, TESTS_ASSET_NAME);
80
+ const { zipBuffer, provenance } = await downloadReleaseZip(version, TESTS_ASSET_NAME);
79
81
 
80
82
  const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'toolcrib-tests-release-'));
81
83
 
@@ -98,6 +100,7 @@ export async function fetchTestsRelease(version) {
98
100
 
99
101
  return {
100
102
  version,
103
+ provenance,
101
104
  config,
102
105
  tempDir,
103
106
  readFile: (relPath) => stripBOM(fs.readFileSync(path.join(tempDir, relPath), 'utf-8')),
@@ -0,0 +1,126 @@
1
+ {
2
+ "mediaType": "application/vnd.dev.sigstore.trustedroot+json;version=0.1",
3
+ "tlogs": [
4
+ {
5
+ "baseUrl": "https://rekor.sigstore.dev",
6
+ "hashAlgorithm": "SHA2_256",
7
+ "publicKey": {
8
+ "rawBytes": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2G2Y+2tabdTV5BcGiBIx0a9fAFwrkBbmLSGtks4L3qX6yYY0zufBnhC8Ur/iy55GhWP/9A/bY2LhC30M9+RYtw==",
9
+ "keyDetails": "PKIX_ECDSA_P256_SHA_256",
10
+ "validFor": {
11
+ "start": "2021-01-12T11:53:27.000Z"
12
+ }
13
+ },
14
+ "logId": {
15
+ "keyId": "wNI9atQGlz+VWfO6LRygH4QUfY/8W4RFwiT5i5WRgB0="
16
+ }
17
+ },
18
+ {
19
+ "baseUrl": "https://log2025-1.rekor.sigstore.dev",
20
+ "hashAlgorithm": "SHA2_256",
21
+ "publicKey": {
22
+ "rawBytes": "MCowBQYDK2VwAyEAt8rlp1knGwjfbcXAYPYAkn0XiLz1x8O4t0YkEhie244=",
23
+ "keyDetails": "PKIX_ED25519",
24
+ "validFor": {
25
+ "start": "2025-09-23T00:00:00.000Z"
26
+ }
27
+ },
28
+ "logId": {
29
+ "keyId": "zxGZFVvd0FEmjR8WrFwMdcAJ9vtaY/QXf44Y1wUeP6A="
30
+ }
31
+ }
32
+ ],
33
+ "certificateAuthorities": [
34
+ {
35
+ "subject": {
36
+ "organization": "sigstore.dev",
37
+ "commonName": "sigstore"
38
+ },
39
+ "uri": "https://fulcio.sigstore.dev",
40
+ "certChain": {
41
+ "certificates": [
42
+ {
43
+ "rawBytes": "MIIB+DCCAX6gAwIBAgITNVkDZoCiofPDsy7dfm6geLbuhzAKBggqhkjOPQQDAzAqMRUwEwYDVQQKEwxzaWdzdG9yZS5kZXYxETAPBgNVBAMTCHNpZ3N0b3JlMB4XDTIxMDMwNzAzMjAyOVoXDTMxMDIyMzAzMjAyOVowKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTB2MBAGByqGSM49AgEGBSuBBAAiA2IABLSyA7Ii5k+pNO8ZEWY0ylemWDowOkNa3kL+GZE5Z5GWehL9/A9bRNA3RbrsZ5i0JcastaRL7Sp5fp/jD5dxqc/UdTVnlvS16an+2Yfswe/QuLolRUCrcOE2+2iA5+tzd6NmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMjFHQBBmiQpMlEk6w2uSu1KBtPsMB8GA1UdIwQYMBaAFMjFHQBBmiQpMlEk6w2uSu1KBtPsMAoGCCqGSM49BAMDA2gAMGUCMH8liWJfMui6vXXBhjDgY4MwslmN/TJxVe/83WrFomwmNf056y1X48F9c4m3a3ozXAIxAKjRay5/aj/jsKKGIkmQatjI8uupHr/+CxFvaJWmpYqNkLDGRU+9orzh5hI2RrcuaQ=="
44
+ }
45
+ ]
46
+ },
47
+ "validFor": {
48
+ "start": "2021-03-07T03:20:29.000Z",
49
+ "end": "2022-12-31T23:59:59.999Z"
50
+ }
51
+ },
52
+ {
53
+ "subject": {
54
+ "organization": "sigstore.dev",
55
+ "commonName": "sigstore"
56
+ },
57
+ "uri": "https://fulcio.sigstore.dev",
58
+ "certChain": {
59
+ "certificates": [
60
+ {
61
+ "rawBytes": "MIICGjCCAaGgAwIBAgIUALnViVfnU0brJasmRkHrn/UnfaQwCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMjA0MTMyMDA2MTVaFw0zMTEwMDUxMzU2NThaMDcxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEeMBwGA1UEAxMVc2lnc3RvcmUtaW50ZXJtZWRpYXRlMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8RVS/ysH+NOvu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E7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/VtWB5b9TNMea7Ix/stJ5TfcLLeABLE4BNJOsQ4vnBHJ"
65
+ }
66
+ ]
67
+ },
68
+ "validFor": {
69
+ "start": "2022-04-13T20:06:15.000Z"
70
+ }
71
+ }
72
+ ],
73
+ "ctlogs": [
74
+ {
75
+ "baseUrl": "https://ctfe.sigstore.dev/test",
76
+ "hashAlgorithm": "SHA2_256",
77
+ "publicKey": {
78
+ "rawBytes": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEbfwR+RJudXscgRBRpKX1XFDy3PyudDxz/SfnRi1fT8ekpfBd2O1uoz7jr3Z8nKzxA69EUQ+eFCFI3zeubPWU7w==",
79
+ "keyDetails": "PKIX_ECDSA_P256_SHA_256",
80
+ "validFor": {
81
+ "start": "2021-03-14T00:00:00.000Z",
82
+ "end": "2022-10-31T23:59:59.999Z"
83
+ }
84
+ },
85
+ "logId": {
86
+ "keyId": "CGCS8ChS/2hF0dFrJ4ScRWcYrBY9wzjSbea8IgY2b3I="
87
+ }
88
+ },
89
+ {
90
+ "baseUrl": "https://ctfe.sigstore.dev/2022",
91
+ "hashAlgorithm": "SHA2_256",
92
+ "publicKey": {
93
+ "rawBytes": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEiPSlFi0CmFTfEjCUqF9HuCEcYXNKAaYalIJmBZ8yyezPjTqhxrKBpMnaocVtLJBI1eM3uXnQzQGAJdJ4gs9Fyw==",
94
+ "keyDetails": "PKIX_ECDSA_P256_SHA_256",
95
+ "validFor": {
96
+ "start": "2022-10-20T00:00:00.000Z"
97
+ }
98
+ },
99
+ "logId": {
100
+ "keyId": "3T0wasbHETJjGR4cmWc3AqJKXrjePK3/h4pygC8p7o4="
101
+ }
102
+ }
103
+ ],
104
+ "timestampAuthorities": [
105
+ {
106
+ "subject": {
107
+ "organization": "sigstore.dev",
108
+ "commonName": "sigstore-tsa-selfsigned"
109
+ },
110
+ "uri": "https://timestamp.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