toolcrib 0.11.2 → 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.
package/README.md CHANGED
@@ -90,6 +90,26 @@ patches for `package.json` (adding the toolkit's dependencies and the
90
90
  `#toolcrib` import alias), `.gitignore`, and an `AGENTS.md`/`CLAUDE.md`
91
91
  block your AI assistant should read.
92
92
 
93
+ It also wires toolcrib's six lint rules (vendored under
94
+ `./toolcrib/eslint-rules/`) into your lint config:
95
+
96
+ - **No lint config** — stages a new `.oxlintrc.json` and adds an `oxlint`
97
+ devDependency and a `lint` script (only if you have none) to the same
98
+ `package.json` patch.
99
+ - **An existing `.oxlintrc.json`** — stages an edit adding the plugin, the
100
+ rules and a `toolcrib/**` override that turns them off for the vendored
101
+ source. A rule you already set (even to `"off"`) keeps your severity. A
102
+ file that isn't plain JSON (comments) isn't edited: `init` prints what to
103
+ add instead.
104
+ - **An ESLint flat config** — nothing is changed; `init` prints the two lines
105
+ to add (`import toolcrib from './toolcrib/eslint-rules/index.js'` and
106
+ `...toolcrib.configs.recommended`). Legacy `.eslintrc` can't load local
107
+ rule files, so it gets a note to migrate or use oxlint.
108
+
109
+ `merge` does the same when it stages an upgrade, so an install that predates
110
+ the wiring picks it up on its next version bump. See
111
+ `./toolcrib/eslint-rules/README.md` for the rules themselves.
112
+
93
113
  `--situation` controls whether a **New Project** or **Refactor** guide gets
94
114
  added to that instruction-file block, on top of the core rules that are
95
115
  always included. Skip it and you'll get the core rules only, with a note
@@ -175,10 +195,17 @@ anything. It reports:
175
195
  installed version actually shipped (usually from hand-editing a vendored
176
196
  file directly, which is supported — that's the whole point of vendoring
177
197
  — but worth knowing about).
198
+ - **How your installed version was verified** — Sigstore provenance,
199
+ SHA-256 only (the release predates signing), or "not recorded" if an older
200
+ CLI installed it (your next `toolcrib merge` to a newer version records it). Informational, never a
201
+ failure. See [Download verification](#download-verification).
178
202
  - **Stale instruction-file blocks** — if the `<!-- toolcrib:managed:... -->`
179
203
  block in your `AGENTS.md`/`CLAUDE.md` was hand-edited instead of
180
204
  regenerated, or is out of date with your installed version.
181
205
  - **Whether a newer release is available** — and, when a known, fixed vulnerability affects your installed version specifically, its severity and a link to the fix (generated from real, fixed toolcrib CodeQL findings — see the project's own `AGENTS.md` for how).
206
+ - **Whether the lint rules are wired** — a success line when your lint
207
+ config references toolcrib's plugin; otherwise a warning (never a failing
208
+ exit code) that says how to wire them for your setup.
182
209
  - **A `tsconfig.json` compatibility check** — if `moduleResolution` isn't
183
210
  set to `"bundler"`, `"node16"`, or `"nodenext"`, `import { ... } from
184
211
  '#toolcrib'` will run fine but your editor/`tsc` may falsely report
@@ -321,6 +348,23 @@ toolcrib apply # actually upgrade
321
348
  toolcrib doctor # confirm nothing's left drifted
322
349
  ```
323
350
 
351
+ ## Download verification
352
+
353
+ Every release zip the CLI downloads (`init`, `merge`, `doctor`, `export-patches`) is checked before anything is extracted:
354
+
355
+ - **SHA-256**, against the `.sha256` file published next to the zip. This catches a corrupted or truncated download. It can't catch a tampered release, because that file lives in the same GitHub release as the zip.
356
+ - **Sigstore provenance**, for releases from **v0.17.0** on. Each release publishes `toolcrib-release.sigstore.json`, a signed SLSA provenance statement made by the project's release workflow. The CLI verifies the signature and transparency-log entry, that the signer is `release.yml` running for **that version's own tag**, and that the statement names the exact SHA-256 of the zip you downloaded. Replacing a release's assets now takes forging a signature, and swapping in an older, validly signed release fails the tag check.
357
+
358
+ A release from v0.17.0 on with a missing or invalid bundle is a hard error: nothing is installed. Older releases predate signing, so they're verified by SHA-256 only and the CLI says so. `init` and `merge` record which check applied as `provenance` in `toolcrib/.toolcrib-lock.json`, and `doctor` reports it.
359
+
360
+ Verification uses Sigstore's public trusted root, fetched over TUF from `tuf-repo-cdn.sigstore.dev` (cached in your user app-data directory). If that host can't be reached, the CLI prints a note and uses the trusted root bundled with it instead. If verification then fails, update the toolcrib CLI: the bundled root may be out of date.
361
+
362
+ To check a release by hand with the GitHub CLI:
363
+
364
+ ```bash
365
+ gh attestation verify toolcrib.zip --repo escape-llc/toolcrib
366
+ ```
367
+
324
368
  ## Troubleshooting
325
369
 
326
370
  **`toolcrib apply` says "No pending patches."**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolcrib",
3
- "version": "0.11.2",
3
+ "version": "0.12.0",
4
4
  "description": "Bootstrap the toolcrib UI toolkit into your project",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -16,7 +16,7 @@
16
16
  "src"
17
17
  ],
18
18
  "engines": {
19
- "node": ">=18"
19
+ "node": "^24.15.0 || >=26.0.0"
20
20
  },
21
21
  "scripts": {
22
22
  "test": "vitest run",
@@ -25,6 +25,10 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "@clack/prompts": "^1.7.0",
28
+ "@sigstore/bundle": "^5.0.1",
29
+ "@sigstore/protobuf-specs": "^0.5.2",
30
+ "@sigstore/tuf": "^5.0.1",
31
+ "@sigstore/verify": "^4.1.4",
28
32
  "commander": "^15.0.0",
29
33
  "diff": "^9.0.0",
30
34
  "semver": "^7.6.0"
@@ -89,6 +89,7 @@ export async function applyCommand() {
89
89
 
90
90
  p.log.success(`Applied ${succeeded.length} of ${patchFiles.length} patch(es).`);
91
91
  if (failed.length > 0) {
92
+ process.exitCode = 1;
92
93
  p.log.warn(
93
94
  `${failed.length} patch(es) failed and were kept in ./toolcrib-patches/ (nothing was deleted):\n` +
94
95
  failed.map((f) => ` ${path.basename(f.patchFile)}${f.error ? ` — ${f.error.split('\n')[0]}` : ''}`).join('\n') +
@@ -3,11 +3,13 @@ import semver from 'semver';
3
3
  import * as p from '@clack/prompts';
4
4
  import { fetchRelease, fetchTestsRelease } from '../lib/release.js';
5
5
  import { normalize } from '../lib/patches.js';
6
- import { readJsonIfExists, readLock, readTextIfExists, fileExists } from '../lib/project.js';
6
+ import { readJsonIfExists, readJsoncIfExists, readLock, readTextIfExists, fileExists } from '../lib/project.js';
7
7
  import { fetchLatestVersion, fetchSecurityAdvisories } from '../lib/github.js';
8
8
  import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks } from '../lib/managedDocs.js';
9
9
  import { detectBundler } from '../lib/bundler.js';
10
10
  import { checkRootProviderWired } from '../lib/rootProvider.js';
11
+ import { SIGNED_SINCE } from '../lib/provenance.js';
12
+ import { isLintWired, eslintSnippet, eslintLegacyNote } from '../lib/lintConfig.js';
11
13
 
12
14
  const TOOLKIT_DIR = './toolcrib';
13
15
 
@@ -26,7 +28,7 @@ const IMPORTS_COMPATIBLE_MODULE_RESOLUTIONS = new Set(['bundler', 'node16', 'nod
26
28
  * message ('' meaning unset/default).
27
29
  */
28
30
  export function checkImportsCompatibility(projectRoot) {
29
- const tsconfig = readJsonIfExists(path.join(projectRoot, 'tsconfig.json'));
31
+ const tsconfig = readJsoncIfExists(path.join(projectRoot, 'tsconfig.json'));
30
32
  if (!tsconfig) return null;
31
33
 
32
34
  const moduleResolution = (tsconfig.compilerOptions?.moduleResolution || '').toLowerCase();
@@ -54,6 +56,33 @@ export function checkTypeScriptAdopted(projectRoot) {
54
56
  return fileExists(path.join(projectRoot, 'tsconfig.json'));
55
57
  }
56
58
 
59
+ /**
60
+ * How the installed version's download was verified, per what `init`/`merge`
61
+ * recorded in the lock (`provenance`). Pure, returns log messages like
62
+ * checkManagedBlocks does. A lock with no `provenance` was written by an
63
+ * older CLI: that's not a failure, just unknown until the next merge to a newer version records it (a merge to the same version exits early without rewriting the lock).
64
+ */
65
+ export function describeProvenance(lock) {
66
+ switch (lock.provenance) {
67
+ case 'sigstore':
68
+ return [{ level: 'success', text: `v${lock.version} was installed with Sigstore provenance verified.` }];
69
+ case 'sha256':
70
+ return [
71
+ {
72
+ level: 'info',
73
+ text: `v${lock.version} was installed verified by SHA-256 only (this release predates signing, v${SIGNED_SINCE}).`,
74
+ },
75
+ ];
76
+ default:
77
+ return [
78
+ {
79
+ level: 'info',
80
+ text: `How v${lock.version} was verified isn't recorded (installed by an older toolcrib CLI). The next 'toolcrib merge' to a newer version records it.`,
81
+ },
82
+ ];
83
+ }
84
+ }
85
+
57
86
  /**
58
87
  * Which vendored files (under TOOLKIT_DIR) differ from what `release`
59
88
  * actually shipped — shared by the core-toolkit drift check and the
@@ -233,6 +262,12 @@ export async function doctorCommand(options = {}) {
233
262
  }
234
263
 
235
264
  if (release) {
265
+ // Informational only, never a failure: a successful fetchRelease above
266
+ // already means the installed version's download verified just now.
267
+ // What's reported is what the lock recorded when it was installed.
268
+ for (const message of describeProvenance(lock)) {
269
+ p.log[message.level](message.text);
270
+ }
236
271
  const drifted = computeDrift(projectRoot, release);
237
272
  const managedBlockMessages = await checkManagedBlocks(projectRoot, release);
238
273
  await release.cleanup();
@@ -368,5 +403,19 @@ export async function doctorCommand(options = {}) {
368
403
  );
369
404
  }
370
405
 
406
+ const lint = isLintWired(projectRoot);
407
+ if (lint.wired) {
408
+ p.log.success(`toolcrib lint rules are wired (${lint.file}).`);
409
+ } else if (lint.kind === 'eslint') {
410
+ p.log.warn(`toolcrib's lint rules aren't wired into ${lint.file}.\n${eslintSnippet()}`);
411
+ } else if (lint.kind === 'eslint-legacy') {
412
+ p.log.warn(`toolcrib's lint rules aren't wired into ${lint.file}.\n${eslintLegacyNote()}`);
413
+ } else {
414
+ p.log.warn(
415
+ `toolcrib's lint rules aren't wired into ${lint.file ?? 'any lint config'}. ` +
416
+ `The next 'toolcrib merge' to a newer version stages that; see toolcrib/eslint-rules/README.md to wire them now.`
417
+ );
418
+ }
419
+
371
420
  p.outro('Done.');
372
421
  }
@@ -4,6 +4,7 @@ import { fetchRelease, fetchTestsRelease } from '../lib/release.js';
4
4
  import { resolveVersion } from '../lib/github.js';
5
5
  import { PendingChanges, joinPatchPath, hasStagedWork, STAGED_WORK_MESSAGE } from '../lib/patches.js';
6
6
  import { resolveDependencyDecisions, buildProposedPackageJson, mergeImportsField } from '../lib/deps.js';
7
+ import { planLintWiring } from '../lib/lintConfig.js';
7
8
  import { readJsonIfExists, readTextIfExists, fileExists, proposeGitignore, proposeLockUpdate } from '../lib/project.js';
8
9
  import { MANAGED_DOCS, DEFAULT_TARGET_FILE, KNOWN_TARGET_FILES, upsertManagedBlock } from '../lib/managedDocs.js';
9
10
 
@@ -29,7 +30,7 @@ const SITUATION_TO_DOC_ID = { new: 'new-app', refactor: 'refactor-app' };
29
30
  */
30
31
  function resolveTargetFile(projectRoot) {
31
32
  for (const file of KNOWN_TARGET_FILES) {
32
- if (readTextIfExists(path.join(projectRoot, file))) return file;
33
+ if (fileExists(path.join(projectRoot, file))) return file;
33
34
  }
34
35
  return DEFAULT_TARGET_FILE;
35
36
  }
@@ -137,8 +138,17 @@ export async function initCommand(options) {
137
138
  // Combined into one patch against package.json — a second propose() call
138
139
  // for the same relPath would produce two independent diffs both based on
139
140
  // the original file, which can't both apply cleanly (see PendingChanges).
140
- const importsResult = mergeImportsField(pkgWithAllDeps, TOOLKIT_IMPORTS_ENTRY);
141
- if (depDecisions.toAdd.length > 0 || testsDepDecisions?.toAdd.length > 0 || importsResult.changed) {
141
+ // Lint wiring: toolcrib's rules go into .oxlintrc.json (created when the
142
+ // project has no lint config). Its devDependency + lint script fold into
143
+ // this same package.json patch; an ESLint project only gets printed hints.
144
+ const lintPlan = planLintWiring(projectRoot, pkgWithAllDeps);
145
+ if (lintPlan.configChange) {
146
+ const { relPath, current, proposed } = lintPlan.configChange;
147
+ changes.propose(relPath, current, proposed, relPath);
148
+ }
149
+
150
+ const importsResult = mergeImportsField(lintPlan.pkg, TOOLKIT_IMPORTS_ENTRY);
151
+ if (depDecisions.toAdd.length > 0 || testsDepDecisions?.toAdd.length > 0 || lintPlan.pkgChanged || importsResult.changed) {
142
152
  changes.propose(
143
153
  'package.json',
144
154
  readTextIfExists(pkgPath),
@@ -161,7 +171,7 @@ export async function initCommand(options) {
161
171
  const lockChange = proposeLockUpdate(
162
172
  projectRoot,
163
173
  release.version,
164
- testsRelease ? { testsVersion: testsRelease.version } : {}
174
+ { provenance: release.provenance, ...(testsRelease ? { testsVersion: testsRelease.version } : {}) }
165
175
  );
166
176
  changes.propose(lockChange.relPath, lockChange.current, lockChange.proposed, '.toolcrib-lock.json');
167
177
 
@@ -238,7 +248,8 @@ export async function initCommand(options) {
238
248
  const written = await changes.writeAll(projectRoot);
239
249
  p.log.success(`Staged ${changes.count()} change(s):\n${changes.summarize()}`);
240
250
 
241
- reportConflicts([...depDecisions.conflicts, ...(testsDepDecisions?.conflicts ?? [])]);
251
+ reportConflicts([...depDecisions.conflicts, ...(testsDepDecisions?.conflicts ?? []), ...lintPlan.conflicts]);
252
+ for (const note of lintPlan.notes) p.log.info(note);
242
253
 
243
254
  const missingSituation = !situationDocId
244
255
  ? `\n\nThis staged a "core" block in ${targetFile}, but not a situational one — re-run with ` +
@@ -9,6 +9,7 @@ import { listFilesRecursive } from '../lib/zip.js';
9
9
  import { isBinaryBuffer, detectEol, toEol, mergeThreeWay } from '../lib/lineMerge.js';
10
10
  import { PendingChanges, normalize, joinPatchPath, hasStagedWork, STAGED_WORK_MESSAGE } from '../lib/patches.js';
11
11
  import { resolveDependencyDecisions, buildProposedPackageJson, mergeImportsField } from '../lib/deps.js';
12
+ import { planLintWiring } from '../lib/lintConfig.js';
12
13
  import { fileExists, readJsonIfExists, readLock, readTextIfExists, proposeLockUpdate } from '../lib/project.js';
13
14
  import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks, upsertManagedBlock } from '../lib/managedDocs.js';
14
15
 
@@ -203,6 +204,7 @@ async function diffReleaseFiles(projectRoot, oldRelease, newRelease, ctx) {
203
204
 
204
205
  switch (status) {
205
206
  case 'unchanged':
207
+ break;
206
208
  case 'safe-update':
207
209
  changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, updated, relPath);
208
210
  results.updated++;
@@ -352,9 +354,11 @@ async function mergeManagedBlocks(projectRoot, oldRelease, newRelease, ctx) {
352
354
  // advanced anyway, or the next merge treats the old version's doc as
353
355
  // the "original" and misclassifies this block.
354
356
  proposedFileContent = upsertManagedBlock(proposedFileContent, block.docId, newRelease.version, updatedDocContent);
355
- fileChanged = fileChanged || status !== 'unchanged';
357
+ // 'unchanged' also advances the version= header; propose() drops
358
+ // the patch if nothing at all differs.
359
+ fileChanged = true;
356
360
  if (status === 'converged') results.absorbed.push(`${targetFile} (managed block "${block.docId}")`);
357
- else results.updated++;
361
+ else if (status === 'safe-update') results.updated++;
358
362
  break;
359
363
  case 'keep-local':
360
364
  results.kept++;
@@ -486,6 +490,7 @@ export async function mergeCommand(options) {
486
490
  const userPkg = readJsonIfExists(pkgPath);
487
491
  let depConflicts = [];
488
492
  let removedPeers = [];
493
+ let lintPlan = null;
489
494
  if (userPkg) {
490
495
  const depDecisions = resolveDependencyDecisions(userPkg, newRelease.config?.peerDependencies ?? {});
491
496
  const pkgWithDeps = depDecisions.toAdd.length > 0
@@ -505,8 +510,17 @@ export async function mergeCommand(options) {
505
510
  removedPeers = Object.keys(oldRelease.config?.peerDependencies ?? {}).filter(
506
511
  (name) => !(name in newPeers) && (userPkg.dependencies?.[name] || userPkg.devDependencies?.[name])
507
512
  );
508
- const importsResult = mergeImportsField(pkgWithAllDeps, TOOLKIT_IMPORTS_ENTRY);
509
- if (depDecisions.toAdd.length > 0 || testsDepDecisions?.toAdd.length > 0 || importsResult.changed) {
513
+ // Lint wiring, same behaviour as init. Only reached when merge stages
514
+ // changes (the "already on this version" exit above is untouched), so
515
+ // an install that predates the wiring gets it on its next version bump.
516
+ lintPlan = planLintWiring(projectRoot, pkgWithAllDeps);
517
+ if (lintPlan.configChange) {
518
+ const { relPath, current, proposed } = lintPlan.configChange;
519
+ changes.propose(relPath, current, proposed, relPath);
520
+ }
521
+ depConflicts.push(...lintPlan.conflicts);
522
+ const importsResult = mergeImportsField(lintPlan.pkg, TOOLKIT_IMPORTS_ENTRY);
523
+ if (depDecisions.toAdd.length > 0 || testsDepDecisions?.toAdd.length > 0 || lintPlan.pkgChanged || importsResult.changed) {
510
524
  changes.propose(
511
525
  'package.json',
512
526
  readTextIfExists(pkgPath),
@@ -528,7 +542,7 @@ export async function mergeCommand(options) {
528
542
  const lockChange = proposeLockUpdate(
529
543
  projectRoot,
530
544
  newRelease.version,
531
- lock.testsVersion ? { testsVersion: newRelease.version } : {}
545
+ { provenance: newRelease.provenance, ...(lock.testsVersion ? { testsVersion: newRelease.version } : {}) }
532
546
  );
533
547
  changes.propose(lockChange.relPath, lockChange.current, lockChange.proposed, '.toolcrib-lock.json');
534
548
 
@@ -590,6 +604,7 @@ export async function mergeCommand(options) {
590
604
  .join('\n')
591
605
  );
592
606
  }
607
+ for (const note of lintPlan?.notes ?? []) p.log.info(note);
593
608
  if (removedPeers.length > 0) {
594
609
  p.log.info(
595
610
  `No longer required by toolcrib (left in package.json; remove them if your own code doesn't use them): ${removedPeers.join(', ')}`
package/src/index.js CHANGED
@@ -8,10 +8,10 @@ import { doctorCommand } from './commands/doctor.js';
8
8
  import { versionsCommand } from './commands/versions.js';
9
9
  import { exportPatchesCommand } from './commands/exportPatches.js';
10
10
 
11
- // Read at runtime instead of a JSON import assertion: `assert { type: 'json' }`
12
- // vs `with { type: 'json' }` differs across the Node 18-22 range this CLI's
13
- // `engines.node >= 18` promises to support, so plain fs avoids picking a
14
- // syntax that breaks on some of those versions.
11
+ // Read at runtime instead of a JSON import attribute. This dates from when
12
+ // the CLI supported Node 18-22, where `assert { type: 'json' }` and
13
+ // `with { type: 'json' }` each broke on some versions. Every Node in
14
+ // `engines.node` now supports `with`, so plain fs is just the simpler option.
15
15
  const packageJson = JSON.parse(
16
16
  readFileSync(new URL('../package.json', import.meta.url), 'utf8')
17
17
  );
package/src/lib/fences.js CHANGED
@@ -136,7 +136,7 @@ export function upsertFence(style, fileContent, id, version, content) {
136
136
  const newBlock = buildFence(style, id, version, content);
137
137
  const regex = style.pattern(id);
138
138
  if (regex.test(fileContent)) {
139
- return fileContent.replace(regex, newBlock);
139
+ return fileContent.replace(regex, () => newBlock);
140
140
  }
141
141
  if (fileContent.length === 0) return newBlock;
142
142
  const separator = fileContent.endsWith('\n\n') ? '' : fileContent.endsWith('\n') ? '\n' : '\n\n';
package/src/lib/github.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import crypto from 'node:crypto';
2
+ import * as p from '@clack/prompts';
2
3
  import { assertValidVersion } from './version.js';
4
+ import { PROVENANCE_ASSET_NAME, SIGNED_SINCE, isSignedRelease, loadTrustMaterial, verifyProvenance } from './provenance.js';
3
5
 
4
6
  const REPO = 'escape-llc/toolcrib';
5
7
  const ASSET_NAME = 'toolcrib.zip';
@@ -82,6 +84,13 @@ export async function listVersions() {
82
84
  * much smaller response and the semantically-correct endpoint for this
83
85
  * exact question. 404 means no qualifying release exists yet, per GitHub's
84
86
  * own documented behavior for this endpoint.
87
+ *
88
+ * Refuses a "latest" older than SIGNED_SINCE (#1016). That release is
89
+ * published, so the newest release can never legitimately be older than it.
90
+ * Accepting one would let anyone able to create a release (a leaked
91
+ * contents:write token) mark a fake, unsigned old tag as latest and get it
92
+ * installed with SHA-256 checking only. An explicit --version still installs
93
+ * an older release, because then the user chose it.
85
94
  */
86
95
  export async function fetchLatestVersion() {
87
96
  const res = await fetch(`${API_BASE}/repos/${REPO}/releases/latest`, {
@@ -92,7 +101,15 @@ export async function fetchLatestVersion() {
92
101
  if (!res.ok) throwGitHubApiError(res, 'the latest release');
93
102
 
94
103
  const release = await res.json();
95
- return assertValidVersion(String(release.tag_name).replace(/^v/, ''), 'GitHub API latest release tag');
104
+ const version = assertValidVersion(String(release.tag_name).replace(/^v/, ''), 'GitHub API latest release tag');
105
+ if (!isSignedRelease(version)) {
106
+ throw new Error(
107
+ `GitHub reports v${version} as the latest release, which is older than v${SIGNED_SINCE}, the first signed release. ` +
108
+ `The latest release can't be older than that, so this one is refused. ` +
109
+ `To install an older release on purpose, pass --version <x.y.z>.`
110
+ );
111
+ }
112
+ return version;
96
113
  }
97
114
 
98
115
  /**
@@ -158,24 +175,80 @@ function sha256(buffer) {
158
175
  return crypto.createHash('sha256').update(buffer).digest('hex');
159
176
  }
160
177
 
178
+ // One Sigstore bundle per version per process: a version's core and tests
179
+ // zips are both attested by the same bundle, and `merge` fetches two
180
+ // versions in parallel, so the bundle is fetched and parsed once and every
181
+ // asset of that version shares the promise. The "predates signing" note is
182
+ // likewise printed once per version, by whichever call created the entry.
183
+ const bundleByVersion = new Map();
184
+
185
+ /** Test seam: forget every cached bundle. */
186
+ export function resetBundleCache() {
187
+ bundleByVersion.clear();
188
+ }
189
+
190
+ function getBundle(version) {
191
+ if (!bundleByVersion.has(version)) {
192
+ const url = assetUrl(version, PROVENANCE_ASSET_NAME);
193
+ bundleByVersion.set(
194
+ version,
195
+ // One try/catch around both the fetch and the parse, so a malformed
196
+ // bundle gets the same message and isn't cached either (.then(ok, fail)
197
+ // would let a JSON.parse throw from `ok` skip `fail`).
198
+ (async () => {
199
+ try {
200
+ return JSON.parse(await fetchText(url));
201
+ } catch (err) {
202
+ // Don't cache a failure: a later call in the same process may succeed.
203
+ bundleByVersion.delete(version);
204
+ throw new Error(
205
+ `Failed to fetch the Sigstore provenance bundle for v${version} (${err.message}). ` +
206
+ `Releases since v${SIGNED_SINCE} are signed, so a missing or unreadable bundle is ` +
207
+ `treated as a failed verification. Refusing to install an unverified download.`
208
+ );
209
+ }
210
+ })()
211
+ );
212
+ }
213
+ return bundleByVersion.get(version);
214
+ }
215
+
161
216
  /**
162
- * Download a release zip + its checksum sibling, verify integrity,
163
- * and return the raw buffer. Throws on mismatch (corrupted/truncated
164
- * download, or a tampered file at rest — see design notes on what a
165
- * checksum does and doesn't guarantee against a compromised source).
217
+ * Download a release zip, verify it, and return `{ zipBuffer, provenance }`.
218
+ * Throws on any verification failure.
219
+ *
220
+ * Two layers, both mandatory where they apply:
221
+ *
222
+ * 1. SHA-256 against the `.sha256` sibling. Catches a corrupted or
223
+ * truncated download. It does NOT stop a tampered release: the sibling
224
+ * lives in the same GitHub release as the zip, so whoever can replace the
225
+ * zip can replace the checksum. Every published release has shipped one,
226
+ * so a failed fetch of it (missing, network error, or an on-path actor
227
+ * blocking just that request) is an integrity failure, not an
228
+ * older-release gap.
229
+ * 2. For versions >= SIGNED_SINCE, the Sigstore bundle
230
+ * (`toolcrib-release.sigstore.json`) from the same release: proves the
231
+ * zip was built by this repo's release.yml for this version's own tag
232
+ * (see lib/provenance.js). A missing or invalid bundle is a hard error.
233
+ * Older releases predate signing; they're verified by SHA-256 only and
234
+ * a note says so.
166
235
  *
167
- * Every published release has shipped a .sha256 sibling since this
168
- * mechanism was introduced — a failed fetch of it (missing, network
169
- * error, or an on-path actor blocking just that request) is treated
170
- * as an integrity failure, not tolerated as an older-release gap.
236
+ * `provenance` is 'sigstore' or 'sha256' according to which of those
237
+ * actually verified the download, for callers to record and report.
238
+ *
239
+ * `version` may be 'latest' (resolved here, so the version checked against
240
+ * the signing identity is the concrete one), though every in-repo caller
241
+ * already passes a resolved version.
171
242
  *
172
243
  * `assetName` defaults to the core toolkit zip; release.js's
173
244
  * fetchTestsRelease passes TESTS_ASSET_NAME to fetch the optional
174
245
  * test-suite artifact via this exact same verified-download path instead
175
246
  * of a parallel one — the checksum sibling is always `${assetName}.sha256`,
176
- * the one naming convention both assets already share.
247
+ * the one naming convention both assets already share, and both assets are
248
+ * subjects of the same Sigstore bundle.
177
249
  */
178
- export async function downloadReleaseZip(version, assetName = ASSET_NAME) {
250
+ export async function downloadReleaseZip(requestedVersion, assetName = ASSET_NAME) {
251
+ const version = await resolveVersion(requestedVersion);
179
252
  const checksumAssetName = `${assetName}.sha256`;
180
253
  const zipUrl = assetUrl(version, assetName);
181
254
  const checksumUrl = assetUrl(version, checksumAssetName);
@@ -199,5 +272,17 @@ export async function downloadReleaseZip(version, assetName = ASSET_NAME) {
199
272
  );
200
273
  }
201
274
 
202
- return zipBuffer;
275
+ if (!isSignedRelease(version)) {
276
+ if (!bundleByVersion.has(version)) {
277
+ bundleByVersion.set(version, Promise.resolve(null));
278
+ p.log.info(`v${version} predates release signing (v${SIGNED_SINCE}); verified by SHA-256 only.`);
279
+ }
280
+ return { zipBuffer, provenance: 'sha256' };
281
+ }
282
+
283
+ const bundleJson = await getBundle(version);
284
+ const { trustMaterial, source } = await loadTrustMaterial();
285
+ verifyProvenance({ bundleJson, assetName, digestHex: actual, version, trustMaterial, trustSource: source });
286
+
287
+ return { zipBuffer, provenance: 'sigstore' };
203
288
  }
@@ -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+NOvuDZyPIZtilgUF9NlarYpAd9HP1vBBH1U5CV77LSS7s0ZiH4nE7Hv7ptS6LvvR/STk798LVgMzLlJ4HeIfF3tHSaexLcYpSASr1kS0N/RgBJz/9jWCiXno3sweTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQU39Ppz1YkEZb5qNjpKFWixi4YZD8wHwYDVR0jBBgwFoAUWMAeX5FFpWapesyQoZMi0CrFxfowCgYIKoZIzj0EAwMDZwAwZAIwPCsQK4DYiZYDPIaDi5HFKnfxXx6ASSVmERfsynYBiX2X6SJRnZU84/9DZdnFvvxmAjBOt6QpBlc4J/0DxvkTCqpclvziL6BCCPnjdlIB3Pu3BxsPmygUY7Ii2zbdCdliiow="
62
+ },
63
+ {
64
+ "rawBytes": "MIIB9zCCAXygAwIBAgIUALZNAPFdxHPwjeDloDwyYChAO/4wCgYIKoZIzj0EAwMwKjEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MREwDwYDVQQDEwhzaWdzdG9yZTAeFw0yMTEwMDcxMzU2NTlaFw0zMTEwMDUxMzU2NThaMCoxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjERMA8GA1UEAxMIc2lnc3RvcmUwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAT7XeFT4rb3PQGwS4IajtLk3/OlnpgangaBclYpsYBr5i+4ynB07ceb3LP0OIOZdxexX69c5iVuyJRQ+Hz05yi+UF3uBWAlHpiS5sh0+H2GHE7SXrk1EC5m1Tr19L9gg92jYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRYwB5fkUWlZql6zJChkyLQKsXF+jAfBgNVHSMEGDAWgBRYwB5fkUWlZql6zJChkyLQKsXF+jAKBggqhkjOPQQDAwNpADBmAjEAj1nHeXZp+13NWBNa+EDsDP8G1WWg1tCMWP/WHPqpaVo0jhsweNFZgSs0eE7wYI4qAjEA2WB9ot98sIkoF3vZYdd3/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.sigstore.dev/api/v1/timestamp",
111
+ "certChain": {
112
+ "certificates": [
113
+ {
114
+ "rawBytes": "MIICEDCCAZagAwIBAgIUOhNULwyQYe68wUMvy4qOiyojiwwwCgYIKoZIzj0EAwMwOTEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MSAwHgYDVQQDExdzaWdzdG9yZS10c2Etc2VsZnNpZ25lZDAeFw0yNTA0MDgwNjU5NDNaFw0zNTA0MDYwNjU5NDNaMC4xFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEVMBMGA1UEAxMMc2lnc3RvcmUtdHNhMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE4ra2Z8hKNig2T9kFjCAToGG30jky+WQv3BzL+mKvh1SKNR/UwuwsfNCg4sryoYAd8E6isovVA3M4aoNdm9QDi50Z8nTEyvqgfDPtTIwXItfiW/AFf1V7uwkbkAoj0xxco2owaDAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFIn9eUOHz9BlRsMCRscsc1t9tOsDMB8GA1UdIwQYMBaAFJjsAe9/u1H/1JUeb4qImFMHic6/MBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMIMAoGCCqGSM49BAMDA2gAMGUCMDtpsV/6KaO0qyF/UMsX2aSUXKQFdoGTptQGc0ftq1csulHPGG6dsmyMNd3JB+G3EQIxAOajvBcjpJmKb4Nv+2Taoj8Uc5+b6ih6FXCCKraSqupe07zqswMcXJTe1cExvHvvlw=="
115
+ },
116
+ {
117
+ "rawBytes": "MIIB9zCCAXygAwIBAgIUV7f0GLDOoEzIh8LXSW80OJiUp14wCgYIKoZIzj0EAwMwOTEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MSAwHgYDVQQDExdzaWdzdG9yZS10c2Etc2VsZnNpZ25lZDAeFw0yNTA0MDgwNjU5NDNaFw0zNTA0MDYwNjU5NDNaMDkxFTATBgNVBAoTDHNpZ3N0b3JlLmRldjEgMB4GA1UEAxMXc2lnc3RvcmUtdHNhLXNlbGZzaWduZWQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQUQNtfRT/ou3YATa6wB/kKTe70cfJwyRIBovMnt8RcJph/COE82uyS6FmppLLL1VBPGcPfpQPYJNXzWwi8icwhKQ6W/Qe2h3oebBb2FHpwNJDqo+TMaC/tdfkv/ElJB72jRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBSY7AHvf7tR/9SVHm+KiJhTB4nOvzAKBggqhkjOPQQDAwNpADBmAjEAwGEGrfGZR1cen1R8/DTVMI943LssZmJRtDp/i7SfGHmGRP6gRbuj9vOK3b67Z0QQAjEAuT2H673LQEaHTcyQSZrkp4mX7WwkmF+sVbkYY5mXN+RMH13KUEHHOqASaemYWK/E"
118
+ }
119
+ ]
120
+ },
121
+ "validFor": {
122
+ "start": "2025-07-04T00:00:00.000Z"
123
+ }
124
+ }
125
+ ]
126
+ }
package/src/lib/zip.js CHANGED
@@ -36,6 +36,18 @@ export function powerShellQuote(value) {
36
36
  * release is a few hundred small files.
37
37
  */
38
38
  export function listZipEntryNames(zipBuffer) {
39
+ return readZipCentralDirectory(zipBuffer).map((e) => e.name);
40
+ }
41
+
42
+ /**
43
+ * Read every central-directory entry: its name, and whether its Unix mode
44
+ * (the external attributes' high 16 bits) says it is a symlink. The "version
45
+ * made by" host isn't consulted: Info-ZIP's unzip applies those mode bits for
46
+ * several hosts besides 3/Unix, so a host check would let an attacker pick
47
+ * another one. DOS/Windows-made zips leave the bits at 0, so nothing real
48
+ * is rejected.
49
+ */
50
+ function readZipCentralDirectory(zipBuffer) {
39
51
  const EOCD_SIG = 0x06054b50;
40
52
  const CEN_SIG = 0x02014b50;
41
53
  // The end-of-central-directory record is 22 bytes plus an optional comment
@@ -56,7 +68,7 @@ export function listZipEntryNames(zipBuffer) {
56
68
  throw new Error('Zip64 archives are not supported.');
57
69
  }
58
70
 
59
- const names = [];
71
+ const entries = [];
60
72
  let pos = centralOffset;
61
73
  for (let n = 0; n < entryCount; n++) {
62
74
  if (pos + 46 > zipBuffer.length || zipBuffer.readUInt32LE(pos) !== CEN_SIG) {
@@ -65,10 +77,14 @@ export function listZipEntryNames(zipBuffer) {
65
77
  const nameLen = zipBuffer.readUInt16LE(pos + 28);
66
78
  const extraLen = zipBuffer.readUInt16LE(pos + 30);
67
79
  const commentLen = zipBuffer.readUInt16LE(pos + 32);
68
- names.push(zipBuffer.toString('utf8', pos + 46, pos + 46 + nameLen));
80
+ const externalAttrs = zipBuffer.readUInt32LE(pos + 38);
81
+ entries.push({
82
+ name: zipBuffer.toString('utf8', pos + 46, pos + 46 + nameLen),
83
+ isSymlink: ((externalAttrs >>> 16) & 0o170000) === 0o120000,
84
+ });
69
85
  pos += 46 + nameLen + extraLen + commentLen;
70
86
  }
71
- return names;
87
+ return entries;
72
88
  }
73
89
 
74
90
  /**
@@ -81,7 +97,12 @@ export function listZipEntryNames(zipBuffer) {
81
97
  * than modern unzip (#831).
82
98
  */
83
99
  export function assertSafeZipEntries(zipBuffer) {
84
- for (const name of listZipEntryNames(zipBuffer)) {
100
+ for (const { name, isSymlink } of readZipCentralDirectory(zipBuffer)) {
101
+ // A symlink entry is recreated by unzip on Linux/macOS and then followed
102
+ // by every later read; a toolcrib release never contains one (#1031).
103
+ if (isSymlink) {
104
+ throw new Error(`Refusing to extract an archive with a symlink entry: ${name}`);
105
+ }
85
106
  const segments = name.split(/[\\/]/);
86
107
  if (name.startsWith('/') || name.startsWith('\\') || /^[A-Za-z]:/.test(name) || name.includes('\0') || segments.includes('..')) {
87
108
  throw new Error(`Refusing to extract an archive with an unsafe entry path: ${name}`);
@@ -157,7 +178,9 @@ export function listFilesRecursive(dir, base = dir) {
157
178
  let results = [];
158
179
  for (const entry of entries) {
159
180
  const full = path.join(dir, entry.name);
160
- if (entry.isDirectory()) {
181
+ if (entry.isSymbolicLink()) {
182
+ continue; // defence in depth: never follow or list a link (#1031)
183
+ } else if (entry.isDirectory()) {
161
184
  results = results.concat(listFilesRecursive(full, base));
162
185
  } else {
163
186
  results.push(path.relative(base, full).split(path.sep).join('/'));