@anizoptera/publish-clean 0.6.0 → 0.7.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.
Files changed (2) hide show
  1. package/dist/cli.js +108 -77
  2. package/package.json +1 -1
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
  /**
@@ -171,6 +171,111 @@ function assertDeclaredFiles(pkg, published) {
171
171
  if (missing.length > 0) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((item) => item.path).join("\n")}`);
172
172
  }
173
173
  //#endregion
174
+ //#region src/command.ts
175
+ /**
176
+ * Runs the external tools this CLI depends on: `pnpm`, `npm` and `git`.
177
+ *
178
+ * Never `{ shell: true }`. It space-joins the argument vector with no escaping at all, which
179
+ * Node runtime-deprecated in v24 as shell injection (DEP0190) — and this tool forwards
180
+ * arguments a caller wrote after `--` straight into `npm publish`, so that vector is
181
+ * attacker-shaped by design. Every spawn here passes an argument vector, never a command line.
182
+ */
183
+ /**
184
+ * The probe below is bounded because a wedged shim would otherwise hang the publish with no
185
+ * end: `execFileSync` blocks this thread, so no timer here could ever interrupt it. The bound
186
+ * belongs on the spawn itself. It stays generous because the only job is to separate a tool
187
+ * that answers from one that never will.
188
+ */
189
+ const TOOL_PROBE_TIMEOUT_MS = 1e4;
190
+ /**
191
+ * Windows cannot launch `pnpm` or `npm` directly: both are `.cmd` shims there, and Node's own
192
+ * documentation states a `.cmd` "cannot be launched using child_process.execFile()" — so the
193
+ * spawn fails as ENOENT and the probe below would report a working package manager as missing.
194
+ * Of the three routes Node names, this is the one that adds no parsing of our own: cmd.exe runs
195
+ * the shim AND does the PATH/PATHEXT lookup, so no name resolution belongs here either.
196
+ *
197
+ * `/d` skips registry AutoRun commands, which would otherwise execute inside a publish. Neither
198
+ * `/s` nor `windowsVerbatimArguments` is used: without them Node applies its ordinary C-runtime
199
+ * quoting to every argument, exactly as on any other platform, and there is no second escaping
200
+ * layer to get wrong. The one residual is cmd's `%VAR%` expansion inside an argument, which no
201
+ * argument this tool generates contains; a caller writing one after `--` gets it expanded.
202
+ */
203
+ function spawnArgs(command, args) {
204
+ return process.platform === "win32" ? ["cmd.exe", [
205
+ "/d",
206
+ "/c",
207
+ command,
208
+ ...args
209
+ ]] : [command, [...args]];
210
+ }
211
+ function run(command, args, cwd) {
212
+ return execFileSync(...spawnArgs(command, args), {
213
+ cwd,
214
+ encoding: "utf8",
215
+ stdio: [
216
+ "ignore",
217
+ "pipe",
218
+ "pipe"
219
+ ]
220
+ });
221
+ }
222
+ /**
223
+ * Runs a command with its streams attached to this process instead of captured.
224
+ *
225
+ * Reserved for `npm publish`. Every other command here is run for its output or its
226
+ * effect, but the publish is the one irreversible step, and npm's output is the only
227
+ * receipt the operator gets: the version that went out, the tarball size, the integrity
228
+ * hash, and the registry's own wording when it refuses. `run` would swallow all of it on
229
+ * success and hold the failure text until the process exits, which in CI means a log
230
+ * that says nothing about the one action that cannot be undone.
231
+ */
232
+ function runAttached(command, args, cwd) {
233
+ execFileSync(...spawnArgs(command, args), {
234
+ cwd,
235
+ stdio: [
236
+ "ignore",
237
+ "inherit",
238
+ "inherit"
239
+ ]
240
+ });
241
+ }
242
+ /** Child output survives only on the thrown error, and is lost unless read off it here. */
243
+ function outputFromError(error, key) {
244
+ if (!isObject(error)) return "";
245
+ let output = error[key];
246
+ return typeof output == "string" ? output.trim() : output instanceof Uint8Array ? Buffer.from(output).toString("utf8").trim() : "";
247
+ }
248
+ /**
249
+ * A required tool can fail three ways, and each one asks something different of the
250
+ * reader, so the probe reports what it observed instead of assuming the common case.
251
+ * A version-manager shim (asdf, mise, volta, corepack) resolves in PATH and still refuses
252
+ * to run when no version is pinned; calling that absence sends the reader to verify the
253
+ * one thing already correct, and `which pnpm` then agrees with them and not with us. The
254
+ * shim's own message names the fix, so it is forwarded rather than replaced.
255
+ */
256
+ function toolFailureReason(cause) {
257
+ if (isObject(cause)) {
258
+ if (cause.code === "ENOENT") return "is not available in PATH";
259
+ if (cause.code === "ETIMEDOUT") return `did not answer --version within ${TOOL_PROBE_TIMEOUT_MS}ms`;
260
+ }
261
+ let stderr = outputFromError(cause, "stderr");
262
+ return `failed to run${stderr ? `: ${stderr}` : ""}`;
263
+ }
264
+ function requireTool(name) {
265
+ try {
266
+ execFileSync(...spawnArgs(name, ["--version"]), {
267
+ stdio: [
268
+ "ignore",
269
+ "ignore",
270
+ "pipe"
271
+ ],
272
+ timeout: TOOL_PROBE_TIMEOUT_MS
273
+ });
274
+ } catch (cause) {
275
+ throw new PublishCleanError(`Required tool "${name}" ${toolFailureReason(cause)}.`, { cause });
276
+ }
277
+ }
278
+ //#endregion
174
279
  //#region src/manifest.ts
175
280
  /**
176
281
  * What the published `package.json` carries: which fields survive cleaning, which are refused,
@@ -459,7 +564,7 @@ function reheader(original, size) {
459
564
  * partial write becomes a published package.
460
565
  */
461
566
  function readArchive(gzipped) {
462
- let tar = gunzipSync(gzipped), entries = [], tail = tar.subarray(tar.length);
567
+ let tar = gunzipSync(gzipped), entries = [], tail = null;
463
568
  for (let offset = 0; offset < tar.length;) {
464
569
  let header = tar.subarray(offset, offset + 512);
465
570
  if (header.length < 512) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
@@ -484,6 +589,7 @@ function readArchive(gzipped) {
484
589
  raw: tar.subarray(offset, end)
485
590
  }), offset = end;
486
591
  }
592
+ if (tail === null) throw new PublishCleanError("Tarball has no end-of-archive marker; the archive is truncated.");
487
593
  return {
488
594
  entries,
489
595
  tail
@@ -577,9 +683,6 @@ function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
577
683
  if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
578
684
  if (githubRepositorySlug(repoUrl) !== env.GITHUB_REPOSITORY) throw new PublishCleanError(`package.json repository.url must match GITHUB_REPOSITORY (${env.GITHUB_REPOSITORY}); found ${repoUrl}.`);
579
685
  }
580
- //#endregion
581
- //#region src/cli.ts
582
- const TOOL_PROBE_TIMEOUT_MS = 1e4;
583
686
  /**
584
687
  * Read from the installed manifest rather than baked in at build time, so the number cannot
585
688
  * drift from the package a user actually has — which is the only reason anyone asks a tool
@@ -599,78 +702,6 @@ function readJson(file) {
599
702
  if (!isObject(parsed)) throw new PublishCleanError(`${file} must contain a JSON object.`);
600
703
  return parsed;
601
704
  }
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
- /**
619
- * Runs a command with its streams attached to this process instead of captured.
620
- *
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.
659
- */
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
705
  function npmVersion() {
675
706
  let raw = run("npm", ["--version"], process.cwd()).trim(), parts = raw.split(".").map((part) => Number.parseInt(part, 10));
676
707
  if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse npm version: ${raw}`);
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.0",
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",