@anizoptera/publish-clean 0.7.3 → 0.9.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 +166 -231
  2. package/dist/cli.js +617 -372
  3. package/package.json +4 -2
package/dist/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- // @anizoptera/publish-clean 0.7.3 | https://github.com/Anizoptera/publish-clean#readme
3
+ // @anizoptera/publish-clean 0.9.1 | https://github.com/Anizoptera/publish-clean#readme
4
4
  import { readFileSync } from "node:fs";
5
5
  import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
6
6
  import { tmpdir } from "node:os";
7
7
  import path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
+ import { spawn } from "node:child_process";
9
10
  import { parseArgs } from "node:util";
10
- import { execFileSync } from "node:child_process";
11
11
  import { gunzipSync, gzipSync } from "node:zlib";
12
12
 
13
13
  //#region src/error.ts
@@ -36,18 +36,6 @@ function isObject(value) {
36
36
  function stringifyJson(value) {
37
37
  return `${JSON.stringify(value, null, 2)}\n`;
38
38
  }
39
- /**
40
- * The form used only to compare two manifests for equality. Key order carries no meaning to a
41
- * consumer, so comparing the written form would report a difference where none exists.
42
- */
43
- function stableJson(value) {
44
- return JSON.stringify(stableValue(value));
45
- }
46
- function stableValue(value) {
47
- if (Array.isArray(value)) return value.map(stableValue);
48
- if (!isObject(value)) return value;
49
- return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, stableValue(child)]));
50
- }
51
39
 
52
40
  //#endregion
53
41
  //#region src/artifact.ts
@@ -90,10 +78,10 @@ const SUSPICIOUS_PATTERNS = [
90
78
  ];
91
79
  function validatePackedFiles(files, skipSuspicious) {
92
80
  const critical = files.filter((file) => CRITICAL_PATTERNS.some((pattern) => pattern.test(file)));
93
- if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.join("\n")}`);
81
+ if (critical.length > 0) throw new PublishCleanError(`Critical files must not be published:\n${critical.map((file) => JSON.stringify(file)).join("\n")}`);
94
82
  if (skipSuspicious) return;
95
83
  const suspicious = files.filter((file) => SUSPICIOUS_PATTERNS.some((pattern) => pattern.test(file)));
96
- if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.join("\n")}`);
84
+ if (suspicious.length > 0) throw new PublishCleanError(`Suspicious files in package artifact:\n${suspicious.map((file) => JSON.stringify(file)).join("\n")}`);
97
85
  }
98
86
  /**
99
87
  * Refuses a rewritten tarball whose file set is not the packed one, entry for entry.
@@ -125,13 +113,13 @@ function assertSameEntries(packed, published) {
125
113
  *
126
114
  * - `"every-string"` for `main`, `module`, `types`, `typings`, `bin` and `typesVersions`,
127
115
  * where every string is a path into this package.
128
- * - `"relative-only"` for `exports`, `imports`, `sideEffects` and the object form of
116
+ * - `"relative-only"` for `sideEffects` and the object form of
129
117
  * `browser`, where a string may just as well be an external package name, a condition
130
118
  * target or a glob. Only a `./` or `../` prefix marks it as a path here. Collecting the
131
119
  * rest would report a missing file for something that was never a file.
132
120
  *
133
121
  * Booleans are skipped rather than ignored by accident: `sideEffects: false` and
134
- * `exports` condition values legitimately hold them.
122
+ * `browser` replacements legitimately hold them. Export/import targets use their own walker.
135
123
  */
136
124
  function collectDeclaredPaths(value, out, mode) {
137
125
  if (typeof value === "string") {
@@ -153,39 +141,139 @@ function normalizeDeclaredPath(declared) {
153
141
  if (normalized === "." || normalized === ".." || normalized.startsWith("../")) return null;
154
142
  return normalized;
155
143
  }
156
- /**
157
- * Refuses a manifest whose declared entry points are not in the tarball.
158
- *
159
- * A path containing `*` is skipped: `exports` subpath patterns and `typesVersions` globs stand
160
- * for a set of files, and resolving them here would mean reimplementing npm's own matcher to
161
- * answer a question npm answers at install time.
162
- */
144
+ /** Node replaces every target star with the same subpath, including slashes. */
145
+ function matchesTarget(file, pattern) {
146
+ const parts = pattern.split("*");
147
+ const count = parts.length - 1;
148
+ if (count === 0) return file === pattern;
149
+ const size = (file.length - parts.reduce((sum, part) => sum + part.length, 0)) / count;
150
+ if (!Number.isInteger(size) || size < 0) return false;
151
+ const start = parts[0]?.length ?? 0;
152
+ return parts.join(file.slice(start, start + size)) === file;
153
+ }
154
+ /** Arrays skip invalid targets, but package-configuration errors must escape the fallback. */
155
+ var InvalidPackageTarget = class extends PublishCleanError {};
156
+ /** Export targets are URLs, unlike legacy main/bin paths; normalization must not hide invalid segments. */
157
+ function targetPath(target) {
158
+ if (!target.startsWith("./") || /%2f|%5c/i.test(target)) throw new InvalidPackageTarget(`Manifest declares invalid package paths: ${JSON.stringify(target)}`);
159
+ try {
160
+ if (decodeURIComponent(target.split(/[?#]/, 1)[0] ?? "").slice(2).split(/[\\/]/).some((segment) => [
161
+ ".",
162
+ "..",
163
+ "node_modules"
164
+ ].includes(segment.toLowerCase()))) throw new Error("Invalid target segment");
165
+ return decodeURIComponent(new URL(target, "file:///package/").pathname).slice(9);
166
+ } catch (cause) {
167
+ throw new InvalidPackageTarget(`Manifest declares invalid package paths: ${JSON.stringify(target)}`, { cause });
168
+ }
169
+ }
170
+ /** True selects a target, null blocks a condition, undefined leaves later conditions reachable. */
171
+ function collectTargets(value, imports, pattern, out) {
172
+ if (value === null) return null;
173
+ if (typeof value === "string") {
174
+ if (imports && !value.startsWith(".") && !value.startsWith("/")) return true;
175
+ out.push({
176
+ name: targetPath(value),
177
+ kind: "target",
178
+ pattern
179
+ });
180
+ return true;
181
+ }
182
+ if (Array.isArray(value)) {
183
+ if (value.length === 0) return null;
184
+ let invalid;
185
+ for (const item of value) try {
186
+ const result = collectTargets(item, imports, pattern, out);
187
+ if (result === true) return true;
188
+ if (result === null) invalid = null;
189
+ } catch (error) {
190
+ if (!(error instanceof InvalidPackageTarget)) throw error;
191
+ invalid = error;
192
+ }
193
+ if (invalid) throw invalid;
194
+ return invalid;
195
+ }
196
+ if (!isObject(value)) throw new InvalidPackageTarget("Invalid exports/imports target; expected a path, condition object, array or null.");
197
+ const conditions = Object.entries(value);
198
+ for (const [condition] of conditions) {
199
+ const number = Number(condition);
200
+ if (String(number) === condition && number >= 0 && number < 4294967295) throw new PublishCleanError(`Invalid export condition: ${JSON.stringify(condition)}.`);
201
+ }
202
+ for (const [condition, item] of conditions) {
203
+ const definite = collectTargets(item, imports, pattern, out);
204
+ if (condition === "default" && definite !== void 0) return definite;
205
+ }
206
+ }
207
+ function collectMap(value, imports, out) {
208
+ if (value === void 0 || value === null) return;
209
+ if (imports && !isObject(value)) throw new PublishCleanError("imports must be a subpath map.");
210
+ if (!(isObject(value) && (imports || Object.keys(value).some((key) => key.startsWith("."))))) {
211
+ collectTargets(value, imports, false, out);
212
+ return;
213
+ }
214
+ for (const [key, target] of Object.entries(value)) {
215
+ if (imports ? !key.startsWith("#") || key === "#" || key.startsWith("#/") : key !== "." && !key.startsWith("./")) throw new PublishCleanError(`Invalid exports/imports key: ${JSON.stringify(key)}.`);
216
+ collectTargets(target, imports, key.includes("*"), out);
217
+ }
218
+ }
219
+ /** A CommonJS main tries file extensions and index files, not a nested package's main. */
220
+ function mainExists(name, files) {
221
+ const file = (target) => [
222
+ "",
223
+ ".js",
224
+ ".json",
225
+ ".node"
226
+ ].some((ext) => files.has(target + ext));
227
+ if (file(name)) return true;
228
+ const prefix = name ? `${name}/` : "";
229
+ return [
230
+ ".js",
231
+ ".json",
232
+ ".node"
233
+ ].some((extension) => files.has(`${prefix}index${extension}`));
234
+ }
235
+ /** Validate declared files using each field's consumer semantics, without extracting the archive. */
163
236
  function assertDeclaredFiles(pkg, published) {
164
237
  const declared = [];
165
- for (const field of [
166
- "main",
167
- "module",
168
- "types",
169
- "typings",
170
- "bin"
171
- ]) collectDeclaredPaths(pkg[field], declared, "every-string");
172
- if (typeof pkg.browser === "string") collectDeclaredPaths(pkg.browser, declared, "every-string");
173
- else collectDeclaredPaths(pkg.browser, declared, "relative-only");
174
- for (const field of [
175
- "exports",
176
- "imports",
177
- "sideEffects"
178
- ]) collectDeclaredPaths(pkg[field], declared, "relative-only");
179
- collectDeclaredPaths(pkg.typesVersions, declared, "every-string");
180
- const resolved = declared.map((declaredPath) => ({
181
- path: declaredPath,
182
- normalized: normalizeDeclaredPath(declaredPath)
183
- }));
184
- const invalid = resolved.filter((item) => item.normalized === null);
185
- if (invalid.length > 0) throw new PublishCleanError(`Manifest declares invalid package paths:\n${invalid.map((item) => item.path).join("\n")}`);
186
- const shipped = new Set(published);
187
- const missing = resolved.filter((item) => !item.path.includes("*") && !shipped.has(String(item.normalized)));
188
- if (missing.length > 0) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((item) => item.path).join("\n")}`);
238
+ const collect = (value, kind, mode = "every-string", patterns = false) => {
239
+ const names = [];
240
+ collectDeclaredPaths(value, names, mode);
241
+ declared.push(...names.map((name) => ({
242
+ name,
243
+ kind,
244
+ pattern: patterns && name.includes("*")
245
+ })));
246
+ };
247
+ collect(pkg.main, "main");
248
+ for (const field of ["types", "typings"]) collect(pkg[field], "types");
249
+ collect(pkg.typesVersions, "types", "every-string", true);
250
+ for (const field of ["module", "bin"]) collect(pkg[field], "file");
251
+ collect(pkg.browser, "file", typeof pkg.browser === "string" ? "every-string" : "relative-only");
252
+ collect(pkg.sideEffects, "glob", "relative-only");
253
+ collectMap(pkg.exports, false, declared);
254
+ collectMap(pkg.imports, true, declared);
255
+ const files = new Set(published);
256
+ const missing = [];
257
+ for (const item of declared) {
258
+ if (item.kind === "glob" && /[*?[\]{}]/.test(item.name)) continue;
259
+ const name = item.kind === "main" && [
260
+ "",
261
+ ".",
262
+ "./"
263
+ ].includes(item.name) ? "" : normalizeDeclaredPath(item.name);
264
+ if (name === null) throw new PublishCleanError(`Manifest declares invalid package paths: ${JSON.stringify(item.name)}`);
265
+ let found = files.has(name);
266
+ if (!found && item.pattern) found = published.some((file) => matchesTarget(file, name));
267
+ else if (!found && item.kind === "main") found = mainExists(name.replace(/\/$/, ""), files);
268
+ else if (!found && item.kind === "types") found = [
269
+ ".d.ts",
270
+ ".d.mts",
271
+ ".d.cts",
272
+ "/index.d.ts"
273
+ ].some((suffix) => files.has(name + suffix));
274
+ if (!found) missing.push(item.name);
275
+ }
276
+ if (missing.length) throw new PublishCleanError(`Manifest declares files missing from packed artifact:\n${missing.map((name) => JSON.stringify(name)).join("\n")}`);
189
277
  }
190
278
 
191
279
  //#endregion
@@ -198,12 +286,7 @@ function assertDeclaredFiles(pkg, published) {
198
286
  * arguments a caller wrote after `--` straight into `npm publish`, so that vector is
199
287
  * attacker-shaped by design. Every spawn here passes an argument vector, never a command line.
200
288
  */
201
- /**
202
- * The probe below is bounded because a wedged shim would otherwise hang the publish with no
203
- * end: `execFileSync` blocks this thread, so no timer here could ever interrupt it. The bound
204
- * belongs on the spawn itself. It stays generous because the only job is to separate a tool
205
- * that answers from one that never will.
206
- */
289
+ /** Bound a hung version-manager shim without blocking the event loop. */
207
290
  const TOOL_PROBE_TIMEOUT_MS = 1e4;
208
291
  /**
209
292
  * Windows cannot launch `pnpm` or `npm` directly: both are `.cmd` shims there, and Node's own
@@ -219,8 +302,8 @@ const TOOL_PROBE_TIMEOUT_MS = 1e4;
219
302
  */
220
303
  function spawnArgs(command, args, platform) {
221
304
  if (platform !== "win32") return [command, [...args]];
222
- const unsafe = [command, ...args].filter((argument) => /[&|<>^%()]/.test(argument));
223
- 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.`);
305
+ const unsafe = [command, ...args].filter((argument) => /[&|<>^%()\r\n]/.test(argument));
306
+ if (unsafe.length > 0) throw new PublishCleanError(`On Windows these arguments cannot be passed safely, because cmd.exe would interpret them:\n${unsafe.map((argument) => JSON.stringify(argument)).join("\n")}\nUse arguments without & | < > ^ % ( ) or line breaks, or publish from Linux or macOS.`);
224
307
  return ["cmd.exe", [
225
308
  "/d",
226
309
  "/c",
@@ -228,74 +311,111 @@ function spawnArgs(command, args, platform) {
228
311
  ...args
229
312
  ]];
230
313
  }
231
- function run(command, args, cwd) {
232
- return execFileSync(...spawnArgs(command, args, process.platform), {
233
- cwd,
234
- encoding: "utf8",
235
- stdio: [
236
- "ignore",
237
- "pipe",
238
- "pipe"
239
- ]
240
- });
241
- }
242
- /**
243
- * Runs a command with its streams attached to this process instead of captured.
244
- *
245
- * Reserved for `npm publish`. Every other command here is run for its output or its
246
- * effect, but the publish is the one irreversible step, and npm's output is the only
247
- * receipt the operator gets: the version that went out, the tarball size, the integrity
248
- * hash, and the registry's own wording when it refuses. `run` would swallow all of it on
249
- * success and hold the failure text until the process exits, which in CI means a log
250
- * that says nothing about the one action that cannot be undone.
251
- */
252
- function runAttached(command, args, cwd) {
253
- execFileSync(...spawnArgs(command, args, process.platform), {
254
- cwd,
255
- stdio: [
256
- "ignore",
257
- "inherit",
258
- "inherit"
259
- ]
260
- });
261
- }
262
- /** Child output survives only on the thrown error, and is lost unless read off it here. */
263
- function outputFromError(error, key) {
264
- if (!isObject(error)) return "";
265
- const output = error[key];
266
- if (typeof output === "string") return output.trim();
267
- if (output instanceof Uint8Array) return Buffer.from(output).toString("utf8").trim();
268
- return "";
269
- }
270
- /**
271
- * A required tool can fail three ways, and each one asks something different of the
272
- * reader, so the probe reports what it observed instead of assuming the common case.
273
- * A version-manager shim (asdf, mise, volta, corepack) resolves in PATH and still refuses
274
- * to run when no version is pinned; calling that absence sends the reader to verify the
275
- * one thing already correct, and `which pnpm` then agrees with them and not with us. The
276
- * shim's own message names the fix, so it is forwarded rather than replaced.
277
- */
278
- function toolFailureReason(cause) {
279
- if (isObject(cause)) {
280
- if (cause.code === "ENOENT") return "is not available in PATH";
281
- if (cause.code === "ETIMEDOUT") return `did not answer --version within ${TOOL_PROBE_TIMEOUT_MS}ms`;
282
- }
283
- const stderr = outputFromError(cause, "stderr");
284
- return `failed to run${stderr ? `: ${stderr}` : ""}`;
285
- }
286
- function requireTool(name) {
287
- try {
288
- execFileSync(...spawnArgs(name, ["--version"], process.platform), {
289
- stdio: [
290
- "ignore",
314
+ /** Await child settlement before returning, so temporary files cannot be removed under a live packer. */
315
+ function run(command, args, cwd, options = {}) {
316
+ options.signal?.throwIfAborted();
317
+ const output = options.output ?? "capture";
318
+ const detached = process.platform !== "win32" && output !== "publish";
319
+ return new Promise((resolve, reject) => {
320
+ const invocation = output === "validator" ? [command, [...args]] : spawnArgs(command, args, process.platform);
321
+ const child = spawn(invocation[0], invocation[1], {
322
+ cwd,
323
+ detached,
324
+ stdio: output === "capture" || output === "validator" ? [
291
325
  "ignore",
326
+ "pipe",
292
327
  "pipe"
293
- ],
294
- timeout: TOOL_PROBE_TIMEOUT_MS
328
+ ] : output === "pack" ? [
329
+ "ignore",
330
+ process.stderr,
331
+ process.stderr
332
+ ] : "inherit"
295
333
  });
296
- } catch (cause) {
297
- throw new PublishCleanError(`Required tool "${name}" ${toolFailureReason(cause)}.`, { cause });
298
- }
334
+ let stdout = "";
335
+ let stderr = "";
336
+ let failure;
337
+ let escalation;
338
+ let stopping = false;
339
+ let termination;
340
+ const killGroup = (signal) => {
341
+ try {
342
+ if (child.pid !== void 0) {
343
+ if (detached) process.kill(-child.pid, signal);
344
+ else child.kill(signal);
345
+ }
346
+ } catch (error) {
347
+ if (!isObject(error) || error.code !== "ESRCH") failure = error instanceof Error ? error : new Error(String(error));
348
+ }
349
+ };
350
+ const stop = () => {
351
+ if (stopping || child.pid === void 0) return;
352
+ stopping = true;
353
+ if (process.platform === "win32") termination = new Promise((done) => {
354
+ const killer = spawn("taskkill", [
355
+ "/pid",
356
+ String(child.pid),
357
+ "/t",
358
+ "/f"
359
+ ], { stdio: "ignore" });
360
+ killer.on("error", (error) => {
361
+ failure = error;
362
+ child.kill();
363
+ });
364
+ killer.once("close", (status) => {
365
+ if (status !== 0 && !failure) failure = new PublishCleanError("Unable to terminate the child process tree.");
366
+ done();
367
+ });
368
+ });
369
+ else {
370
+ killGroup("SIGTERM");
371
+ escalation = setTimeout(() => killGroup("SIGKILL"), 1e3);
372
+ escalation.unref();
373
+ }
374
+ };
375
+ const timer = options.timeout === void 0 ? void 0 : setTimeout(() => {
376
+ failure = new PublishCleanError(`${command} did not finish within ${options.timeout}ms.`);
377
+ stop();
378
+ }, options.timeout);
379
+ const collect = (chunk, stream) => {
380
+ if (stream === "stdout") stdout += chunk.toString();
381
+ else stderr += chunk.toString();
382
+ if (stdout.length + stderr.length > 1048576) {
383
+ failure = new PublishCleanError(`${command} exceeded the captured output limit.`);
384
+ stdout = stdout.slice(-4096);
385
+ stderr = stderr.slice(-4096);
386
+ stop();
387
+ }
388
+ };
389
+ child.stdout?.on("data", (chunk) => collect(chunk, "stdout"));
390
+ child.stderr?.on("data", (chunk) => collect(chunk, "stderr"));
391
+ child.on("error", (error) => {
392
+ failure = error;
393
+ });
394
+ options.signal?.addEventListener("abort", stop, { once: true });
395
+ child.once("close", async (status, signal) => {
396
+ if (stopping && process.platform !== "win32") killGroup("SIGKILL");
397
+ await termination;
398
+ clearTimeout(timer);
399
+ clearTimeout(escalation);
400
+ options.signal?.removeEventListener("abort", stop);
401
+ if (options.signal?.aborted) {
402
+ reject(options.signal.reason);
403
+ return;
404
+ }
405
+ if (failure || status !== 0) {
406
+ const reason = failure && isObject(failure) && failure.code === "ENOENT" ? "is not available in PATH" : failure?.message ?? `exited with ${signal ?? status}`;
407
+ reject(new PublishCleanError(`${command} ${reason}${stderr.trim() ? `: ${stderr.trim()}` : ""}${output === "validator" && stdout.trim() ? `\n${stdout.trim()}` : ""}`, { cause: failure }));
408
+ } else resolve(stdout);
409
+ });
410
+ if (options.signal?.aborted) stop();
411
+ });
412
+ }
413
+ /** Probe in the package directory: version-manager shims resolve their toolchain from cwd. */
414
+ async function requireTool(name, cwd, signal) {
415
+ return (await run(name, ["--version"], cwd, {
416
+ signal,
417
+ timeout: TOOL_PROBE_TIMEOUT_MS
418
+ })).trim();
299
419
  }
300
420
 
301
421
  //#endregion
@@ -375,6 +495,17 @@ const MONOREPO_PROTOCOLS = [
375
495
  * platform gating, so `devFields` is not allowed to name them.
376
496
  */
377
497
  const RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
498
+ "config",
499
+ "deno",
500
+ "directories",
501
+ "jsdelivr",
502
+ "man",
503
+ "react-native",
504
+ "sass",
505
+ "style",
506
+ "styleModule",
507
+ "svelte",
508
+ "unpkg",
378
509
  ...DEP_FIELDS,
379
510
  "bin",
380
511
  "browser",
@@ -399,39 +530,20 @@ const RUNTIME_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
399
530
  "typings",
400
531
  "version"
401
532
  ]);
402
- /**
403
- * Fields npm's registry, website and CLI read, plus the de-facto entry points bundlers
404
- * and CDNs look for. Recognised, so they raise no report, but a maintainer may legitimately
405
- * strip any of them through `devFields`: none is load-bearing for an install.
406
- *
407
- * Together with RUNTIME_MANIFEST_FIELDS this is the answer to "does anything downstream
408
- * read this key?". Anything outside both sets is, as far as this tool can tell, project
409
- * bookkeeping that a consumer downloads and never uses.
410
- */
533
+ /** Registry metadata is recognised; consumer-resolved fields are protected separately. */
411
534
  const REGISTRY_MANIFEST_FIELDS = /* @__PURE__ */ new Set([
412
535
  "author",
413
536
  "bugs",
414
- "config",
415
537
  "contributors",
416
- "deno",
417
538
  "description",
418
- "directories",
419
539
  "funding",
420
540
  "gitHead",
421
541
  "homepage",
422
- "jsdelivr",
423
542
  "keywords",
424
543
  "maintainers",
425
- "man",
426
544
  "preferGlobal",
427
- "react-native",
428
545
  "repository",
429
- "sass",
430
- "scripts",
431
- "style",
432
- "styleModule",
433
- "svelte",
434
- "unpkg"
546
+ "scripts"
435
547
  ]);
436
548
  /**
437
549
  * Shown when another package manager started this tool, so the pnpm requirement is not a
@@ -448,13 +560,29 @@ function stripManifest(pkg, extraDevFields) {
448
560
  for (const field of [...DEV_FIELDS, ...extraDevFields]) delete stripped[field];
449
561
  const scripts = isObject(pkg.scripts) ? pkg.scripts : null;
450
562
  if (scripts) {
451
- const kept = {};
452
- for (const [name, value] of Object.entries(scripts)) if (CONSUMER_SCRIPTS.has(name) && typeof value === "string") kept[name] = value;
453
- if (Object.keys(kept).length > 0) stripped.scripts = kept;
563
+ if (Object.entries(scripts).some(([name, value]) => CONSUMER_SCRIPTS.has(name) && typeof value === "string")) stripped.scripts = scripts;
454
564
  else delete stripped.scripts;
455
565
  }
456
566
  return stripped;
457
567
  }
568
+ /** npm gives a scope registry priority over the general registry setting. */
569
+ function packageScope(pkg) {
570
+ if (typeof pkg.name !== "string" || !pkg.name.startsWith("@")) return null;
571
+ const slash = pkg.name.indexOf("/");
572
+ return slash > 1 ? pkg.name.slice(0, slash) : null;
573
+ }
574
+ /** A misspelled registry must fail locally rather than fall back to a public destination. */
575
+ function assertRegistry(value) {
576
+ if (typeof value !== "string" || !URL.canParse(value)) throw new PublishCleanError("Registry must be an absolute HTTP(S) URL.");
577
+ const url = new URL(value);
578
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new PublishCleanError("Registry must be an absolute HTTP(S) URL.");
579
+ if (url.username || url.password) throw new PublishCleanError("Registry URLs must not contain credentials. Configure npm authentication separately.");
580
+ }
581
+ /** Check every registry destination in the artifact without disclosing its credentials. */
582
+ function assertRegistryDestinations(pkg) {
583
+ if (!isObject(pkg.publishConfig)) return;
584
+ for (const [key, value] of Object.entries(pkg.publishConfig)) if (key === "registry" || key.endsWith(":registry")) assertRegistry(value);
585
+ }
458
586
  /**
459
587
  * Pins the published manifest to a registry, when one was chosen.
460
588
  *
@@ -468,8 +596,11 @@ function stripManifest(pkg, extraDevFields) {
468
596
  */
469
597
  function withRegistry(pkg, registry) {
470
598
  if (registry === null) return pkg;
599
+ assertRegistry(registry);
471
600
  const publishConfig = isObject(pkg.publishConfig) ? { ...pkg.publishConfig } : {};
472
601
  publishConfig.registry = registry;
602
+ const scope = packageScope(pkg);
603
+ if (scope) publishConfig[`${scope}:registry`] = registry;
473
604
  return {
474
605
  ...pkg,
475
606
  publishConfig
@@ -488,9 +619,8 @@ function withRegistry(pkg, registry) {
488
619
  * introduced while rewriting the archive is caught as well as one introduced by stripping.
489
620
  *
490
621
  * `devFields` entries are exempt: removing those was the request. `scripts` is exempt
491
- * because it is rewritten rather than removed, down to the install lifecycle hooks a
492
- * consumer runs, and a package whose scripts are all developer-only correctly ends up with
493
- * none.
622
+ * because its entire block survives when consumer lifecycle hooks exist, and otherwise
623
+ * the development-only block is removed.
494
624
  */
495
625
  function assertNoLostConsumerFields(sourcePkg, finalPkg, removedOnRequest) {
496
626
  const expected = /* @__PURE__ */ new Set([
@@ -520,7 +650,9 @@ function unrecognizedFieldsReport(pkg, kept) {
520
650
  const acknowledged = new Set(kept);
521
651
  const unrecognized = Object.keys(pkg).filter((field) => !RUNTIME_MANIFEST_FIELDS.has(field) && !REGISTRY_MANIFEST_FIELDS.has(field) && !acknowledged.has(field));
522
652
  if (unrecognized.length === 0) return null;
523
- return `publish-clean: these manifest fields are not recognised and were published as-is:\n${unrecognized.map((field) => ` ${field}`).join("\n")}\nStrip the ones consumers do not read, and acknowledge the ones they do:\n "publish-clean": { "devFields": [${unrecognized.map((f) => `"${f}"`).join(", ")}] }\n "publish-clean": { "keepFields": [${unrecognized.map((f) => `"${f}"`).join(", ")}] }`;
653
+ const quoted = unrecognized.map((field) => JSON.stringify(field));
654
+ const list = quoted.join(", ");
655
+ return `publish-clean: these manifest fields are not recognised and are retained as-is:\n ${quoted.join("\n ")}\nStrip the ones consumers do not read, and acknowledge the ones they do:\n "publish-clean": { "devFields": [${list}] }\n "publish-clean": { "keepFields": [${list}] }`;
524
656
  }
525
657
  /**
526
658
  * Refuses a manifest that still carries a spec only a workspace can resolve. Published
@@ -531,14 +663,23 @@ function unrecognizedFieldsReport(pkg, kept) {
531
663
  * absent by construction. They are still checked, because a guard whose correctness depends on
532
664
  * the order it happens to be called in fails silently the day someone reorders it.
533
665
  */
534
- function assertNoMonorepoProtocols(pkg) {
666
+ function assertNoMonorepoProtocols(pkg, files = []) {
535
667
  const failures = [];
668
+ const shipped = new Set(files);
536
669
  for (const field of DEP_FIELDS) {
537
670
  const map = pkg[field];
538
671
  if (!isObject(map)) continue;
539
672
  for (const [name, spec] of Object.entries(map)) {
540
673
  if (typeof spec !== "string") continue;
541
- if (MONOREPO_PROTOCOLS.some((prefix) => spec.includes(prefix))) failures.push(`${field}.${name}: ${spec}`);
674
+ const resolved = spec.startsWith("npm:") ? spec.slice(spec.lastIndexOf("@") + 1) : spec;
675
+ if (MONOREPO_PROTOCOLS.some((prefix) => resolved.startsWith(prefix))) failures.push(`${field}.${name}: ${spec}`);
676
+ if (/^(?:file:|git\+file:|\.{1,2}(?:[\\/]|$)|\/|~[\\/]|[a-z]:[\\/])/i.test(spec)) {
677
+ let local = null;
678
+ try {
679
+ local = normalizeDeclaredPath(decodeURIComponent(spec.replace(/^file:/i, "")));
680
+ } catch {}
681
+ if (!local || /[\\]/.test(local) || /^(?:git\+file:|~[\\/]|(?:file:)?[a-z]:[\\/])/i.test(spec) || !(/\.(?:tgz|tar\.gz|tar)$/.test(local) && shipped.has(local) || shipped.has(`${local}/package.json`))) failures.push(`${field}.${name}: ${spec} (local target is not in the artifact)`);
682
+ }
542
683
  }
543
684
  }
544
685
  if (failures.length > 0) throw new PublishCleanError(`Packed manifest contains unresolved monorepo-only dependency specs:\n${failures.join("\n")}\n${PUBLISH_ADVISORY}`);
@@ -548,8 +689,11 @@ function assertPublicPackage(pkg) {
548
689
  }
549
690
  function assertFilesField(pkg, skip) {
550
691
  if (skip) return;
551
- if (!Array.isArray(pkg.files) || pkg.files.length === 0) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array.");
692
+ if (!Array.isArray(pkg.files) || pkg.files.length === 0 || pkg.files.some((file) => typeof file !== "string" || !file.trim())) throw new PublishCleanError("Package manifest must define a non-empty \"files\" array of non-empty strings.");
552
693
  }
694
+
695
+ //#endregion
696
+ //#region src/config.ts
553
697
  /**
554
698
  * Every key this tool reads out of the manifest's `publish-clean` block. Naming them is what
555
699
  * makes a typo an error instead of a silent no-op — and a silent no-op here is not cosmetic:
@@ -561,13 +705,27 @@ const CONFIG_KEYS = /* @__PURE__ */ new Set([
561
705
  "keepFields",
562
706
  "noGitChecks",
563
707
  "registry",
564
- "skipFileCheck"
708
+ "skipFileCheck",
709
+ "validateArtifact"
565
710
  ]);
566
711
  function packageConfig(pkg) {
567
712
  const config = pkg["publish-clean"];
568
- if (!isObject(config)) return {};
713
+ if (config === void 0) return {};
714
+ if (!isObject(config)) throw new PublishCleanError("\"publish-clean\" must be an object.");
569
715
  const unknown = Object.keys(config).filter((key) => !CONFIG_KEYS.has(key));
570
716
  if (unknown.length > 0) throw new PublishCleanError(`Unknown "publish-clean" manifest options:\n${unknown.join("\n")}\nValid options: ${[...CONFIG_KEYS].join(", ")}`);
717
+ for (const key of [
718
+ "allowSuspicious",
719
+ "noGitChecks",
720
+ "skipFileCheck"
721
+ ]) if (config[key] !== void 0 && typeof config[key] !== "boolean") throw new PublishCleanError(`publish-clean.${key} must be a boolean.`);
722
+ if (config.registry !== void 0) assertRegistry(config.registry);
723
+ stringList(config, "devFields");
724
+ stringList(config, "keepFields");
725
+ if (config.validateArtifact !== void 0) {
726
+ const argv = stringList(config, "validateArtifact");
727
+ if (!argv[0]?.trim() || argv.some((argument) => argument.includes("\0"))) throw new PublishCleanError("publish-clean.validateArtifact must contain an executable followed by optional arguments, without NUL bytes.");
728
+ }
571
729
  return config;
572
730
  }
573
731
  /**
@@ -606,63 +764,173 @@ function keptFields(config) {
606
764
  }
607
765
 
608
766
  //#endregion
609
- //#region src/tarball.ts
767
+ //#region src/options.ts
768
+ const PUBLISH_OPTIONS = /* @__PURE__ */ new Map([
769
+ ["access", "string"],
770
+ ["tag", "string"],
771
+ ["otp", "string"],
772
+ ["registry", "string"],
773
+ ["provenance-file", "string"],
774
+ ["provenance", "boolean"],
775
+ ["dry-run", "boolean"],
776
+ ["ignore-scripts", "boolean"],
777
+ ["json", "boolean"],
778
+ ["loglevel", "string"]
779
+ ]);
780
+ /** npm reparses even equals-form values as flags; reject flag-shaped values before forwarding. */
781
+ function publicationArgs(args) {
782
+ const result = [];
783
+ for (let index = 0; index < args.length; index++) {
784
+ const arg = args[index] ?? "";
785
+ const equal = arg.indexOf("=");
786
+ const flag = equal < 0 ? arg : arg.slice(0, equal);
787
+ const negative = flag.startsWith("--no-");
788
+ const name = flag.slice(negative ? 5 : 2);
789
+ const type = flag.startsWith("--") ? PUBLISH_OPTIONS.get(name) : void 0;
790
+ if (!type || negative && type !== "boolean") throw new PublishCleanError(`After --, use publication options only: ${[...PUBLISH_OPTIONS.keys()].join(", ")}. Package operands and workspace selectors are forbidden.`);
791
+ let value = equal < 0 ? void 0 : arg.slice(equal + 1);
792
+ if (value === void 0 && (type === "string" || args[index + 1] === "true" || args[index + 1] === "false")) value = args[++index];
793
+ if (type === "boolean") {
794
+ value ??= "true";
795
+ if (value !== "true" && value !== "false") throw new PublishCleanError(`--${name} requires true or false.`);
796
+ if (negative) value = value === "true" ? "false" : "true";
797
+ } else if (!value || value.startsWith("-")) throw new PublishCleanError(`--${name} requires a value that does not start with -. Use ./ for a filename starting with -.`);
798
+ if (name === "registry") assertRegistry(value);
799
+ result.push(`--${name}=${value}`);
800
+ }
801
+ return result;
802
+ }
610
803
  /**
611
- * Reads and rewrites a packed npm tarball. The only place this tool decodes or authors
612
- * archive bytes, and the only reader every guard consults.
613
- *
614
- * The pipeline packs once, with pnpm, because that packer decides the file set. Cleaning the
615
- * manifest by unpacking and packing again hands that decision to a second packer, which
616
- * re-derives it from the very field being cleaned and silently disagrees; rewriting the one
617
- * member that changed keeps the first packer's selection, and its normalisation (uid/gid 0,
618
- * a fixed mtime, mode 644) that a naive `tar` invocation leaks the build machine's identity
619
- * into.
620
- *
621
- * Every entry other than the manifest is copied as opaque bytes and never decoded, so entry
622
- * shapes this code does not model — pax extended headers, ustar prefix splitting — survive
623
- * untouched. Only walking is universal: an entry's length is always its header block plus its
624
- * size rounded up to a block, whatever the type.
625
- *
626
- * Reading here rather than through the `tar` binary is what makes the whole tool depend on
627
- * nothing but Node: one archive is decompressed once and answers every question about it
628
- * (file list, manifest bytes, rewrite), instead of one spawn and one decompression per
629
- * question. It is also the stricter reader — `tar tzf` prints one name per line, so a path
630
- * containing a newline arrives as two entries there and as itself here.
804
+ * The whole interface in one screen, because this is where an out-of-context reader lands:
805
+ * the flags, the manifest config block that sets the same policies durably, and the `--`
806
+ * convention that decides which arguments this tool reads and which npm does. Anything a
807
+ * user must know to publish correctly belongs here, not only in the README, which is not
808
+ * installed next to the binary.
631
809
  */
810
+ const HELP = `publish-clean [options] [package-dir] [-- npm publish args]
811
+
812
+ Packs with pnpm, strips developer-only fields from the packed manifest, validates the
813
+ artifact, and publishes that exact tarball with npm. Arguments after \`--\` go to
814
+ \`npm publish\` as publication options (e.g. --access public --tag next --provenance).
815
+ Allowed: ${[...PUBLISH_OPTIONS.keys()].map((name) => `--${name}`).join(", ")}.
816
+ Additional package operands and workspace selectors are rejected.
817
+
818
+ Options:
819
+ --dry-run Pack, clean and validate; print the file list and manifest, publish nothing.
820
+ --guard-only Validate a preview artifact; no file-list output or publish.
821
+ --tarball-out DIR Also write the validated tarball into DIR, for attestation or release upload.
822
+ --registry URL Publish to URL, and record it in the artifact's publishConfig.
823
+ --no-git-checks Publish from a working tree with uncommitted changes.
824
+ --skip-file-check Allow a manifest with no "files" array.
825
+ --allow-suspicious Allow tests, CI config, lockfiles or tsconfig in the published artifact.
826
+ -h, --help Show this help.
827
+ -v, --version Show the publish-clean version.
828
+
829
+ Manifest configuration, under a "publish-clean" key in package.json:
830
+ validateArtifact string[] Executable and arguments; appends the final tarball path in every mode.
831
+ devFields string[] Extra fields to strip. Refused for fields consumers resolve.
832
+ keepFields string[] Fields to acknowledge, so they stop being reported as unrecognised.
833
+ registry string Default for --registry.
834
+ noGitChecks boolean Default for --no-git-checks.
835
+ skipFileCheck boolean Default for --skip-file-check.
836
+ allowSuspicious boolean Default for --allow-suspicious.
837
+
838
+ Preview modes do not test registry access, credentials or provenance eligibility.
839
+ Requires pnpm and npm on PATH. npm provenance additionally requires Node.js 22.14+ and
840
+ npm 11.5.1+, and only a cloud CI runner can produce it.`;
841
+ function parseOptions(rawArgs) {
842
+ const separator = rawArgs.indexOf("--");
843
+ const cliArgs = separator === -1 ? rawArgs : rawArgs.slice(0, separator);
844
+ const publishArgs = publicationArgs(separator === -1 ? [] : rawArgs.slice(separator + 1));
845
+ return {
846
+ ...parseArgs({
847
+ args: cliArgs,
848
+ allowPositionals: true,
849
+ options: {
850
+ "allow-suspicious": {
851
+ type: "boolean",
852
+ default: false
853
+ },
854
+ "dry-run": {
855
+ type: "boolean",
856
+ default: false
857
+ },
858
+ "guard-only": {
859
+ type: "boolean",
860
+ default: false
861
+ },
862
+ help: {
863
+ type: "boolean",
864
+ short: "h",
865
+ default: false
866
+ },
867
+ "no-git-checks": {
868
+ type: "boolean",
869
+ default: false
870
+ },
871
+ registry: {
872
+ type: "string",
873
+ default: void 0
874
+ },
875
+ "skip-file-check": {
876
+ type: "boolean",
877
+ default: false
878
+ },
879
+ "tarball-out": {
880
+ type: "string",
881
+ default: void 0
882
+ },
883
+ version: {
884
+ type: "boolean",
885
+ short: "v",
886
+ default: false
887
+ }
888
+ },
889
+ strict: true
890
+ }),
891
+ publishArgs
892
+ };
893
+ }
894
+
895
+ //#endregion
896
+ //#region src/tarball.ts
897
+ /** Read effective archive paths and rewrite only the manifest, preserving every other raw entry. */
632
898
  const BLOCK = 512;
633
899
  const NAME_LEN = 100;
634
900
  const SIZE_OFFSET = 124;
635
901
  const CHECKSUM_OFFSET = 148;
636
902
  const TYPE_OFFSET = 156;
637
- /**
638
- * The manifest is always at this exact path, and at 20 characters it can never be the entry
639
- * that needs a pax header or a prefix split — so the one entry this code must identify is
640
- * also the one whose name is guaranteed to be readable straight from the header block.
641
- */
642
903
  const MANIFEST_PATH = "package/package.json";
643
- /** Extended (`x`) and global (`g`) pax headers carry key/value overrides for other entries. */
644
904
  const PAX_TYPES = /* @__PURE__ */ new Set(["x", "g"]);
645
- /** Tar's flag for a directory entry. Directories are not files a consumer imports. */
646
905
  const DIRECTORY_TYPE = "5";
647
- /**
648
- * GNU's long-name entry, whose payload is the real path of the entry that follows it while
649
- * that entry's own header reads `././@LongLink`.
650
- *
651
- * Refused for the same reason a pax `path=` override is: it renames the following entry, so it
652
- * can point at `package/package.json` and the archive then extracts a manifest no guard here
653
- * ever saw. pnpm emits pax and never this, so refusing costs nothing and closes the second way
654
- * to rename an entry onto the one path this tool authors. `K` (long *link* name) is left alone:
655
- * it renames a symlink target, which cannot collide with an entry path.
656
- */
657
- const GNU_LONG_NAME = "L";
906
+ const UTF8 = new TextDecoder("utf-8", { fatal: true });
658
907
  function field(block, offset, length) {
659
- return block.toString("utf8", offset, offset + length).replace(/\0.*/s, "");
908
+ const bytes = block.subarray(offset, offset + length);
909
+ const nul = bytes.indexOf(0);
910
+ return UTF8.decode(nul < 0 ? bytes : bytes.subarray(0, nul));
660
911
  }
661
912
  function entrySize(block) {
662
- if ((block[SIZE_OFFSET] ?? 0) & 128) throw new PublishCleanError("Tarball uses base-256 entry sizes, which this tool cannot rewrite.");
663
- const size = Number.parseInt(field(block, SIZE_OFFSET, 12).trim(), 8);
664
- if (!Number.isFinite(size) || size < 0) throw new PublishCleanError("Tarball entry has an unreadable size field.");
665
- return size;
913
+ const value = field(block, SIZE_OFFSET, 12).trim();
914
+ if (!/^[0-7]+$/.test(value)) throw new PublishCleanError("Tarball entry has an unreadable size field.");
915
+ return Number.parseInt(value, 8);
916
+ }
917
+ /** PAX lengths count bytes, including their own digits; values may contain newlines. */
918
+ function paxFields(payload) {
919
+ const fields = /* @__PURE__ */ new Map();
920
+ for (let offset = 0; offset < payload.length;) {
921
+ const space = payload.indexOf(32, offset);
922
+ const digits = payload.toString("ascii", offset, space < 0 ? offset : space);
923
+ const length = Number(digits);
924
+ const end = offset + length;
925
+ const equals = payload.indexOf(61, space + 1);
926
+ if (!/^[1-9][0-9]*$/.test(digits) || !Number.isSafeInteger(length) || end > payload.length || equals <= space + 1 || equals >= end - 1 || payload[end - 1] !== 10) throw new PublishCleanError("Tarball has a malformed PAX record.");
927
+ const key = UTF8.decode(payload.subarray(space + 1, equals));
928
+ const value = UTF8.decode(payload.subarray(equals + 1, end - 1));
929
+ if (key.includes("sparse") || key === "hdrcharset") throw new PublishCleanError(`Tarball uses unsupported PAX ${key}.`);
930
+ fields.set(key, value);
931
+ offset = end;
932
+ }
933
+ return fields;
666
934
  }
667
935
  /**
668
936
  * Verifies a header block against the checksum tar stores inside it.
@@ -689,17 +957,6 @@ function assertChecksum(header, name) {
689
957
  }
690
958
  if (stored !== unsigned && stored !== signed) throw new PublishCleanError(`Tarball entry ${name} has a corrupt header checksum.`);
691
959
  }
692
- /**
693
- * Rejects a pax header that renames another entry onto the manifest path.
694
- *
695
- * Without this the archive could extract a `package.json` that no check ever saw: the guards
696
- * validate the entry rewritten here, while an extractor honours the pax override and writes
697
- * a different one over it. The header's own name field is `PaxHeader`, so nothing about the
698
- * substitution is visible from the walk alone.
699
- */
700
- function assertNoManifestOverride(payload) {
701
- for (const record of payload.toString("utf8").split("\n")) if (/^\d+ path=/.test(record) && record.slice(record.indexOf("=") + 1) === MANIFEST_PATH) throw new PublishCleanError(`Tarball contains a pax header renaming an entry to ${MANIFEST_PATH}.`);
702
- }
703
960
  /** Rebuilds a header for a changed payload size, keeping every other field of the original. */
704
961
  function reheader(original, size) {
705
962
  const header = Buffer.from(original);
@@ -723,26 +980,55 @@ function reheader(original, size) {
723
980
  function readArchive(gzipped) {
724
981
  const tar = gunzipSync(gzipped);
725
982
  const entries = [];
983
+ const names = /* @__PURE__ */ new Set();
984
+ let local = null;
726
985
  let tail = null;
727
986
  for (let offset = 0; offset < tar.length;) {
728
987
  const header = tar.subarray(offset, offset + BLOCK);
729
988
  if (header.length < BLOCK) throw new PublishCleanError("Tarball ends mid-header; the archive is truncated.");
730
- const name = field(header, 0, NAME_LEN);
731
- if (name === "") {
989
+ if (header.every((byte) => byte === 0)) {
732
990
  tail = tar.subarray(offset);
991
+ if (tail.length < BLOCK * 2 || tail.length % BLOCK || tail.some((byte) => byte !== 0)) throw new PublishCleanError("Tarball has an invalid end-of-archive marker.");
733
992
  break;
734
993
  }
735
- assertChecksum(header, name);
736
- const size = entrySize(header);
737
- const end = offset + BLOCK + BLOCK * Math.ceil(size / BLOCK);
738
- if (end > tar.length) throw new PublishCleanError(`Tarball entry ${name} runs past the end of the archive.`);
739
994
  const type = field(header, TYPE_OFFSET, 1);
995
+ const rawName = [field(header, 257, 6) === "ustar" ? field(header, 345, 155) : "", field(header, 0, NAME_LEN)].filter(Boolean).join("/");
996
+ assertChecksum(header, rawName);
997
+ const extended = PAX_TYPES.has(type);
998
+ const name = extended ? rawName : local?.get("path") || rawName;
999
+ let size = entrySize(header);
1000
+ const sizeOverride = !extended && local?.get("size");
1001
+ if (sizeOverride) {
1002
+ if (!/^[0-9]+$/.test(sizeOverride) || !Number.isSafeInteger(Number(sizeOverride))) throw new PublishCleanError("Tarball has an invalid PAX size.");
1003
+ size = Number(sizeOverride);
1004
+ }
1005
+ const end = offset + BLOCK + BLOCK * Math.ceil(size / BLOCK);
1006
+ if (!Number.isSafeInteger(end) || end > tar.length) throw new PublishCleanError(`Tarball entry ${JSON.stringify(name)} runs past the end of the archive.`);
740
1007
  const body = tar.subarray(offset + BLOCK, offset + BLOCK + size);
741
- if (type === GNU_LONG_NAME) throw new PublishCleanError("Tarball uses GNU long-name entries, which this tool refuses.");
742
- if (PAX_TYPES.has(type)) assertNoManifestOverride(body);
743
- if (name === MANIFEST_PATH) {
744
- if (type !== "0" && type !== "") throw new PublishCleanError(`${MANIFEST_PATH} is not a regular file in the tarball.`);
745
- if (entries.some((entry) => entry.name === MANIFEST_PATH)) throw new PublishCleanError(`Tarball contains ${MANIFEST_PATH} more than once.`);
1008
+ if (type === "L") throw new PublishCleanError("Tarball uses GNU long-name entries, which this tool refuses.");
1009
+ if (extended) {
1010
+ const fields = paxFields(body);
1011
+ if (fields.get("path") === MANIFEST_PATH) throw new PublishCleanError(`Tarball contains a pax header renaming an entry to ${MANIFEST_PATH}.`);
1012
+ if (type === "g") {
1013
+ if ([
1014
+ "path",
1015
+ "size",
1016
+ "linkpath"
1017
+ ].some((key) => fields.has(key))) throw new PublishCleanError("Tarball has a global PAX path, linkpath or size override.");
1018
+ } else {
1019
+ if (local) throw new PublishCleanError("Tarball has consecutive PAX extended headers.");
1020
+ local = fields;
1021
+ }
1022
+ } else {
1023
+ if (name === MANIFEST_PATH) {
1024
+ if (type !== "0" && type !== "") throw new PublishCleanError(`${MANIFEST_PATH} is not a regular file in the tarball.`);
1025
+ if (sizeOverride) throw new PublishCleanError("Tarball manifest has a PAX size override that cannot survive rewriting.");
1026
+ }
1027
+ const parts = name.replace(/\/$/, "").split("/");
1028
+ if (parts[0] !== "package" || parts.some((part) => !part || part === "." || part === "..") || name.includes("\\") || name.includes("\0")) throw new PublishCleanError(`Tarball has an unsafe entry path: ${JSON.stringify(name)}.`);
1029
+ if (names.has(name)) throw new PublishCleanError(`Tarball contains ${JSON.stringify(name)} more than once.`);
1030
+ names.add(name);
1031
+ local = null;
746
1032
  }
747
1033
  entries.push({
748
1034
  name,
@@ -754,11 +1040,20 @@ function readArchive(gzipped) {
754
1040
  offset = end;
755
1041
  }
756
1042
  if (tail === null) throw new PublishCleanError("Tarball has no end-of-archive marker; the archive is truncated.");
1043
+ if (local) throw new PublishCleanError("Tarball ends with an unused PAX extended header.");
757
1044
  return {
758
1045
  entries,
759
1046
  tail
760
1047
  };
761
1048
  }
1049
+ /** Check the final readback against the packed bytes, including entry order and metadata. */
1050
+ function assertPreservedArchive(before, after) {
1051
+ if (before.entries.length !== after.entries.length || !before.tail.equals(after.tail)) throw new PublishCleanError("Rewriting the manifest changed the archive structure.");
1052
+ for (const [index, original] of before.entries.entries()) {
1053
+ const result = after.entries[index];
1054
+ if (!result || original.name !== result.name || original.type !== result.type || (original.name === MANIFEST_PATH && !PAX_TYPES.has(original.type) ? !reheader(original.header, result.body.length).equals(result.header) : !original.raw.equals(result.raw))) throw new PublishCleanError(`Rewriting the manifest changed archive entry ${JSON.stringify(original.name)}.`);
1055
+ }
1056
+ }
762
1057
  /**
763
1058
  * The paths a consumer's installer writes, with the `package/` prefix stripped — the list every
764
1059
  * content guard judges. Directories and pax headers are dropped: neither is a file anyone
@@ -768,7 +1063,7 @@ function packageFiles(archive) {
768
1063
  return archive.entries.filter((entry) => entry.type !== DIRECTORY_TYPE && !PAX_TYPES.has(entry.type)).map((entry) => entry.name.startsWith("package/") ? entry.name.slice(8) : entry.name).filter((name) => name.length > 0 && !name.endsWith("/")).sort();
769
1064
  }
770
1065
  function manifestEntry(archive) {
771
- const entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH);
1066
+ const entry = archive.entries.find((candidate) => candidate.name === MANIFEST_PATH && !PAX_TYPES.has(candidate.type));
772
1067
  if (!entry) throw new PublishCleanError(`Tarball does not contain ${MANIFEST_PATH}.`);
773
1068
  return entry;
774
1069
  }
@@ -801,8 +1096,8 @@ function replaceManifest(archive, manifest) {
801
1096
  * The floors npm's trusted publishing puts on the toolchain, each formatted into its own error
802
1097
  * message so the version a reader is told to install is the version the comparison made.
803
1098
  *
804
- * The Node floor is also the package's declared `engines.node`, since a publisher that cannot
805
- * produce provenance cannot do this tool's job; a test asserts the two agree.
1099
+ * These floors apply to trusted publication; ordinary token-based publication can use the
1100
+ * lower Node floor declared by engines.node.
806
1101
  */
807
1102
  const MIN_TRUSTED_NPM_VERSION = [
808
1103
  11,
@@ -826,9 +1121,12 @@ function isAtLeast(actual, minimum) {
826
1121
  return true;
827
1122
  }
828
1123
  function wantsTrustedPublish(pkg, publishArgs, env) {
829
- if (publishArgs.includes("--provenance")) return true;
830
- if (isObject(pkg.publishConfig) && pkg.publishConfig.provenance === true) return true;
831
- return env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL === "string";
1124
+ if (env.GITHUB_ACTIONS === "true" && typeof env.ACTIONS_ID_TOKEN_REQUEST_URL === "string") return true;
1125
+ for (let index = publishArgs.length - 1; index >= 0; index--) {
1126
+ if (publishArgs[index] === "--provenance=true" || publishArgs[index] === "--provenance") return true;
1127
+ if (publishArgs[index] === "--provenance=false") return false;
1128
+ }
1129
+ if (isObject(pkg.publishConfig) && pkg.publishConfig.provenance !== void 0) return Boolean(pkg.publishConfig.provenance);
832
1130
  }
833
1131
  function repositoryUrl(pkg) {
834
1132
  if (typeof pkg.repository === "string") return pkg.repository;
@@ -850,8 +1148,7 @@ function githubRepositorySlug(url) {
850
1148
  return null;
851
1149
  }
852
1150
  }
853
- function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
854
- if (!wantsTrustedPublish(pkg, publishArgs, env)) return;
1151
+ function assertRepositoryForTrustedPublish(pkg, env) {
855
1152
  if (env.GITHUB_ACTIONS !== "true" || typeof env.GITHUB_REPOSITORY !== "string") return;
856
1153
  const repoUrl = repositoryUrl(pkg);
857
1154
  if (!repoUrl) throw new PublishCleanError("GitHub trusted publishing requires package.json repository.url to match GITHUB_REPOSITORY.");
@@ -861,40 +1158,6 @@ function assertRepositoryForTrustedPublish(pkg, publishArgs, env) {
861
1158
  //#endregion
862
1159
  //#region src/cli.ts
863
1160
  /**
864
- * The whole interface in one screen, because this is where an out-of-context reader lands:
865
- * the flags, the manifest config block that sets the same policies durably, and the `--`
866
- * convention that decides which arguments this tool reads and which npm does. Anything a
867
- * user must know to publish correctly belongs here, not only in the README, which is not
868
- * installed next to the binary.
869
- */
870
- const HELP = `publish-clean [options] [package-dir] [-- npm publish args]
871
-
872
- Packs with pnpm, strips developer-only fields from the packed manifest, validates the
873
- artifact, and publishes that exact tarball with npm. Arguments after \`--\` go to
874
- \`npm publish\` untouched (e.g. --access public --tag next --provenance).
875
-
876
- Options:
877
- --dry-run Pack, clean and validate; print the file list and manifest, publish nothing.
878
- --guard-only Same checks, no output and no publish. For a pre-publish gate.
879
- --tarball-out DIR Also write the validated tarball into DIR, for attestation or release upload.
880
- --registry URL Publish to URL, and record it in the artifact's publishConfig.
881
- --no-git-checks Publish from a working tree with uncommitted changes.
882
- --skip-file-check Allow a manifest with no "files" array.
883
- --allow-suspicious Allow tests, CI config, lockfiles or tsconfig in the published artifact.
884
- -h, --help Show this help.
885
- -v, --version Show the publish-clean version.
886
-
887
- Manifest configuration, under a "publish-clean" key in package.json:
888
- devFields string[] Extra fields to strip. Refused for fields consumers resolve.
889
- keepFields string[] Fields to acknowledge, so they stop being reported as unrecognised.
890
- registry string Default for --registry.
891
- noGitChecks boolean Default for --no-git-checks.
892
- skipFileCheck boolean Default for --skip-file-check.
893
- allowSuspicious boolean Default for --allow-suspicious.
894
-
895
- Requires pnpm and npm on PATH. npm provenance additionally requires Node.js 22.14+ and
896
- npm 11.5.1+, and only a cloud CI runner can produce it.`;
897
- /**
898
1161
  * Read from the installed manifest rather than baked in at build time, so the number cannot
899
1162
  * drift from the package a user actually has — which is the only reason anyone asks a tool
900
1163
  * for its version.
@@ -923,8 +1186,8 @@ function readJson(file) {
923
1186
  * is a compatibility claim (1.3.14 reports 24.3.0) about a runtime that never runs npm at all,
924
1187
  * so reading it would answer a question nobody asked while looking exactly like a check.
925
1188
  */
926
- function toolVersion(command) {
927
- const raw = run(command, ["--version"], process.cwd()).trim().replace(/^v/, "");
1189
+ function toolVersion(command, version) {
1190
+ const raw = version.trim().replace(/^v/, "");
928
1191
  const parts = raw.split(".").map((part) => Number.parseInt(part, 10));
929
1192
  if (parts.length < 3 || parts.some((part) => Number.isNaN(part))) throw new PublishCleanError(`Unable to parse ${command} version: ${raw}`);
930
1193
  return [
@@ -945,11 +1208,10 @@ function publishEnv() {
945
1208
  GITHUB_REPOSITORY: process.env.GITHUB_REPOSITORY
946
1209
  };
947
1210
  }
948
- function assertTrustedPublishingRuntime(pkg, publishArgs) {
949
- if (!wantsTrustedPublish(pkg, publishArgs, publishEnv())) return;
950
- const npm = toolVersion("npm");
1211
+ async function assertTrustedPublishingRuntime(cwd, npmVersion, signal) {
1212
+ const npm = toolVersion("npm", npmVersion);
951
1213
  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(".")}.`);
952
- const node = toolVersion("node");
1214
+ const node = toolVersion("node", await requireTool("node", cwd, signal));
953
1215
  if (isAtLeast(node, MIN_TRUSTED_NODE_VERSION)) return;
954
1216
  throw new PublishCleanError(`Trusted npm publishing requires Node.js ${MIN_TRUSTED_NODE_VERSION.join(".")} or newer; found ${node.join(".")}.`);
955
1217
  }
@@ -958,21 +1220,15 @@ function warnIfNonPnpmLifecycle() {
958
1220
  if (!userAgent || userAgent.startsWith("pnpm/")) return;
959
1221
  console.warn(`${PUBLISH_ADVISORY} Detected lifecycle user agent: ${userAgent}`);
960
1222
  }
961
- function assertCleanGit(packageDir, skip) {
1223
+ async function assertCleanGit(packageDir, skip, signal) {
962
1224
  if (skip) return;
963
- try {
964
- const output = run("git", [
965
- "status",
966
- "--porcelain",
967
- "--",
968
- "."
969
- ], packageDir).trim();
970
- if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
971
- } catch (error) {
972
- if (error instanceof PublishCleanError) throw error;
973
- const stderr = outputFromError(error, "stderr");
974
- throw new PublishCleanError(`Unable to verify source git status${stderr ? `: ${stderr}` : ""}.\nPass --no-git-checks to publish without this check.`, { cause: error });
975
- }
1225
+ const output = (await run("git", [
1226
+ "status",
1227
+ "--porcelain",
1228
+ "--",
1229
+ "."
1230
+ ], packageDir, { signal })).trim();
1231
+ if (output) throw new PublishCleanError(`Source package has uncommitted changes:\n${output}`);
976
1232
  }
977
1233
  /**
978
1234
  * Reads an archive from disk, so every judgement is made about bytes that exist as a file
@@ -1011,12 +1267,10 @@ async function soleTarball(packRoot) {
1011
1267
  if (tarballs.length !== 1 || !tarball) throw new PublishCleanError(`pnpm pack left ${tarballs.length} tarballs in ${packRoot}; expected exactly one.`);
1012
1268
  return path.join(packRoot, tarball);
1013
1269
  }
1014
- async function packAndClean(packageDir, opts) {
1015
- requireTool("pnpm");
1016
- requireTool("npm");
1270
+ async function packAndClean(packageDir, signal, opts) {
1271
+ const [, npmVersion] = await Promise.all([requireTool("pnpm", packageDir, signal), requireTool("npm", packageDir, signal)]);
1017
1272
  warnIfNonPnpmLifecycle();
1018
1273
  const sourcePkg = readJson(path.join(packageDir, "package.json"));
1019
- if (!opts.guardOnly && !opts.dryRun) assertTrustedPublishingRuntime(sourcePkg, opts.publishArgs);
1020
1274
  const config = packageConfig(sourcePkg);
1021
1275
  const skipFileCheck = opts.skipFileCheck || config.skipFileCheck === true;
1022
1276
  const allowSuspicious = opts.allowSuspicious || config.allowSuspicious === true;
@@ -1025,33 +1279,49 @@ async function packAndClean(packageDir, opts) {
1025
1279
  const extraDevFields = customDevFields(config);
1026
1280
  const keepFields = keptFields(config);
1027
1281
  assertPublicPackage(sourcePkg);
1028
- assertCleanGit(packageDir, noGitChecks);
1282
+ await assertCleanGit(packageDir, noGitChecks, signal);
1029
1283
  assertFilesField(sourcePkg, skipFileCheck);
1030
1284
  const root = await mkdtemp(path.join(tmpdir(), "publish-clean-"));
1031
1285
  try {
1032
- run("pnpm", [
1286
+ await run("pnpm", [
1033
1287
  "pack",
1034
1288
  "--pack-destination",
1035
1289
  root
1036
- ], packageDir);
1037
- const tarball = await soleTarball(root);
1038
- const packed = await readTarball(tarball);
1039
- const cleanedPkg = withRegistry(stripManifest(manifestOf(packed, "the packed tarball"), extraDevFields), registry);
1290
+ ], packageDir, {
1291
+ signal,
1292
+ output: "pack"
1293
+ });
1294
+ const finalTarball = await soleTarball(root);
1295
+ const packed = await readTarball(finalTarball);
1296
+ const packedPkg = manifestOf(packed, "the packed tarball");
1297
+ assertPublicPackage(packedPkg);
1298
+ const cleanedPkg = withRegistry(stripManifest(packedPkg, extraDevFields), registry);
1299
+ const cleanedText = stringifyJson(cleanedPkg);
1040
1300
  const unrecognized = unrecognizedFieldsReport(cleanedPkg, keepFields);
1041
1301
  if (unrecognized) console.warn(unrecognized);
1042
- const publishRoot = path.join(root, "publish");
1043
- await mkdir(publishRoot);
1044
- const finalTarball = path.join(publishRoot, path.basename(tarball));
1045
- await writeFile(finalTarball, replaceManifest(packed, stringifyJson(cleanedPkg)));
1046
- const published = await readTarball(finalTarball);
1302
+ await writeFile(finalTarball, replaceManifest(packed, cleanedText));
1303
+ const finalBytes = await readFile(finalTarball);
1304
+ const published = readArchive(finalBytes);
1047
1305
  const finalFiles = packageFiles(published);
1048
1306
  assertSameEntries(packageFiles(packed), finalFiles);
1307
+ assertPreservedArchive(packed, published);
1049
1308
  validatePackedFiles(finalFiles, allowSuspicious);
1050
- assertDeclaredFiles(cleanedPkg, finalFiles);
1051
1309
  const shippedPkg = manifestOf(published, "the published tarball");
1052
- assertNoMonorepoProtocols(shippedPkg);
1053
- assertNoLostConsumerFields(sourcePkg, shippedPkg, extraDevFields);
1054
- if (stableJson(shippedPkg) !== stableJson(cleanedPkg)) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
1310
+ assertRegistryDestinations(shippedPkg);
1311
+ assertDeclaredFiles(shippedPkg, finalFiles);
1312
+ assertNoMonorepoProtocols(shippedPkg, finalFiles);
1313
+ assertNoLostConsumerFields(packedPkg, shippedPkg, extraDevFields);
1314
+ if (manifestText(published) !== cleanedText) throw new PublishCleanError("Rewritten tarball manifest differs from the cleaned manifest.");
1315
+ const validator = config.validateArtifact;
1316
+ if (validator) try {
1317
+ await run(validator[0], [...validator.slice(1), finalTarball], packageDir, {
1318
+ signal,
1319
+ output: "validator"
1320
+ });
1321
+ if (!finalBytes.equals(await readFile(finalTarball))) throw new PublishCleanError("The validator changed the tarball. Validators must be read-only.");
1322
+ } catch (cause) {
1323
+ throw new PublishCleanError("publish-clean.validateArtifact failed; no tarball was retained or published.", { cause });
1324
+ }
1055
1325
  if (opts.tarballOut !== null) {
1056
1326
  await mkdir(opts.tarballOut, { recursive: true });
1057
1327
  const kept = path.join(opts.tarballOut, path.basename(finalTarball));
@@ -1060,24 +1330,43 @@ async function packAndClean(packageDir, opts) {
1060
1330
  }
1061
1331
  if (opts.dryRun) {
1062
1332
  console.log(`[dry-run] ${finalFiles.length} files:`);
1063
- for (const file of finalFiles) console.log(` ${file}`);
1064
- console.log(`[dry-run] cleaned package.json:\n${stringifyJson(cleanedPkg)}`);
1333
+ for (const file of finalFiles) console.log(` ${JSON.stringify(file)}`);
1334
+ console.log(`[dry-run] cleaned package.json:\n${cleanedText}`);
1065
1335
  return;
1066
1336
  }
1067
1337
  if (opts.guardOnly) return;
1068
- assertRepositoryForTrustedPublish(cleanedPkg, opts.publishArgs, publishEnv());
1069
- const publishArgs = registry ? [
1070
- "publish",
1071
- finalTarball,
1072
- "--registry",
1073
- registry,
1074
- ...opts.publishArgs
1075
- ] : [
1338
+ const env = publishEnv();
1339
+ let trusted = wantsTrustedPublish(shippedPkg, opts.publishArgs, env);
1340
+ if (trusted === void 0) {
1341
+ const value = (await run("npm", [
1342
+ "config",
1343
+ "get",
1344
+ "provenance"
1345
+ ], packageDir, {
1346
+ signal,
1347
+ timeout: 1e4
1348
+ })).trim();
1349
+ if (value !== "true" && value !== "false") throw new PublishCleanError("npm config get provenance must return true or false.");
1350
+ trusted = value === "true";
1351
+ }
1352
+ if (trusted) {
1353
+ await assertTrustedPublishingRuntime(packageDir, npmVersion, signal);
1354
+ assertRepositoryForTrustedPublish(shippedPkg, env);
1355
+ }
1356
+ const scope = packageScope(shippedPkg);
1357
+ const publishArgs = [
1076
1358
  "publish",
1077
1359
  finalTarball,
1078
1360
  ...opts.publishArgs
1079
1361
  ];
1080
- runAttached("npm", publishArgs, packageDir);
1362
+ if (registry) {
1363
+ publishArgs.push("--registry", registry);
1364
+ if (scope) publishArgs.push(`--${scope}:registry=${registry}`);
1365
+ }
1366
+ await run("npm", publishArgs, packageDir, {
1367
+ signal,
1368
+ output: "publish"
1369
+ });
1081
1370
  } finally {
1082
1371
  await rm(root, {
1083
1372
  recursive: true,
@@ -1085,56 +1374,9 @@ async function packAndClean(packageDir, opts) {
1085
1374
  });
1086
1375
  }
1087
1376
  }
1088
- async function main() {
1089
- const rawArgs = process.argv.slice(2);
1090
- const separator = rawArgs.indexOf("--");
1091
- const cliArgs = separator === -1 ? rawArgs : rawArgs.slice(0, separator);
1092
- const publishArgs = separator === -1 ? [] : rawArgs.slice(separator + 1);
1093
- const parsed = parseArgs({
1094
- args: cliArgs,
1095
- allowPositionals: true,
1096
- options: {
1097
- "allow-suspicious": {
1098
- type: "boolean",
1099
- default: false
1100
- },
1101
- "dry-run": {
1102
- type: "boolean",
1103
- default: false
1104
- },
1105
- "guard-only": {
1106
- type: "boolean",
1107
- default: false
1108
- },
1109
- help: {
1110
- type: "boolean",
1111
- short: "h",
1112
- default: false
1113
- },
1114
- "no-git-checks": {
1115
- type: "boolean",
1116
- default: false
1117
- },
1118
- registry: {
1119
- type: "string",
1120
- default: void 0
1121
- },
1122
- "skip-file-check": {
1123
- type: "boolean",
1124
- default: false
1125
- },
1126
- "tarball-out": {
1127
- type: "string",
1128
- default: void 0
1129
- },
1130
- version: {
1131
- type: "boolean",
1132
- short: "v",
1133
- default: false
1134
- }
1135
- },
1136
- strict: true
1137
- });
1377
+ async function main(signal) {
1378
+ const parsed = parseOptions(process.argv.slice(2));
1379
+ const { publishArgs } = parsed;
1138
1380
  if (parsed.values.version) {
1139
1381
  console.log(ownVersion());
1140
1382
  return;
@@ -1144,7 +1386,7 @@ async function main() {
1144
1386
  return;
1145
1387
  }
1146
1388
  if (parsed.positionals.length > 1) throw new PublishCleanError(`Unexpected positional arguments before --:\n${parsed.positionals.slice(1).join("\n")}`);
1147
- await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), {
1389
+ await packAndClean(path.resolve(String(parsed.positionals[0] ?? ".")), signal, {
1148
1390
  allowSuspicious: parsed.values["allow-suspicious"] === true,
1149
1391
  dryRun: parsed.values["dry-run"] === true,
1150
1392
  guardOnly: parsed.values["guard-only"] === true,
@@ -1155,14 +1397,17 @@ async function main() {
1155
1397
  tarballOut: typeof parsed.values["tarball-out"] === "string" ? parsed.values["tarball-out"] : null
1156
1398
  });
1157
1399
  }
1158
- main().catch((error) => {
1159
- const details = [
1160
- error instanceof Error ? error.message : String(error),
1161
- outputFromError(error, "stdout"),
1162
- outputFromError(error, "stderr")
1163
- ].filter((detail) => detail.length > 0);
1164
- console.error(`publish-clean: ${details.join("\n")}`);
1165
- process.exitCode = 1;
1400
+ const cancellation = new AbortController();
1401
+ let interrupted = false;
1402
+ for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143]]) process.on(signal, () => {
1403
+ interrupted = true;
1404
+ process.exitCode = code;
1405
+ cancellation.abort(new PublishCleanError(`Cancelled by ${signal}.`));
1406
+ });
1407
+ main(cancellation.signal).catch((error) => {
1408
+ console.error("publish-clean:", error instanceof PublishCleanError ? error.message : error);
1409
+ if (error instanceof PublishCleanError && error.cause) console.error("Caused by:", error.cause);
1410
+ if (!interrupted) process.exitCode = 1;
1166
1411
  });
1167
1412
 
1168
1413
  //#endregion