@anizoptera/publish-clean 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +21 -0
  2. package/dist/cli.js +154 -90
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -61,6 +61,27 @@ supply-chain risk of its own, and this one has no transitive code to audit.
61
61
  `--provenance` additionally needs npm 11.5.1+ and a cloud CI runner. npm will not sign a
62
62
  publish that came from your laptop.
63
63
 
64
+ ### Running it under Bun packs a smaller tarball
65
+
66
+ gzip encoding belongs to whichever runtime executes the CLI, and Bun's (libdeflate) beats
67
+ Node's zlib on tar-shaped data: 0.17% smaller for this package, 0.28% for a sibling one, with
68
+ a byte-identical archive inside. To get it, pass Bun the **file path**:
69
+
70
+ ```sh
71
+ bun ./node_modules/.bin/publish-clean
72
+ ```
73
+
74
+ Naming the bin instead does not work, and does not say so: `bun publish-clean`,
75
+ `bun run publish-clean` and `bunx publish-clean` all hand the file to the OS, which honours
76
+ its `#!/usr/bin/env node` shebang and runs Node. They succeed, and you get Node's bytes.
77
+
78
+ Not `bunx --bun`, which forces Bun onto the `pnpm` this tool spawns as well; pnpm 11 needs
79
+ `node:sqlite`, which Bun does not implement, and that is the error you get.
80
+
81
+ Either runtime produces valid gzip with identical contents, so the choice is free. The one
82
+ rule is not to switch runtimes _within_ a version: if a release is re-run to repair its
83
+ artifacts, the bytes have to come out the same, and the two encoders do not agree.
84
+
64
85
  ## Package managers
65
86
 
66
87
  Why pnpm packs and npm publishes: pnpm is the only packer that resolves every workspace
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import { execFileSync } from "node:child_process";
3
2
  import { readFileSync } from "node:fs";
4
3
  import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
5
4
  import { tmpdir } from "node:os";
6
5
  import path from "node:path";
7
6
  import { fileURLToPath } from "node:url";
8
7
  import { parseArgs } from "node:util";
8
+ import { execFileSync } from "node:child_process";
9
9
  import { gunzipSync, gzipSync } from "node:zlib";
10
10
  //#region src/error.ts
11
11
  /**
@@ -45,9 +45,9 @@ function stableValue(value) {
45
45
  //#region src/artifact.ts
46
46
  /**
47
47
  * What the published tarball may carry, and what it must. Every rule here judges a file list —
48
- * the paths `tar` reads out of the archive, with the `package/` prefix already stripped — never
49
- * a directory on disk, because that list is what a consumer's installer unpacks and it needs no
50
- * filesystem to exist.
48
+ * the archive's entry paths with the `package/` prefix already stripped — never a directory on
49
+ * disk, because that list is what a consumer's installer unpacks and it needs no filesystem to
50
+ * exist.
51
51
  *
52
52
  * Ambient inputs arrive as parameters and never by reaching for them — no process, filesystem or
53
53
  * argv here. `cli.ts` owns the effects.
@@ -95,8 +95,10 @@ function validatePackedFiles(files, skipSuspicious) {
95
95
  * dropped file: the leak checks only ask what is present, and a package missing a file installs
96
96
  * fine and then fails at import, on a version the registry keeps forever.
97
97
  *
98
- * Both lists are read out of the archives by `tar`, an instrument that cannot share a mistake
99
- * with the walk being checked.
98
+ * The two lists come from the same reader, so this cannot catch a defect in the reader itself —
99
+ * only one in the rewrite, which is what it is for. Independence from the reader is bought
100
+ * elsewhere, by the case in test/cli.test.ts that compares the list this reader prints against
101
+ * `tar tzf` of the same tarball — an instrument that cannot share a mistake with this one.
100
102
  */
101
103
  function assertSameEntries(packed, published) {
102
104
  let before = new Set(packed), after = new Set(published), changed = [...packed.filter((file) => !after.has(file)).map((file) => `- ${file}`), ...published.filter((file) => !before.has(file)).map((file) => `+ ${file}`)];
@@ -171,6 +173,113 @@ function assertDeclaredFiles(pkg, published) {
171
173
  if (missing.length > 0) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((item) => item.path).join("\n")}`);
172
174
  }
173
175
  //#endregion
176
+ //#region src/command.ts
177
+ /**
178
+ * Runs the external tools this CLI depends on: `pnpm`, `npm` and `git`.
179
+ *
180
+ * Never `{ shell: true }`. It space-joins the argument vector with no escaping at all, which
181
+ * Node runtime-deprecated in v24 as shell injection (DEP0190) — and this tool forwards
182
+ * arguments a caller wrote after `--` straight into `npm publish`, so that vector is
183
+ * attacker-shaped by design. Every spawn here passes an argument vector, never a command line.
184
+ */
185
+ /**
186
+ * The probe below is bounded because a wedged shim would otherwise hang the publish with no
187
+ * end: `execFileSync` blocks this thread, so no timer here could ever interrupt it. The bound
188
+ * belongs on the spawn itself. It stays generous because the only job is to separate a tool
189
+ * that answers from one that never will.
190
+ */
191
+ const TOOL_PROBE_TIMEOUT_MS = 1e4;
192
+ /**
193
+ * Windows cannot launch `pnpm` or `npm` directly: both are `.cmd` shims there, and Node's own
194
+ * documentation states a `.cmd` "cannot be launched using child_process.execFile()" — so the
195
+ * spawn fails as ENOENT and the probe below would report a working package manager as missing.
196
+ * Of the three routes Node names, this is the one that adds no parsing of our own: cmd.exe runs
197
+ * the shim AND does the PATH/PATHEXT lookup, so no name resolution belongs here either.
198
+ *
199
+ * `/d` skips registry AutoRun commands, which would otherwise execute inside a publish. Neither
200
+ * `/s` nor `windowsVerbatimArguments` is used: without them Node applies its ordinary C-runtime
201
+ * quoting to every argument, exactly as on any other platform, so this file owns no escaping.
202
+ * What it owns instead is the refusal below, which is what keeps that true.
203
+ */
204
+ function spawnArgs(command, args, platform) {
205
+ if (platform !== "win32") return [command, [...args]];
206
+ let unsafe = [command, ...args].filter((argument) => /[&|<>^%()]/.test(argument));
207
+ if (unsafe.length > 0) throw new PublishCleanError(`On Windows these arguments cannot be passed safely, because cmd.exe would interpret them:\n${unsafe.join("\n")}\nMove the package to a path without & | < > ^ % ( ), or publish from Linux or macOS.`);
208
+ return ["cmd.exe", [
209
+ "/d",
210
+ "/c",
211
+ command,
212
+ ...args
213
+ ]];
214
+ }
215
+ function run(command, args, cwd) {
216
+ return execFileSync(...spawnArgs(command, args, process.platform), {
217
+ cwd,
218
+ encoding: "utf8",
219
+ stdio: [
220
+ "ignore",
221
+ "pipe",
222
+ "pipe"
223
+ ]
224
+ });
225
+ }
226
+ /**
227
+ * Runs a command with its streams attached to this process instead of captured.
228
+ *
229
+ * Reserved for `npm publish`. Every other command here is run for its output or its
230
+ * effect, but the publish is the one irreversible step, and npm's output is the only
231
+ * receipt the operator gets: the version that went out, the tarball size, the integrity
232
+ * hash, and the registry's own wording when it refuses. `run` would swallow all of it on
233
+ * success and hold the failure text until the process exits, which in CI means a log
234
+ * that says nothing about the one action that cannot be undone.
235
+ */
236
+ function runAttached(command, args, cwd) {
237
+ execFileSync(...spawnArgs(command, args, process.platform), {
238
+ cwd,
239
+ stdio: [
240
+ "ignore",
241
+ "inherit",
242
+ "inherit"
243
+ ]
244
+ });
245
+ }
246
+ /** Child output survives only on the thrown error, and is lost unless read off it here. */
247
+ function outputFromError(error, key) {
248
+ if (!isObject(error)) return "";
249
+ let output = error[key];
250
+ return typeof output == "string" ? output.trim() : output instanceof Uint8Array ? Buffer.from(output).toString("utf8").trim() : "";
251
+ }
252
+ /**
253
+ * A required tool can fail three ways, and each one asks something different of the
254
+ * reader, so the probe reports what it observed instead of assuming the common case.
255
+ * A version-manager shim (asdf, mise, volta, corepack) resolves in PATH and still refuses
256
+ * to run when no version is pinned; calling that absence sends the reader to verify the
257
+ * one thing already correct, and `which pnpm` then agrees with them and not with us. The
258
+ * shim's own message names the fix, so it is forwarded rather than replaced.
259
+ */
260
+ function toolFailureReason(cause) {
261
+ if (isObject(cause)) {
262
+ if (cause.code === "ENOENT") return "is not available in PATH";
263
+ if (cause.code === "ETIMEDOUT") return `did not answer --version within ${TOOL_PROBE_TIMEOUT_MS}ms`;
264
+ }
265
+ let stderr = outputFromError(cause, "stderr");
266
+ return `failed to run${stderr ? `: ${stderr}` : ""}`;
267
+ }
268
+ function requireTool(name) {
269
+ try {
270
+ execFileSync(...spawnArgs(name, ["--version"], process.platform), {
271
+ stdio: [
272
+ "ignore",
273
+ "ignore",
274
+ "pipe"
275
+ ],
276
+ timeout: TOOL_PROBE_TIMEOUT_MS
277
+ });
278
+ } catch (cause) {
279
+ throw new PublishCleanError(`Required tool "${name}" ${toolFailureReason(cause)}.`, { cause });
280
+ }
281
+ }
282
+ //#endregion
174
283
  //#region src/manifest.ts
175
284
  /**
176
285
  * What the published `package.json` carries: which fields survive cleaning, which are refused,
@@ -430,6 +539,28 @@ function entrySize(block) {
430
539
  return size;
431
540
  }
432
541
  /**
542
+ * Verifies a header block against the checksum tar stores inside it.
543
+ *
544
+ * This is the format's own integrity check over the 512 bytes that say where an entry starts,
545
+ * how long it is and what it is called — the fields a walk trusts absolutely. The gzip CRC
546
+ * already covers every byte of the archive, so on a packed tarball this is redundant; it is
547
+ * here because the rewrite AUTHORS one of these blocks, and a checksum nothing verifies is a
548
+ * value vouching for itself. Reading the written artifact back runs this over that block.
549
+ *
550
+ * Both sums are accepted because tar has two historical conventions: the standard sums the
551
+ * bytes unsigned, while older implementations summed them as signed chars. The two agree for
552
+ * every all-ASCII header and diverge the moment a name carries a byte above 127, so refusing
553
+ * the signed form would reject valid archives holding non-ASCII filenames.
554
+ */
555
+ function assertChecksum(header, name) {
556
+ let stored = Number.parseInt(field(header, 148, 8).trim(), 8), unsigned = 0, signed = 0;
557
+ for (let [index, byte] of header.entries()) {
558
+ let value = index >= 148 && index < 156 ? 32 : byte;
559
+ unsigned += value, signed += value > 127 ? value - 256 : value;
560
+ }
561
+ if (stored !== unsigned && stored !== signed) throw new PublishCleanError(`Tarball entry ${name} has a corrupt header checksum.`);
562
+ }
563
+ /**
433
564
  * Rejects a pax header that renames another entry onto the manifest path.
434
565
  *
435
566
  * Without this the archive could extract a `package.json` that no check ever saw: the guards
@@ -459,7 +590,7 @@ function reheader(original, size) {
459
590
  * partial write becomes a published package.
460
591
  */
461
592
  function readArchive(gzipped) {
462
- let tar = gunzipSync(gzipped), entries = [], tail = tar.subarray(tar.length);
593
+ let tar = gunzipSync(gzipped), entries = [], tail = null;
463
594
  for (let offset = 0; offset < tar.length;) {
464
595
  let header = tar.subarray(offset, offset + 512);
465
596
  if (header.length < 512) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
@@ -468,6 +599,7 @@ function readArchive(gzipped) {
468
599
  tail = tar.subarray(offset);
469
600
  break;
470
601
  }
602
+ assertChecksum(header, name);
471
603
  let size = entrySize(header), end = offset + 512 + 512 * Math.ceil(size / 512);
472
604
  if (end > tar.length) throw new PublishCleanError(`Tarball entry ${name} runs past the end of the archive.`);
473
605
  let type = field(header, 156, 1), body = tar.subarray(offset + 512, offset + 512 + size);
@@ -484,6 +616,7 @@ function readArchive(gzipped) {
484
616
  raw: tar.subarray(offset, end)
485
617
  }), offset = end;
486
618
  }
619
+ if (tail === null) throw new PublishCleanError("Tarball has no end-of-archive marker; the archive is truncated.");
487
620
  return {
488
621
  entries,
489
622
  tail
@@ -577,9 +710,6 @@ function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
577
710
  if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
578
711
  if (githubRepositorySlug(repoUrl) !== env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
579
712
  }
580
- //#endregion
581
- //#region src/cli.ts
582
- const TOOL_PROBE_TIMEOUT_MS = 1e4;
583
713
  /**
584
714
  * Read from the installed manifest rather than baked in at build time, so the number cannot
585
715
  * drift from the package a user actually has — which is the only reason anyone asks a tool
@@ -599,81 +729,19 @@ function readJson(file) {
599
729
  if (!isObject(parsed)) throw new PublishCleanError(`${file} must contain a JSON object.`);
600
730
  return parsed;
601
731
  }
602
- function run(command, args, cwd) {
603
- return execFileSync(command, [...args], {
604
- cwd,
605
- encoding: "utf8",
606
- stdio: [
607
- "ignore",
608
- "pipe",
609
- "pipe"
610
- ]
611
- });
612
- }
613
- function outputFromError(error, key) {
614
- if (!isObject(error)) return "";
615
- let output = error[key];
616
- return typeof output == "string" ? output.trim() : output instanceof Uint8Array ? Buffer.from(output).toString("utf8").trim() : "";
617
- }
618
732
  /**
619
- * Runs a command with its streams attached to this process instead of captured.
733
+ * Asks an executable on PATH what version it is, e.g. `24.15.0` from node's `v24.15.0`.
620
734
  *
621
- * Reserved for `npm publish`. Every other command here is run for its output or its
622
- * effect, but the publish is the one irreversible step, and npm's output is the only
623
- * receipt the operator gets: the version that went out, the tarball size, the integrity
624
- * hash, and the registry's own wording when it refuses. `run` would swallow all of it on
625
- * success and hold the failure text until the process exits, which in CI means a log
626
- * that says nothing about the one action that cannot be undone.
627
- */
628
- function runAttached(command, args, cwd) {
629
- execFileSync(command, [...args], {
630
- cwd,
631
- stdio: [
632
- "ignore",
633
- "inherit",
634
- "inherit"
635
- ]
636
- });
637
- }
638
- /**
639
- * A required tool can fail three ways, and each one asks something different of the
640
- * reader, so the probe reports what it observed instead of assuming the common case.
641
- * A version-manager shim (asdf, mise, volta, corepack) resolves in PATH and still refuses
642
- * to run when no version is pinned; calling that absence sends the reader to verify the
643
- * one thing already correct, and `which pnpm` then agrees with them and not with us. The
644
- * shim's own message names the fix, so it is forwarded rather than replaced.
645
- */
646
- function toolFailureReason(cause) {
647
- if (isObject(cause)) {
648
- if (cause.code === "ENOENT") return "is not available in PATH";
649
- if (cause.code === "ETIMEDOUT") return `did not answer --version within ${TOOL_PROBE_TIMEOUT_MS}ms`;
650
- }
651
- let stderr = outputFromError(cause, "stderr");
652
- return `is present but failed to run${stderr ? `: ${stderr}` : ""}`;
653
- }
654
- /**
655
- * The probe is bounded because a wedged shim would otherwise hang the publish with no end:
656
- * `execFileSync` blocks this thread, so no timer here could ever interrupt it. The bound
657
- * belongs on the spawn itself. It stays generous because the only job is to separate a
658
- * tool that answers from one that never will.
735
+ * Both provenance floors are asked of PATH rather than read from this process, because the
736
+ * process that has to satisfy them is npm's, not this one. `npm` is a `#!/usr/bin/env node`
737
+ * script, so the Node enforcing the floor is whichever one PATH resolves — and that is not
738
+ * necessarily the one executing this file. Under Bun the gap is total: `process.versions.node`
739
+ * is a compatibility claim (1.3.14 reports 24.3.0) about a runtime that never runs npm at all,
740
+ * so reading it would answer a question nobody asked while looking exactly like a check.
659
741
  */
660
- function requireTool(name) {
661
- try {
662
- execFileSync(name, ["--version"], {
663
- stdio: [
664
- "ignore",
665
- "ignore",
666
- "pipe"
667
- ],
668
- timeout: TOOL_PROBE_TIMEOUT_MS
669
- });
670
- } catch (cause) {
671
- throw new PublishCleanError(`Required tool "${name}" ${toolFailureReason(cause)}.`, { cause });
672
- }
673
- }
674
- function npmVersion() {
675
- let raw = run("npm", ["--version"], process.cwd()).trim(), parts = raw.split(".").map((part) => Number.parseInt(part, 10));
676
- if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse npm version: ${raw}`);
742
+ function toolVersion(command) {
743
+ let raw = run(command, ["--version"], process.cwd()).trim().replace(/^v/, ""), parts = raw.split(".").map((part) => Number.parseInt(part, 10));
744
+ if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse ${command} version: ${raw}`);
677
745
  return [
678
746
  parts[0] ?? 0,
679
747
  parts[1] ?? 0,
@@ -694,14 +762,10 @@ function publishEnv() {
694
762
  }
695
763
  function assertTrustedPublishingRuntime(pkg, publishArgs) {
696
764
  if (!wantsTrustedPublish(pkg, publishArgs, publishEnv())) return;
697
- let actual = npmVersion();
698
- if (!isAtLeast(actual, MIN_TRUSTED_NPM_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires npm ${MIN_TRUSTED_NPM_VERSION.join(".")} or newer; found ${actual.join(".")}.`);
699
- let node = process.versions.node.split(".").map(Number);
700
- if (!isAtLeast([
701
- node[0] ?? 0,
702
- node[1] ?? 0,
703
- node[2] ?? 0
704
- ], MIN_TRUSTED_NODE_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${process.versions.node}.`);
765
+ let npm = toolVersion("npm");
766
+ if (!isAtLeast(npm, MIN_TRUSTED_NPM_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires npm ${MIN_TRUSTED_NPM_VERSION.join(".")} or newer; found ${npm.join(".")}.`);
767
+ let node = toolVersion("node");
768
+ if (!isAtLeast(node, MIN_TRUSTED_NODE_VERSION)) throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${node.join(".")}.`);
705
769
  }
706
770
  function warnIfNonPnpmLifecycle() {
707
771
  let userAgent = process.env.npm_config_user_agent;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anizoptera/publish-clean",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "description": "Pre-publish npm package cleaner that strips common useless noise and crap from package.json; prevents accidental publication of unwanted things and unresolved dependencies. No deps, one JS file.",
5
5
  "keywords": [
6
6
  "bun",