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.
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.1",
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
  }
@@ -80,6 +80,23 @@ async function postExport(options) {
80
80
  .filter((d) => d.isDirectory())
81
81
  .map((d) => d.name)
82
82
  .sort();
83
+ // The README was written at export time; the user may have deleted folders since.
84
+ const readmePath = path.join(outDir, 'README.md');
85
+ if (fs.existsSync(readmePath)) {
86
+ const listed = new Set();
87
+ for (const line of fs.readFileSync(readmePath, 'utf8').split(/\r?\n/)) {
88
+ const m = /^\|\s*(\d+-[^\s|]+)\s*\|/.exec(line);
89
+ if (m) listed.add(m[1]);
90
+ }
91
+ const missing = [...listed].filter((f) => !folders.includes(f)).sort();
92
+ const unlisted = folders.filter((f) => !listed.has(f));
93
+ if (missing.length) {
94
+ p.log.warn(`README.md lists contribution(s) whose folder is missing (not posted): ${missing.join(', ')}`);
95
+ }
96
+ if (unlisted.length) {
97
+ p.log.warn(`Folder(s) present but not listed in README.md: ${unlisted.join(', ')}`);
98
+ }
99
+ }
83
100
  const plans = [];
84
101
  for (const folder of folders) {
85
102
  const dir = path.join(outDir, folder);
@@ -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
  );
@@ -177,6 +177,8 @@ export function renderReadme({ baseVersion, entries, notExported, regeneratedUps
177
177
  '',
178
178
  "Fill in each contribution's `intent:` lines in its SUMMARY.md before posting.",
179
179
  '',
180
+ 'This README describes the export as generated. If you delete a contribution folder you do not want to send, this file is not updated; `--post` sends only the folders still present.',
181
+ '',
180
182
  '## Contributions',
181
183
  '',
182
184
  ];
@@ -30,6 +30,38 @@ export const VALID_CATEGORIES = ['Layout Primitives', 'Containers', 'Overlays',
30
30
 
31
31
  const INFRA_DIRS = ['theme', 'eventBus', 'observer'];
32
32
  const CODE_FILE = /\.[cm]?[jt]sx?$/;
33
+
34
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
35
+
36
+ /**
37
+ * The binding names imported from `specifier` across every import/export
38
+ * statement naming it: default, named (by their exported name), `*`, and
39
+ * `side-effect` for a bare `import 'x'` or a dynamic import. Whitespace and
40
+ * order don't matter, so reformatting an import line changes nothing.
41
+ */
42
+ function importedNames(source, specifier) {
43
+ const code = stripComments(source);
44
+ const q = `['"]${escapeRegExp(specifier)}['"]`;
45
+ const names = new Set();
46
+ const re = new RegExp(`\\b(?:import|export)\\s+(?:type\\s+)?([^'";]*?)\\s*from\\s*${q}`, 'g');
47
+ let m;
48
+ while ((m = re.exec(code))) {
49
+ const clause = m[1];
50
+ const braces = /\{([^}]*)\}/.exec(clause);
51
+ if (braces) {
52
+ for (const part of braces[1].split(',')) {
53
+ const name = part.trim().replace(/^type\s+/, '').split(/\s+as\s+/)[0].trim();
54
+ if (name) names.add(name);
55
+ }
56
+ }
57
+ const outside = clause.replace(/\{[^}]*\}/, '');
58
+ if (/\*/.test(outside)) names.add('*');
59
+ const def = outside.replace(/\*(\s*as\s+\w+)?/, '').replace(/,/g, ' ').trim();
60
+ if (def) names.add('default');
61
+ }
62
+ if (new RegExp(`\\bimport\\s*(?:\\(\\s*)?${q}`).test(code)) names.add('side-effect');
63
+ return names;
64
+ }
33
65
  const MANIFEST_BLOCK_RE = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/\s*export\s+(?:const|function)\s+(\w+)/g;
34
66
  const EXPORT_DECL_RE = /\bexport\s+(?:declare\s+)?(?:abstract\s+)?(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;
35
67
  /** Raw React prop types that carry style/className, as an extends, intersection or alias. */
@@ -265,6 +297,31 @@ export function analyzeExport({ releaseFiles, localFiles }) {
265
297
  const isInfraCandidate = (p) => changed.has(p) && INFRA_DIRS.includes(topSegment(p)) && !unitOf.has(p);
266
298
  const reachedBy = new Map(); // candidate relPath -> Set(unit key)
267
299
  const reachedPerUnit = new Map();
300
+ const dependencyPerUnit = new Map();
301
+ const relHas = (p) => rel.has(p);
302
+ // Resolved import target -> the names imported from it (see importedNames).
303
+ const resolvedImports = (content, relPath, exists) => {
304
+ const out = new Map();
305
+ if (content === undefined || !CODE_FILE.test(relPath)) return out;
306
+ for (const spec of extractImports(content)) {
307
+ const resolved = resolveRelativeImport(relPath, spec, exists);
308
+ if (!resolved) continue;
309
+ if (!out.has(resolved)) out.set(resolved, new Set());
310
+ for (const n of importedNames(content, spec)) out.get(resolved).add(n);
311
+ }
312
+ return out;
313
+ };
314
+ // Import targets the unit's own change introduced: a target the release
315
+ // version didn't import, or one it now imports a name from that it didn't
316
+ // before (a new export used through an import line that already existed).
317
+ // An added file counts all its imports; a deleted file contributes none.
318
+ const newImportTargets = (relPath) => {
319
+ const before = resolvedImports(rel.get(relPath), relPath, relHas);
320
+ const after = resolvedImports(loc.get(relPath), relPath, localHas);
321
+ return [...after]
322
+ .filter(([t, names]) => !before.has(t) || [...names].some((n) => !before.get(t).has(n)))
323
+ .map(([t]) => t);
324
+ };
268
325
  for (const [key, unit] of units) {
269
326
  const seen = new Set(unit.paths);
270
327
  const stack = [...unit.paths];
@@ -286,6 +343,22 @@ export function analyzeExport({ releaseFiles, localFiles }) {
286
343
  }
287
344
  }
288
345
  reachedPerUnit.set(key, reached);
346
+ // Dependency, as opposed to reachability: only what the unit's own change newly imports.
347
+ const dependencySeen = new Set(unit.paths);
348
+ const dependencyStack = [];
349
+ for (const f of unit.paths) dependencyStack.push(...newImportTargets(f));
350
+ const dependsOnFiles = new Set();
351
+ while (dependencyStack.length) {
352
+ const d = dependencyStack.pop();
353
+ if (dependencySeen.has(d)) continue;
354
+ dependencySeen.add(d);
355
+ if (SHARED_FILES.includes(d)) continue;
356
+ const owner = unitOf.get(d);
357
+ if (owner !== undefined && owner !== key) continue; // another unit's own files
358
+ if (isInfraCandidate(d)) dependsOnFiles.add(d);
359
+ for (const n of deps(d)) dependencyStack.push(n);
360
+ }
361
+ dependencyPerUnit.set(key, dependsOnFiles);
289
362
  unit.missingDependencies = [...missing].sort();
290
363
  for (const d of reached) {
291
364
  if (!reachedBy.has(d)) reachedBy.set(d, new Set());
@@ -335,7 +408,7 @@ export function analyzeExport({ releaseFiles, localFiles }) {
335
408
  infra.sort((a, b) => a.name.localeCompare(b.name));
336
409
  for (const [key, unit] of units) {
337
410
  const names = new Set();
338
- for (const d of reachedPerUnit.get(key)) {
411
+ for (const d of dependencyPerUnit.get(key)) {
339
412
  if (infraOfFile.has(d)) names.add(infraOfFile.get(d).name);
340
413
  }
341
414
  unit.dependsOn = [...names].sort();
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
  }