bestzip 3.1.0 → 4.0.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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2018 Nathan Friedly - http://nfriedly.com/
3
+ Copyright (c) 2026 Nathan Friedly - http://nfriedly.com/
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -15,12 +15,16 @@ The native `zip` command on GNU/Linux and macOS is significantly faster and crea
15
15
 
16
16
  ## Global command line usage
17
17
 
18
- npm install -g bestzip
19
- bestzip --no-follow-sym-links destination.zip source/ [other sources...]
18
+ ```bash
19
+ npm install -g bestzip
20
+ bestzip --no-follow-sym-links destination.zip source/ [other sources...]
21
+ ```
20
22
 
21
23
  ## Command line usage within `package.json` scripts
22
24
 
23
- npm install --save-dev bestzip
25
+ ```bash
26
+ npm install --save-dev bestzip
27
+ ```
24
28
 
25
29
  package.json:
26
30
 
@@ -38,7 +42,7 @@ package.json:
38
42
 
39
43
  ## Command line options
40
44
 
41
- * `--follow-sym-links` / `--no-follow-sym-links`: Follow symbolic links and include their target contents in the archive (the default) or don't follow and instead include the link itself. Setting one flag or the other is recommended because the default will change in the next major version (v4.0.0). If symlinks are encountered when the flag is not set, a warning will be logged.
45
+ * `--follow-sym-links` / `--no-follow-sym-links`: Follow symbolic links and include their target contents in the archive, or don't follow and instead include the link itself (the default). If symlinks are encountered when the flag is not set, a warning will be logged.
42
46
  * `--level N` / `-N`: Level of compression, as with the native `zip` command. `N` must be an integer from 0 (store, no compression) to 9 (maximum compression). Defaults to each implementation's own default when unset.
43
47
  * `--force node|native`: Force the Node.js implementation or the native `zip` command instead of letting bestzip pick automatically.
44
48
 
@@ -46,18 +50,18 @@ package.json:
46
50
  ## Programmatic usage from within Node.js
47
51
 
48
52
  ```javascript
49
- import { zip } from 'bestzip';
50
- // const { zip } = require('bestzip'); // for CJS (requires node.js v22 or newer
53
+ import { bestZip } from 'bestzip';
54
+ // const { bestZip } = require('bestzip'); // for CJS (requires node.js v22 or newer
51
55
 
52
56
  // zip a single source
53
- await zip({
57
+ await bestZip({
54
58
  source: 'build/*',
55
59
  destination: './destination.zip',
56
60
  followSymLinks: false,
57
61
  })
58
62
 
59
63
  // zip multiple sources, starting in a different CWD (current working directory)
60
- await zip({
64
+ await bestZip({
61
65
  source: ['img1.jpg', 'img2.jpg', 'imgn.jpg'],
62
66
  destination: '../images.zip',
63
67
  cwd: './images/', // optional, defaults to process.cwd()
@@ -74,17 +78,7 @@ await zip({
74
78
  * `destination`: Path to generated .zip file.
75
79
  * `cwd`: Set the Current Working Directory that source and destination paths are relative to. Defaults to `process.cwd()`
76
80
  * `level`: Level of compression, as with the native `zip` command. An integer from 0 (store, no compression) to 9 (maximum compression). Defaults to each implementation's own default when unset.
77
- * `followSymLinks`: Follow symbolic links and include the contents of their targets in the zip file. When set to `true` or `false` the preference is honored and no warning is printed. When left unset, symbolic links are followed (the current default) and a warning is printed whenever symlinks are detected, because this default will change in v4 to store symlinks as links instead (see [Symbolic links](#symbolic-links)).
78
-
79
- ## Symbolic links
80
-
81
- By default, bestzip **follows** symbolic links — their target contents are included in the archive. When symlinks are present and the `followSymLinks` option has not been set explicitly, bestzip prints a warning to stderr listing the symlinked paths and how to opt in or out.
82
-
83
- **This default will change in v4** to store symlinks as link entries (not following them), which is the more secure behavior. To prepare for this, set `followSymLinks` explicitly in your code.
84
-
85
- To follow symlinks (the current default), set `followSymLinks: true` (programmatic API) or pass `--follow-sym-links` on the command line. To suppress the warning while keeping the current default, set `followSymLinks: true` explicitly. To store symlinks as links instead, set `followSymLinks: false` or pass `--no-follow-sym-links` on the command line.
86
-
87
- When storing symlinks as links, bestzip uses the native `zip` command when available. Some native `zip` builds (notably the Windows build of Info-ZIP) cannot store symlinks as link entries at all, so bestzip falls back to its built-in Node.js implementation in that case. Note that calling `bestzip.nativeZip` directly with `followSymLinks` unset/false on such a platform throws an error; use the `bestzip()` entry point, which routes to the Node.js implementation automatically. Use `bestzip.nativeZipSupportsSymlinks()` to check whether the available native `zip` can store symlinks as links; it returns `true`/`false` and caches its result after the first call. `bestzip.hasNativeZip()` checks whether a native `zip` is installed at all.
81
+ * `followSymLinks`: Follow symbolic links and include the contents of their targets in the zip file. When set to `true` or `false` the preference is honored and no warning is printed. When left unset, symbolic links are **not** followed and a warning is printed whenever symlinks are detected (see [Symbolic links](#symbolic-links)).
88
82
 
89
83
  ## How to control the directory structure
90
84
 
@@ -111,3 +105,14 @@ Wildcards (`*`) ignore dotfiles.
111
105
  * To include a dotfile, either include the directory it's in (`folder/`) or include it by name (`folder/.dotfile`)
112
106
  * To omit dotfiles, either use a wildcard (`folder/*`) or explicitly list the desired files (`folder/file1.txt folder/file2.txt`)
113
107
 
108
+ ## Symbolic links
109
+
110
+ Starting in v4, bestzip does **not** follow symbolic links by default. Symlinks are stored in the archive as link entries rather than as the contents of their targets. This prevents an archive from accidentally (or maliciously) capturing files from anywhere else on the filesystem that only happen to be reachable through a symlink inside the directory being archived.
111
+
112
+ When symlinks are present and the `followSymLinks` option has not been set explicitly, bestzip prints a warning to stderr listing the symlinked paths and how to opt in to following them.
113
+
114
+ To follow symlinks, set `followSymLinks: true` (programmatic API) or pass `--follow-sym-links` on the command line. To keep the link entries (the default behavior) while suppressing the warning, set `followSymLinks: false` or pass `--no-follow-sym-links` on the command line.
115
+
116
+ When archiving symlinks without following them, bestzip uses the native `zip` command when available. Some native `zip` builds (notably the Windows build of Info-ZIP) cannot store symlinks as link entries at all, so bestzip falls back to its built-in Node.js implementation in that case.
117
+
118
+ Note that calling `nativeZip()` directly with `followSymLinks` unset/false on such a platform throws an error; use the `bestZip()` entry point, which routes to the Node.js implementation automatically. Use `nativeZipSupportsSymlinks()` to check whether the available native `zip` can store symlinks as links; it returns `true`/`false` and caches its result after the first call. `bestzip.hasNativeZip()` checks whether a native `zip` is installed at all.
package/lib/bestzip.js CHANGED
@@ -6,13 +6,103 @@ import fs from "node:fs";
6
6
  import fsp from "node:fs/promises";
7
7
  import path from "node:path";
8
8
  import os from "node:os";
9
+ import { isDeepStrictEqual } from "node:util";
9
10
 
10
11
  import { ZipArchive } from "archiver";
11
12
  import { glob, hasMagic } from "glob";
12
- import which from "which";
13
+
14
+ // Directories where the system `zip` command is expected to live. Only these
15
+ // are ever consulted, so a file named `zip` anywhere else — committed into an
16
+ // archived directory, delivered through a relative/empty PATH element, or
17
+ // dropped into node_modules/.bin by a dependency — is never executed
18
+ // (CWE-426/CWE-427).
19
+ const DEFAULT_ZIP_DIRS = (() => {
20
+ if (process.platform === "win32") {
21
+ // note, some node.js environments, like MINGW64 (git-bash), report SystemRoot
22
+ // and ProgramFiles as uppercase, but they still support the version here
23
+ const systemRoot = process.env.SystemRoot || "C:\\Windows";
24
+ const programFiles = process.env.ProgramFiles || "C:\\Program Files";
25
+ const programFilesX86 =
26
+ process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
27
+ const localAppData = process.env.LOCALAPPDATA;
28
+ const userProfile = process.env.USERPROFILE;
29
+
30
+ const dirs = [
31
+ path.join(systemRoot, "System32"),
32
+ systemRoot,
33
+ "C:\\ProgramData\\chocolatey\\bin",
34
+ path.join(programFiles, "Git\\usr\\bin"),
35
+ path.join(programFilesX86, "Git\\usr\\bin"),
36
+ ];
37
+
38
+ if (localAppData) {
39
+ dirs.push(path.join(localAppData, "Microsoft\\WinGet\\Links"));
40
+ }
41
+ if (userProfile) {
42
+ dirs.push(path.join(userProfile, "scoop\\shims"));
43
+ }
44
+
45
+ return dirs;
46
+ }
47
+
48
+ return [
49
+ "/usr/bin",
50
+ "/bin",
51
+ "/usr/local/bin",
52
+ "/opt/homebrew/bin", // Homebrew on Apple Silicon
53
+ "/opt/local/bin", // MacPorts
54
+ "/snap/bin", // Linux Snap packages
55
+ "/nix/var/nix/profiles/default/bin", // Nix OS/Package Manager
56
+ ];
57
+ })();
58
+
59
+ const ZIP_EXECUTABLE_NAMES =
60
+ process.platform === "win32" ? ["zip.exe", "zip"] : ["zip"];
61
+
62
+ function isExecutableFile(file) {
63
+ try {
64
+ fs.accessSync(file, fs.constants.X_OK);
65
+ return fs.statSync(file).isFile();
66
+ } catch (e) {
67
+ return false;
68
+ }
69
+ }
70
+
71
+ function findInDir(dir, names) {
72
+ for (const name of names) {
73
+ const candidate = path.join(dir, name);
74
+ if (isExecutableFile(candidate)) {
75
+ return candidate;
76
+ }
77
+ }
78
+ return null;
79
+ }
80
+
81
+ // Resolves the native `zip` binary's absolute path, or null when none is
82
+ // usable (so callers fall back to the node implementation). PATH is never
83
+ // consulted: the child process chdirs into the (possibly untrusted) archive
84
+ // directory before running, so a bare command name could be shadowed by a
85
+ // `zip` planted there or in the dependency tree (CWE-426/CWE-427). Only the
86
+ // allowlisted system directories above are ever checked, and the resolved
87
+ // absolute path — never the bare `zip` name — is what gets spawned.
88
+ let nativeZipCommand;
89
+ function getNativeZipCommand() {
90
+ if (nativeZipCommand !== undefined) {
91
+ return nativeZipCommand;
92
+ }
93
+ nativeZipCommand = null;
94
+ for (const dir of DEFAULT_ZIP_DIRS) {
95
+ const found = findInDir(dir, ZIP_EXECUTABLE_NAMES);
96
+ if (found) {
97
+ nativeZipCommand = found;
98
+ break;
99
+ }
100
+ }
101
+ return nativeZipCommand;
102
+ }
13
103
 
14
104
  function hasNativeZip() {
15
- return Boolean(which.sync("zip", { nothrow: true }));
105
+ return Boolean(getNativeZipCommand());
16
106
  }
17
107
 
18
108
  let nativeSymlinkCapability;
@@ -25,6 +115,11 @@ function nativeZipSupportsSymlinks() {
25
115
  if (nativeSymlinkCapability !== undefined) {
26
116
  return nativeSymlinkCapability;
27
117
  }
118
+ const command = getNativeZipCommand();
119
+ if (!command) {
120
+ nativeSymlinkCapability = false;
121
+ return nativeSymlinkCapability;
122
+ }
28
123
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bestzip-symlink-check"));
29
124
  try {
30
125
  const file = path.join(dir, "file");
@@ -37,7 +132,7 @@ function nativeZipSupportsSymlinks() {
37
132
  return nativeSymlinkCapability;
38
133
  }
39
134
  const res = spawnSync(
40
- "zip",
135
+ command,
41
136
  ["-q", "--symlinks", "check.zip", "file", "link"],
42
137
  {
43
138
  cwd: dir,
@@ -123,6 +218,14 @@ function validateLevel(level) {
123
218
  }
124
219
  }
125
220
 
221
+ async function safeStat(path) {
222
+ try {
223
+ return await fsp.stat(path);
224
+ } catch (err) {
225
+ return null;
226
+ }
227
+ }
228
+
126
229
  async function detectSymlinks(cwd, sources) {
127
230
  const results = await Promise.all(
128
231
  sources.map(async (source) => {
@@ -151,11 +254,9 @@ function maybeWarnAboutSymlinks(options, symlinks, cwd) {
151
254
  lines.push(`...and ${symlinks.length - 3} more`);
152
255
  }
153
256
  console.warn(
154
- "Warning: Symbolic links are followed by default — their target contents are included in the archive.\n" +
155
- `To keep this behavior and prevent this warning, ${optIn}.\n` +
156
- `To store symlinks as links instead, ${optOut}.\n` +
157
- "This default will change in v4 to store symlinks as links. " +
158
- "Set followSymLinks explicitly to opt in to following.\n" +
257
+ "Warning: Symbolic links are stored as the link itself rather than the destination by default.\n" +
258
+ `To keep the default behavior and prevent this warning, ${optOut}.\n` +
259
+ `To follow symlinks and include their target contents, ${optIn}.\n` +
159
260
  "Detected symlinks:\n" +
160
261
  lines.join("\n")
161
262
  );
@@ -163,13 +264,23 @@ function maybeWarnAboutSymlinks(options, symlinks, cwd) {
163
264
 
164
265
  const nativeZip = async (options) => {
165
266
  const cwd = options.cwd || process.cwd();
166
- const command = "zip";
267
+ // Resolve the absolute path in the parent's context and pass that to the
268
+ // child. Resolving the bare `zip` name inside the spawned process would let
269
+ // the archive directory's contents shadow the real binary when PATH has a
270
+ // relative or empty element (CWE-426/CWE-427).
271
+ const command = getNativeZipCommand();
272
+ if (!command) {
273
+ throw new Error(
274
+ "The native zip command was not found at a trusted location on this system."
275
+ );
276
+ }
167
277
  const sources = await expandSources(cwd, options.source);
168
278
  const destination = path.resolve(cwd, options.destination);
169
279
  validateLevel(options.level);
170
- // followSymLinks: false opts into storing symlinks as links; the default
171
- // (unset or true) follows symlinks and is unchanged.
172
- const followSymLinks = options.followSymLinks !== false;
280
+ const destStatBefore = await safeStat(destination);
281
+ // followSymLinks: true opts into following symlinks (archiving their target
282
+ // contents); the default (unset or false) stores symlinks as links.
283
+ const followSymLinks = options.followSymLinks === true;
173
284
 
174
285
  if (!followSymLinks && !nativeZipSupportsSymlinks()) {
175
286
  // The native zip command cannot store symlinks as links on this platform
@@ -214,15 +325,36 @@ const nativeZip = async (options) => {
214
325
  cwd,
215
326
  });
216
327
  zipProcess.on("error", reject);
217
- zipProcess.on("close", (exitCode) => {
328
+ zipProcess.on("close", async (exitCode) => {
218
329
  if (exitCode === 0) {
219
- resolve();
330
+ // The native zip reported success. Make sure it actually wrote the
331
+ // archive — the zip exits 0 without creating or updating the
332
+ // destination, that's a silent no-op, not a real archive.
333
+ const destStatAfter = await safeStat(destination);
334
+ if (
335
+ destStatAfter &&
336
+ !isDeepStrictEqual(destStatBefore, destStatAfter)
337
+ ) {
338
+ resolve();
339
+ } else {
340
+ reject(
341
+ new Error(
342
+ `The native zip command exited 0 but did not ${
343
+ destStatBefore ? "update" : "create"
344
+ } the destination archive '${destination}'. This may indicate a broken or incompatible native zip command, or a filesystem issue. Consider using ${
345
+ options.viaCli ? "--force=node" : `{force: 'node'}`
346
+ }.\n Executed command: '${command} ${args.join(
347
+ " "
348
+ )}'\n Executed in directory: '${cwd}'`
349
+ )
350
+ );
351
+ }
220
352
  } else {
221
353
  reject(
222
354
  new Error(
223
- `Unexpected exit code from native zip: ${exitCode}\n executed command '${command} ${args.join(
355
+ `Unexpected exit code from native zip: ${exitCode}\n Executed command: '${command} ${args.join(
224
356
  " "
225
- )}'\n executed in directory '${cwd}'`
357
+ )}'\n Executed in directory '${cwd}'`
226
358
  )
227
359
  );
228
360
  }
@@ -237,9 +369,10 @@ const nativeZip = async (options) => {
237
369
  const nodeZip = async (options) => {
238
370
  const cwd = options.cwd || process.cwd();
239
371
  validateLevel(options.level);
240
- // followSymLinks: false stores symlinks as links; the default (unset or
241
- // true) follows symlinks, matching the native zip implementation.
242
- const followSymLinks = options.followSymLinks !== false;
372
+ // followSymLinks: true follows symlinks and archives their target contents;
373
+ // the default (unset or false) stores symlinks as links.
374
+ const followSymLinks = options.followSymLinks === true;
375
+ const trackSymLinks = typeof options.followSymLinks === "undefined";
243
376
  const symlinks = [];
244
377
  const outputFile = await fsp.open(
245
378
  path.resolve(cwd, options.destination),
@@ -270,49 +403,29 @@ const nodeZip = async (options) => {
270
403
  const fullPath = path.resolve(cwd, source);
271
404
  const destPath = source;
272
405
 
273
- if (!followSymLinks) {
274
- // Store symlinks as link entries (their targets, not their contents).
275
- const entries = await walkTree(fullPath, false);
276
- for (const entry of entries) {
277
- const subPath = entry.path.substring(fullPath.length);
278
- if (entry.stats.isSymbolicLink()) {
279
- symlinks.push(entry.path);
280
- archive.symlink(
281
- destPath + subPath,
282
- await fsp.readlink(entry.path),
283
- entry.stats.mode
284
- );
285
- } else {
286
- archive.file(entry.path, {
287
- name: destPath + subPath,
288
- stats: entry.stats,
289
- });
290
- }
291
- }
292
- return;
293
- }
294
-
295
- // Follow symlinks by default. Pass explicit (stat) stats so archiver
296
- // dereferences symlinks and stores their target contents rather than the
297
- // link itself, matching the native zip implementation.
298
- const entries = await walkTree(fullPath, true);
406
+ // Walk the source once in the requested mode: an lstat walk when storing
407
+ // links (symlinks are emitted as their own entries and stored as links),
408
+ // or a stat walk when following (symlinks are dereferenced and their
409
+ // target contents archived, matching the native zip implementation).
410
+ const entries = await walkTree(fullPath, followSymLinks);
299
411
  for (const entry of entries) {
300
412
  const archiveName = destPath + entry.path.substring(fullPath.length);
301
- archive.file(entry.path, {
302
- name: archiveName,
303
- stats: entry.stats,
304
- });
305
- }
306
-
307
- // Warn while following by default (followSymLinks unset): detect symlinks
308
- // via an lstat walk so the deprecation warning still fires even though the
309
- // archive stores their target contents.
310
- if (options.followSymLinks === undefined) {
311
- const detected = await walkTree(fullPath, false);
312
- for (const entry of detected) {
313
- if (entry.stats.isSymbolicLink()) {
413
+ if (entry.stats.isSymbolicLink()) {
414
+ // Storing a link: keep the raw link target and record it for the
415
+ // default warning (an explicit followSymLinks setting suppresses it).
416
+ if (trackSymLinks) {
314
417
  symlinks.push(entry.path);
315
418
  }
419
+ archive.symlink(
420
+ archiveName,
421
+ await fsp.readlink(entry.path),
422
+ entry.stats.mode
423
+ );
424
+ } else {
425
+ archive.file(entry.path, {
426
+ name: archiveName,
427
+ stats: entry.stats,
428
+ });
316
429
  }
317
430
  }
318
431
  }
@@ -338,13 +451,14 @@ function zip(options) {
338
451
  };
339
452
  }
340
453
 
341
- // The native zip command can store symlinks as links only when it supports
342
- // --symlinks. If followSymLinks is not explicitly false, it just follows
343
- // symlinks, which every native zip can do. When storing links is requested
344
- // but the native zip can't do it, fall back to the node implementation.
454
+ // By default symlinks are stored as links, not followed. The native zip
455
+ // command can always follow symlinks (followSymLinks: true), but can only
456
+ // store them as links when it supports --symlinks. When storing links is
457
+ // requested but the native zip can't do it, fall back to the node
458
+ // implementation, which can store links regardless.
345
459
  const useNative =
346
460
  hasNativeZip() &&
347
- (options.followSymLinks !== false || nativeZipSupportsSymlinks());
461
+ (options.followSymLinks === true || nativeZipSupportsSymlinks());
348
462
 
349
463
  let promise;
350
464
  if (useNative) {
@@ -362,4 +476,11 @@ function zip(options) {
362
476
 
363
477
  export default zip;
364
478
 
365
- export { zip, nodeZip, nativeZip, hasNativeZip, nativeZipSupportsSymlinks };
479
+ export {
480
+ zip,
481
+ zip as bestZip,
482
+ nodeZip,
483
+ nativeZip,
484
+ hasNativeZip,
485
+ nativeZipSupportsSymlinks,
486
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bestzip",
3
- "version": "3.1.0",
3
+ "version": "4.0.1",
4
4
  "description": "Uses OS zip command if available (for better performance and speed) or node.js version if there is no system command available. Can be called via node or command line.",
5
5
  "type": "module",
6
6
  "exports": "./lib/bestzip.js",
@@ -13,7 +13,7 @@
13
13
  "scripts": {
14
14
  "lint": "eslint .",
15
15
  "lint-fix": "eslint --fix .",
16
- "unit-test": "node --experimental-test-snapshots --test",
16
+ "unit-test": "node --experimental-test-snapshots --test \"test/**/*.test.js\"",
17
17
  "update-snapshot": "npm run unit-test -- --test-update-snapshots",
18
18
  "test": "npm run lint && npm run unit-test"
19
19
  },
@@ -31,7 +31,6 @@
31
31
  "dependencies": {
32
32
  "archiver": "^8.0.0",
33
33
  "glob": "^13.0.6",
34
- "which": "^6.0.1",
35
34
  "yargs": "^16.2.0"
36
35
  },
37
36
  "devDependencies": {