bestzip 4.0.1 → 4.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -75,7 +75,7 @@ await bestZip({
75
75
  ### API Options
76
76
 
77
77
  * `source`: Path or paths to files and folders to include in the zip file. String or Array of Strings.
78
- * `destination`: Path to generated .zip file.
78
+ * `destination`: Path to generated .zip file. bestzip excludes the destination from the archive, so it is safe to write it inside a folder that is also being zipped.
79
79
  * `cwd`: Set the Current Working Directory that source and destination paths are relative to. Defaults to `process.cwd()`
80
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.
81
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)).
package/bin/cli.js CHANGED
@@ -1,60 +1,4 @@
1
1
  #!/usr/bin/env node
2
+ import { main } from "../lib/cli.js";
2
3
 
3
- import * as bestzip from "../lib/bestzip.js";
4
-
5
- import yargs from "yargs";
6
- import { hideBin } from "yargs/helpers";
7
-
8
- // Rewrite -0 … -9 into --level 0 … --level 9 before yargs parses them
9
- const preprocessed = hideBin(process.argv).flatMap((arg) => {
10
- const match = /^-([0-9])$/.exec(arg);
11
- return match ? ["--level", match[1]] : [arg];
12
- });
13
-
14
- const argv = yargs(preprocessed)
15
- .usage("\nUsage: bestzip destination.zip sources/")
16
- .option("force", {
17
- describe: "Force use of node.js or native zip methods",
18
- choices: ["node", "native"],
19
- })
20
- .option("level", {
21
- describe: "Level of compression",
22
- type: "number",
23
- })
24
- .option("follow-sym-links", {
25
- describe:
26
- "Follow symbolic links and include their target contents in the archive",
27
- type: "boolean",
28
- })
29
- .demand(2).argv;
30
-
31
- const destination = argv._.shift();
32
- const source = argv._;
33
-
34
- console.log("Writing %s to %s...", source.join(", "), destination);
35
-
36
- let zip;
37
-
38
- if (argv.force === "node") {
39
- zip = bestzip.nodeZip;
40
- } else if (argv.force === "native") {
41
- zip = bestzip.nativeZip;
42
- } else {
43
- zip = bestzip.zip;
44
- }
45
-
46
- zip({
47
- source,
48
- destination,
49
- verbose: !!argv.verbose,
50
- level: argv.level,
51
- followSymLinks: argv.followSymLinks,
52
- viaCli: true,
53
- })
54
- .then(function () {
55
- console.log("zipped!");
56
- })
57
- .catch(function (err) {
58
- console.error(err);
59
- process.exit(1);
60
- });
4
+ main();
package/lib/bestzip.js CHANGED
@@ -1,446 +1,12 @@
1
1
  // creates a zip file using either the native `zip` command if available,
2
2
  // or a node.js zip implementation otherwise.
3
3
 
4
- import cp, { spawnSync } from "node:child_process";
5
- import fs from "node:fs";
6
- import fsp from "node:fs/promises";
7
- import path from "node:path";
8
- import os from "node:os";
9
- import { isDeepStrictEqual } from "node:util";
10
-
11
- import { ZipArchive } from "archiver";
12
- import { glob, hasMagic } from "glob";
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
- }
103
-
104
- function hasNativeZip() {
105
- return Boolean(getNativeZipCommand());
106
- }
107
-
108
- let nativeSymlinkCapability;
109
-
110
- // The native zip command needs the --symlinks flag to store symlinks as links
111
- // rather than following them. Not every build supports it (notably the
112
- // Windows build of Info-ZIP). This probes the installed zip for support, since
113
- // the version string isn't a reliable indicator.
114
- function nativeZipSupportsSymlinks() {
115
- if (nativeSymlinkCapability !== undefined) {
116
- return nativeSymlinkCapability;
117
- }
118
- const command = getNativeZipCommand();
119
- if (!command) {
120
- nativeSymlinkCapability = false;
121
- return nativeSymlinkCapability;
122
- }
123
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bestzip-symlink-check"));
124
- try {
125
- const file = path.join(dir, "file");
126
- const link = path.join(dir, "link");
127
- fs.writeFileSync(file, "bestzip symlink check");
128
- try {
129
- fs.symlinkSync("file", link);
130
- } catch (e) {
131
- nativeSymlinkCapability = false;
132
- return nativeSymlinkCapability;
133
- }
134
- const res = spawnSync(
135
- command,
136
- ["-q", "--symlinks", "check.zip", "file", "link"],
137
- {
138
- cwd: dir,
139
- encoding: "utf8",
140
- }
141
- );
142
- nativeSymlinkCapability = res.status === 0;
143
- } catch (e) {
144
- nativeSymlinkCapability = false;
145
- } finally {
146
- fs.rmSync(dir, { recursive: true, force: true });
147
- }
148
- return nativeSymlinkCapability;
149
- }
150
-
151
- async function expandSources(cwd, source) {
152
- // options to behave more like the native zip's glob support
153
- const globOpts = {
154
- cwd,
155
- dot: false, // ignore .dotfiles
156
- noglobstar: true, // treat ** as *
157
- noext: true, // no (a|b)
158
- nobrace: true, // no {a,b}
159
- };
160
-
161
- // first handle arrays
162
- if (Array.isArray(source)) {
163
- const results = await Promise.all(source.map((s) => expandSources(cwd, s)));
164
- return results.flat();
165
- }
166
-
167
- // then expand magic
168
- if (typeof source !== "string") {
169
- throw new Error(`source is (${typeof source}) `);
170
- }
171
-
172
- if (hasMagic(source, globOpts)) {
173
- // archiver uses this library but somehow ends up with different results on windows:
174
- // archiver.glob('*') will include subdirectories, but omit their contents on windows
175
- // so we'll use glob directly, and add all of the files it finds
176
- return await glob(source, globOpts);
177
- } else {
178
- // or just trigger the callback with the source string if there is no magic
179
- // always return an array
180
- return [source];
181
- }
182
- }
183
-
184
- async function walkTree(fullPath, followSymLinks) {
185
- let stats;
186
- if (followSymLinks) {
187
- stats = await fsp.stat(fullPath);
188
- } else {
189
- stats = await fsp.lstat(fullPath);
190
- }
191
- if (stats.isSymbolicLink() || !stats.isDirectory()) {
192
- return [{ path: fullPath, stats }];
193
- }
194
- const entries = await fsp.readdir(fullPath);
195
- const children = await Promise.all(
196
- entries.map((entry) => walkTree(path.join(fullPath, entry), followSymLinks))
197
- );
198
- return children.flat();
199
- }
200
-
201
- // Validates the compression level. A level of exactly 0-9 (an integer) is
202
- // accepted; anything else that is set causes an error. An unset level is
203
- // allowed and left to each implementation's default.
204
- function validateLevel(level) {
205
- if (typeof level === "undefined") {
206
- return;
207
- }
208
- if (
209
- typeof level !== "number" ||
210
- !Number.isInteger(level) ||
211
- level < 0 ||
212
- level > 9
213
- ) {
214
- const typehint = typeof level === "number" ? "" : ` (${typeof level})`;
215
- throw new Error(
216
- `bestzip: level should be an integer from 0 to 9, got ${level}${typehint}`
217
- );
218
- }
219
- }
220
-
221
- async function safeStat(path) {
222
- try {
223
- return await fsp.stat(path);
224
- } catch (err) {
225
- return null;
226
- }
227
- }
228
-
229
- async function detectSymlinks(cwd, sources) {
230
- const results = await Promise.all(
231
- sources.map(async (source) => {
232
- const fullPath = path.resolve(cwd, source);
233
- const entries = await walkTree(fullPath, false);
234
- return entries
235
- .filter((entry) => entry.stats.isSymbolicLink())
236
- .map((entry) => entry.path);
237
- })
238
- );
239
- return results.flat();
240
- }
241
-
242
- function maybeWarnAboutSymlinks(options, symlinks, cwd) {
243
- if (options.followSymLinks !== undefined || symlinks.length === 0) {
244
- return;
245
- }
246
- const cli = options.viaCli;
247
- const optIn = cli ? "pass --follow-sym-links" : "set followSymLinks: true";
248
- const optOut = cli
249
- ? "pass --no-follow-sym-links"
250
- : "set followSymLinks: false";
251
- let lines = symlinks.map((p) => path.relative(cwd, p));
252
- if (lines.length > 4) {
253
- lines = lines.slice(0, 3);
254
- lines.push(`...and ${symlinks.length - 3} more`);
255
- }
256
- console.warn(
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` +
260
- "Detected symlinks:\n" +
261
- lines.join("\n")
262
- );
263
- }
264
-
265
- const nativeZip = async (options) => {
266
- const cwd = options.cwd || process.cwd();
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
- }
277
- const sources = await expandSources(cwd, options.source);
278
- const destination = path.resolve(cwd, options.destination);
279
- validateLevel(options.level);
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;
284
-
285
- if (!followSymLinks && !nativeZipSupportsSymlinks()) {
286
- // The native zip command cannot store symlinks as links on this platform
287
- // (e.g. the Windows build of Info-ZIP). nodeZip can, so the bestzip()
288
- // entry point routes accordingly — but a direct nativeZip() call can't
289
- // fulfill this request.
290
- throw new Error(
291
- "The native zip command on this platform cannot store symlinks as links. Use the bestzip() entry point, which will select the node implementation, or set followSymLinks to true to follow symlinks instead."
292
- );
293
- }
294
-
295
- const args = ["--quiet", "--recurse-paths"];
296
- if (typeof options.level === "number") {
297
- args.push("-" + options.level.toString());
298
- }
299
- if (!followSymLinks) {
300
- args.push("--symlinks");
301
- }
302
- args.push(destination, "--", ...sources);
303
-
304
- // Scan for symlinks to warn about in parallel with the zip command. The
305
- // scan is best-effort: if it fails (e.g. it races the zip command touching
306
- // the same paths), log and fall back to no warning rather than aborting the
307
- // zip, and never let it reject before the zip process has completed.
308
- const warnScan = (async () => {
309
- if (options.followSymLinks !== undefined) {
310
- return [];
311
- }
312
- try {
313
- return await detectSymlinks(cwd, sources);
314
- } catch (err) {
315
- console.warn(
316
- `bestzip: failed to scan for symlinks to warn about: ${err.message}`
317
- );
318
- return [];
319
- }
320
- })();
321
-
322
- const zipPromise = new Promise((resolve, reject) => {
323
- const zipProcess = cp.spawn(command, args, {
324
- stdio: "inherit",
325
- cwd,
326
- });
327
- zipProcess.on("error", reject);
328
- zipProcess.on("close", async (exitCode) => {
329
- if (exitCode === 0) {
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
- }
352
- } else {
353
- reject(
354
- new Error(
355
- `Unexpected exit code from native zip: ${exitCode}\n Executed command: '${command} ${args.join(
356
- " "
357
- )}'\n Executed in directory '${cwd}'`
358
- )
359
- );
360
- }
361
- });
362
- });
363
-
364
- const [symlinks] = await Promise.all([warnScan, zipPromise]);
365
- maybeWarnAboutSymlinks(options, symlinks, cwd);
366
- };
367
-
368
- // based on http://stackoverflow.com/questions/15641243/need-to-zip-an-entire-directory-using-node-js/18775083#18775083
369
- const nodeZip = async (options) => {
370
- const cwd = options.cwd || process.cwd();
371
- validateLevel(options.level);
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";
376
- const symlinks = [];
377
- const outputFile = await fsp.open(
378
- path.resolve(cwd, options.destination),
379
- "w"
380
- );
381
- const output = outputFile.createWriteStream();
382
- const archive = new ZipArchive({
383
- zlib: { level: options.level },
384
- });
385
-
386
- output.on("close", async () => {
387
- await outputFile.close();
388
- resolvePromise();
389
- });
390
- archive.on("error", (err) => rejectPromise(err));
391
- archive.on("warning", (err) => console.warn(err && err.message));
392
-
393
- archive.pipe(output);
394
-
395
- let resolvePromise;
396
- let rejectPromise;
397
- const promise = new Promise((resolve, reject) => {
398
- resolvePromise = resolve;
399
- rejectPromise = reject;
400
- });
401
-
402
- async function addSource(source) {
403
- const fullPath = path.resolve(cwd, source);
404
- const destPath = source;
405
-
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);
411
- for (const entry of entries) {
412
- const archiveName = destPath + entry.path.substring(fullPath.length);
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) {
417
- symlinks.push(entry.path);
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
- });
429
- }
430
- }
431
- }
432
-
433
- try {
434
- const expandedSources = await expandSources(cwd, options.source);
435
- await Promise.all(expandedSources.map(addSource));
436
- maybeWarnAboutSymlinks(options, symlinks, cwd);
437
- archive.finalize();
438
- } catch (err) {
439
- rejectPromise(err);
440
- }
441
-
442
- return promise;
443
- };
4
+ import {
5
+ nativeZip,
6
+ hasNativeZip,
7
+ nativeZipSupportsSymlinks,
8
+ } from "./nativezip.js";
9
+ import { nodeZip } from "./nodezip.js";
444
10
 
445
11
  function zip(options) {
446
12
  const compatMode = typeof options === "string";
package/lib/cli.js ADDED
@@ -0,0 +1,66 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import process from "node:process";
3
+
4
+ import yargs from "yargs";
5
+ import { hideBin } from "yargs/helpers";
6
+
7
+ import * as bestzip from "../lib/bestzip.js";
8
+
9
+ export function main() {
10
+ // Rewrite -0 … -9 into --level 0 … --level 9 before yargs parses them
11
+ const preprocessed = hideBin(process.argv).flatMap((arg) => {
12
+ const match = /^-([0-9])$/.exec(arg);
13
+ return match ? ["--level", match[1]] : [arg];
14
+ });
15
+
16
+ const argv = yargs(preprocessed)
17
+ .usage("\nUsage: bestzip destination.zip sources/")
18
+ .option("force", {
19
+ describe: "Force use of node.js or native zip methods",
20
+ choices: ["node", "native"],
21
+ })
22
+ .option("level", {
23
+ describe: "Level of compression",
24
+ type: "number",
25
+ })
26
+ .option("follow-sym-links", {
27
+ describe:
28
+ "Follow symbolic links and include their target contents in the archive",
29
+ type: "boolean",
30
+ })
31
+ .demand(2).argv;
32
+
33
+ const destination = argv._.shift();
34
+ const source = argv._;
35
+
36
+ console.log("Writing %s to %s...", source.join(", "), destination);
37
+
38
+ let zip;
39
+
40
+ if (argv.force === "node") {
41
+ zip = bestzip.nodeZip;
42
+ } else if (argv.force === "native") {
43
+ zip = bestzip.nativeZip;
44
+ } else {
45
+ zip = bestzip.zip;
46
+ }
47
+
48
+ zip({
49
+ source,
50
+ destination,
51
+ level: argv.level,
52
+ followSymLinks: argv.followSymLinks,
53
+ viaCli: true,
54
+ })
55
+ .then(function () {
56
+ console.log("zipped!");
57
+ })
58
+ .catch(function (err) {
59
+ console.error(err);
60
+ process.exit(1);
61
+ });
62
+ }
63
+
64
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
65
+ main();
66
+ }
@@ -0,0 +1,82 @@
1
+ import fs from "node:fs";
2
+ import fsp from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { glob, hasMagic } from "glob";
6
+
7
+ export function isExecutableFile(file) {
8
+ try {
9
+ fs.accessSync(file, fs.constants.X_OK);
10
+ return fs.statSync(file).isFile();
11
+ } catch (e) {
12
+ return false;
13
+ }
14
+ }
15
+
16
+ export function findInDir(dir, names) {
17
+ for (const name of names) {
18
+ const candidate = path.join(dir, name);
19
+ if (isExecutableFile(candidate)) {
20
+ return candidate;
21
+ }
22
+ }
23
+ return null;
24
+ }
25
+
26
+ export async function expandSources(cwd, source) {
27
+ // options to behave more like the native zip's glob support
28
+ const globOpts = {
29
+ cwd,
30
+ dot: false, // ignore .dotfiles
31
+ noglobstar: true, // treat ** as *
32
+ noext: true, // no (a|b)
33
+ nobrace: true, // no {a,b}
34
+ };
35
+
36
+ // first handle arrays
37
+ if (Array.isArray(source)) {
38
+ const results = await Promise.all(source.map((s) => expandSources(cwd, s)));
39
+ return results.flat();
40
+ }
41
+
42
+ // then expand magic
43
+ if (typeof source !== "string") {
44
+ throw new Error(`source is (${typeof source}) `);
45
+ }
46
+
47
+ if (hasMagic(source, globOpts)) {
48
+ // archiver uses this library but somehow ends up with different results on windows:
49
+ // archiver.glob('*') will include subdirectories, but omit their contents on windows
50
+ // so we'll use glob directly, and add all of the files it finds
51
+ return await glob(source, globOpts);
52
+ } else {
53
+ // or just trigger the callback with the source string if there is no magic
54
+ // always return an array
55
+ return [source];
56
+ }
57
+ }
58
+
59
+ export async function walkTree(fullPath, followSymLinks) {
60
+ let stats;
61
+ if (followSymLinks) {
62
+ stats = await fsp.stat(fullPath);
63
+ } else {
64
+ stats = await fsp.lstat(fullPath);
65
+ }
66
+ if (stats.isSymbolicLink() || !stats.isDirectory()) {
67
+ return [{ path: fullPath, stats }];
68
+ }
69
+ const entries = await fsp.readdir(fullPath);
70
+ const children = await Promise.all(
71
+ entries.map((entry) => walkTree(path.join(fullPath, entry), followSymLinks))
72
+ );
73
+ return [{ path: fullPath, stats }, ...children.flat()];
74
+ }
75
+
76
+ export async function safeStat(path) {
77
+ try {
78
+ return await fsp.stat(path);
79
+ } catch (err) {
80
+ return null;
81
+ }
82
+ }
@@ -0,0 +1,234 @@
1
+ import process from "node:process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import cp, { spawnSync } from "node:child_process";
5
+ import os from "node:os";
6
+ import { isDeepStrictEqual } from "node:util";
7
+
8
+ import { expandSources, findInDir, safeStat } from "./fs-utils.js";
9
+ import {
10
+ detectSymlinks,
11
+ maybeWarnAboutSymlinks,
12
+ validateLevel,
13
+ } from "./validate.js";
14
+
15
+ export const nativeZip = async (options) => {
16
+ const cwd = options.cwd || process.cwd();
17
+ // Resolve the absolute path in the parent's context and pass that to the
18
+ // child. Resolving the bare `zip` name inside the spawned process would let
19
+ // the archive directory's contents shadow the real binary when PATH has a
20
+ // relative or empty element (CWE-426/CWE-427).
21
+ const command = getNativeZipCommand();
22
+ if (!command) {
23
+ throw new Error(
24
+ "The native zip command was not found at a trusted location on this system."
25
+ );
26
+ }
27
+ const sources = await expandSources(cwd, options.source);
28
+ const destination = path.resolve(cwd, options.destination);
29
+ validateLevel(options.level);
30
+ const destStatBefore = await safeStat(destination);
31
+ // followSymLinks: true opts into following symlinks (archiving their target
32
+ // contents); the default (unset or false) stores symlinks as links.
33
+ const followSymLinks = options.followSymLinks === true;
34
+
35
+ if (!followSymLinks && !nativeZipSupportsSymlinks()) {
36
+ // The native zip command cannot store symlinks as links on this platform
37
+ // (e.g. the Windows build of Info-ZIP). nodeZip can, so the bestzip()
38
+ // entry point routes accordingly — but a direct nativeZip() call can't
39
+ // fulfill this request.
40
+ throw new Error(
41
+ "The native zip command on this platform cannot store symlinks as links. Use the bestzip() entry point, which will select the node implementation, or set followSymLinks to true to follow symlinks instead."
42
+ );
43
+ }
44
+
45
+ const args = ["--quiet", "--recurse-paths"];
46
+ if (typeof options.level === "number") {
47
+ args.push("-" + options.level.toString());
48
+ }
49
+ if (!followSymLinks) {
50
+ args.push("--symlinks");
51
+ }
52
+ args.push(destination, "--", ...sources);
53
+
54
+ // Scan for symlinks to warn about in parallel with the zip command. The
55
+ // scan is best-effort: if it fails (e.g. it races the zip command touching
56
+ // the same paths), log and fall back to no warning rather than aborting the
57
+ // zip, and never let it reject before the zip process has completed.
58
+ const warnScan = (async () => {
59
+ if (options.followSymLinks !== undefined) {
60
+ return [];
61
+ }
62
+ try {
63
+ return await detectSymlinks(cwd, sources);
64
+ } catch (err) {
65
+ console.warn(
66
+ `bestzip: failed to scan for symlinks to warn about: ${err.message}`
67
+ );
68
+ return [];
69
+ }
70
+ })();
71
+
72
+ const zipPromise = new Promise((resolve, reject) => {
73
+ const zipProcess = cp.spawn(command, args, {
74
+ stdio: "inherit",
75
+ cwd,
76
+ });
77
+ zipProcess.on("error", reject);
78
+ zipProcess.on("close", async (exitCode) => {
79
+ if (exitCode === 0) {
80
+ // The native zip reported success. Make sure it actually wrote the
81
+ // archive — the zip exits 0 without creating or updating the
82
+ // destination, that's a silent no-op, not a real archive.
83
+ const destStatAfter = await safeStat(destination);
84
+ if (
85
+ destStatAfter &&
86
+ !isDeepStrictEqual(destStatBefore, destStatAfter)
87
+ ) {
88
+ resolve();
89
+ } else {
90
+ reject(
91
+ new Error(
92
+ `The native zip command exited 0 but did not ${
93
+ destStatBefore ? "update" : "create"
94
+ } the destination archive '${destination}'. This may indicate a broken or incompatible native zip command, or a filesystem issue. Consider using ${
95
+ options.viaCli ? "--force=node" : `{force: 'node'}`
96
+ }.\n Executed command: '${command} ${args.join(
97
+ " "
98
+ )}'\n Executed in directory: '${cwd}'`
99
+ )
100
+ );
101
+ }
102
+ } else {
103
+ reject(
104
+ new Error(
105
+ `Unexpected exit code from native zip: ${exitCode}\n Executed command: '${command} ${args.join(
106
+ " "
107
+ )}'\n Executed in directory '${cwd}'`
108
+ )
109
+ );
110
+ }
111
+ });
112
+ });
113
+
114
+ const [symlinks] = await Promise.all([warnScan, zipPromise]);
115
+ maybeWarnAboutSymlinks(options, symlinks, cwd);
116
+ };
117
+
118
+ // Directories where the system `zip` command is expected to live. Only these
119
+ // are ever consulted, so a file named `zip` anywhere else — committed into an
120
+ // archived directory, delivered through a relative/empty PATH element, or
121
+ // dropped into node_modules/.bin by a dependency — is never executed
122
+ // (CWE-426/CWE-427).
123
+ const DEFAULT_ZIP_DIRS = (() => {
124
+ if (process.platform === "win32") {
125
+ // note, some node.js environments, like MINGW64 (git-bash), report SystemRoot
126
+ // and ProgramFiles as uppercase, but they still support the version here
127
+ const systemRoot = process.env.SystemRoot || "C:\\Windows";
128
+ const programFiles = process.env.ProgramFiles || "C:\\Program Files";
129
+ const programFilesX86 =
130
+ process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
131
+ const localAppData = process.env.LOCALAPPDATA;
132
+ const userProfile = process.env.USERPROFILE;
133
+
134
+ const dirs = [
135
+ path.join(systemRoot, "System32"),
136
+ systemRoot,
137
+ "C:\\ProgramData\\chocolatey\\bin",
138
+ path.join(programFiles, "Git\\usr\\bin"),
139
+ path.join(programFilesX86, "Git\\usr\\bin"),
140
+ ];
141
+
142
+ if (localAppData) {
143
+ dirs.push(path.join(localAppData, "Microsoft\\WinGet\\Links"));
144
+ }
145
+ if (userProfile) {
146
+ dirs.push(path.join(userProfile, "scoop\\shims"));
147
+ }
148
+
149
+ return dirs;
150
+ }
151
+
152
+ return [
153
+ "/usr/bin",
154
+ "/bin",
155
+ "/usr/local/bin",
156
+ "/opt/homebrew/bin", // Homebrew on Apple Silicon
157
+ "/opt/local/bin", // MacPorts
158
+ "/snap/bin", // Linux Snap packages
159
+ "/nix/var/nix/profiles/default/bin", // Nix OS/Package Manager
160
+ ];
161
+ })();
162
+
163
+ const ZIP_EXECUTABLE_NAMES =
164
+ process.platform === "win32" ? ["zip.exe", "zip"] : ["zip"];
165
+
166
+ // Resolves the native `zip` binary's absolute path, or null when none is
167
+ // usable (so callers fall back to the node implementation). PATH is never
168
+ // consulted: the child process chdirs into the (possibly untrusted) archive
169
+ // directory before running, so a bare command name could be shadowed by a
170
+ // `zip` planted there or in the dependency tree (CWE-426/CWE-427). Only the
171
+ // allowlisted system directories above are ever checked, and the resolved
172
+ // absolute path — never the bare `zip` name — is what gets spawned.
173
+ let nativeZipCommand;
174
+ function getNativeZipCommand() {
175
+ if (nativeZipCommand !== undefined) {
176
+ return nativeZipCommand;
177
+ }
178
+ nativeZipCommand = null;
179
+ for (const dir of DEFAULT_ZIP_DIRS) {
180
+ const found = findInDir(dir, ZIP_EXECUTABLE_NAMES);
181
+ if (found) {
182
+ nativeZipCommand = found;
183
+ break;
184
+ }
185
+ }
186
+ return nativeZipCommand;
187
+ }
188
+
189
+ export function hasNativeZip() {
190
+ return Boolean(getNativeZipCommand());
191
+ }
192
+
193
+ let nativeSymlinkCapability;
194
+
195
+ // The native zip command needs the --symlinks flag to store symlinks as links
196
+ // rather than following them. Not every build supports it (notably the
197
+ // Windows build of Info-ZIP). This probes the installed zip for support, since
198
+ // the version string isn't a reliable indicator.
199
+ export function nativeZipSupportsSymlinks() {
200
+ if (nativeSymlinkCapability !== undefined) {
201
+ return nativeSymlinkCapability;
202
+ }
203
+ const command = getNativeZipCommand();
204
+ if (!command) {
205
+ nativeSymlinkCapability = false;
206
+ return nativeSymlinkCapability;
207
+ }
208
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bestzip-symlink-check"));
209
+ try {
210
+ const file = path.join(dir, "file");
211
+ const link = path.join(dir, "link");
212
+ fs.writeFileSync(file, "bestzip symlink check");
213
+ try {
214
+ fs.symlinkSync("file", link);
215
+ } catch (e) {
216
+ nativeSymlinkCapability = false;
217
+ return nativeSymlinkCapability;
218
+ }
219
+ const res = spawnSync(
220
+ command,
221
+ ["-q", "--symlinks", "check.zip", "file", "link"],
222
+ {
223
+ cwd: dir,
224
+ encoding: "utf8",
225
+ }
226
+ );
227
+ nativeSymlinkCapability = res.status === 0;
228
+ } catch (e) {
229
+ nativeSymlinkCapability = false;
230
+ } finally {
231
+ fs.rmSync(dir, { recursive: true, force: true });
232
+ }
233
+ return nativeSymlinkCapability;
234
+ }
package/lib/nodezip.js ADDED
@@ -0,0 +1,102 @@
1
+ import fsp from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { ZipArchive } from "archiver";
5
+
6
+ import { expandSources, walkTree } from "./fs-utils.js";
7
+ import { maybeWarnAboutSymlinks, validateLevel } from "./validate.js";
8
+
9
+ export async function nodeZip(options) {
10
+ const cwd = options.cwd || process.cwd();
11
+ validateLevel(options.level);
12
+ // followSymLinks: true follows symlinks and archives their target contents;
13
+ // the default (unset or false) stores symlinks as links.
14
+ const followSymLinks = options.followSymLinks === true;
15
+ const trackSymLinks = typeof options.followSymLinks === "undefined";
16
+ const symlinks = [];
17
+ const destination = path.resolve(cwd, options.destination);
18
+ const outputFile = await fsp.open(destination, "w");
19
+ const output = outputFile.createWriteStream();
20
+ const archive = new ZipArchive({
21
+ zlib: { level: options.level },
22
+ });
23
+
24
+ output.on("close", async () => {
25
+ await outputFile.close();
26
+ resolvePromise();
27
+ });
28
+ archive.on("error", (err) => rejectPromise(err));
29
+ archive.on("warning", (err) => console.warn(err && err.message));
30
+
31
+ archive.pipe(output);
32
+
33
+ let resolvePromise;
34
+ let rejectPromise;
35
+ const promise = new Promise((resolve, reject) => {
36
+ resolvePromise = resolve;
37
+ rejectPromise = reject;
38
+ });
39
+
40
+ async function addSource(source) {
41
+ const fullPath = path.resolve(cwd, source);
42
+ const destPath = source;
43
+
44
+ // Walk the source once in the requested mode: an lstat walk when storing
45
+ // links (symlinks are emitted as their own entries and stored as links),
46
+ // or a stat walk when following (symlinks are dereferenced and their
47
+ // target contents archived, matching the native zip implementation).
48
+ const entries = await walkTree(fullPath, followSymLinks);
49
+ for (const entry of entries) {
50
+ // The archive was created (and truncated) above, so a source that
51
+ // reaches it — directly, or through a directory glob — would otherwise
52
+ // archive a partial copy of the archive itself. walkTree yields absolute
53
+ // normalized paths, so this compares directly.
54
+ //
55
+ // Known limit: neither implementation compares file identity, only paths,
56
+ // so a destination accessed via a symlinked parent directory still
57
+ // matches itself when the walk reaches the same file by its real path.
58
+ // That needs followSymLinks: true plus an overlapping symlink, and it affects
59
+ // nativeZip identically, so it is left alone rather than diverging here.
60
+ if (entry.path === destination) {
61
+ continue;
62
+ }
63
+ const archiveName = destPath + entry.path.substring(fullPath.length);
64
+ if (entry.stats.isSymbolicLink()) {
65
+ // Storing a link: keep the raw link target and record it for the
66
+ // default warning (an explicit followSymLinks setting suppresses it).
67
+ if (trackSymLinks) {
68
+ symlinks.push(entry.path);
69
+ }
70
+ archive.symlink(
71
+ archiveName,
72
+ await fsp.readlink(entry.path),
73
+ entry.stats.mode
74
+ );
75
+ } else {
76
+ if (
77
+ entry.stats.isDirectory() &&
78
+ [".", ""].includes(path.basename(archiveName))
79
+ ) {
80
+ continue;
81
+ }
82
+ archive.file(entry.path, {
83
+ name: archiveName,
84
+ stats: entry.stats,
85
+ });
86
+ }
87
+ }
88
+ }
89
+
90
+ try {
91
+ const expandedSources = await expandSources(cwd, options.source);
92
+ for (const source of expandedSources) {
93
+ await addSource(source);
94
+ }
95
+ maybeWarnAboutSymlinks(options, symlinks, cwd);
96
+ archive.finalize();
97
+ } catch (err) {
98
+ rejectPromise(err);
99
+ }
100
+
101
+ return promise;
102
+ }
@@ -0,0 +1,59 @@
1
+ import path from "node:path";
2
+
3
+ import { walkTree } from "./fs-utils.js";
4
+
5
+ // Validates the compression level. A level of exactly 0-9 (an integer) is
6
+ // accepted; anything else that is set causes an error. An unset level is
7
+ // allowed and left to each implementation's default.
8
+ export function validateLevel(level) {
9
+ if (typeof level === "undefined") {
10
+ return;
11
+ }
12
+ if (
13
+ typeof level !== "number" ||
14
+ !Number.isInteger(level) ||
15
+ level < 0 ||
16
+ level > 9
17
+ ) {
18
+ const typehint = typeof level === "number" ? "" : ` (${typeof level})`;
19
+ throw new Error(
20
+ `bestzip: level should be an integer from 0 to 9, got ${level}${typehint}`
21
+ );
22
+ }
23
+ }
24
+
25
+ export async function detectSymlinks(cwd, sources) {
26
+ const results = await Promise.all(
27
+ sources.map(async (source) => {
28
+ const fullPath = path.resolve(cwd, source);
29
+ const entries = await walkTree(fullPath, false);
30
+ return entries
31
+ .filter((entry) => entry.stats.isSymbolicLink())
32
+ .map((entry) => entry.path);
33
+ })
34
+ );
35
+ return results.flat();
36
+ }
37
+
38
+ export function maybeWarnAboutSymlinks(options, symlinks, cwd) {
39
+ if (options.followSymLinks !== undefined || symlinks.length === 0) {
40
+ return;
41
+ }
42
+ const cli = options.viaCli;
43
+ const optIn = cli ? "pass --follow-sym-links" : "set followSymLinks: true";
44
+ const optOut = cli
45
+ ? "pass --no-follow-sym-links"
46
+ : "set followSymLinks: false";
47
+ let lines = symlinks.map((p) => path.relative(cwd, p));
48
+ if (lines.length > 4) {
49
+ lines = lines.slice(0, 3);
50
+ lines.push(`...and ${symlinks.length - 3} more`);
51
+ }
52
+ console.warn(
53
+ "Warning: Symbolic links are stored as the link itself rather than the destination by default.\n" +
54
+ `To keep the default behavior and prevent this warning, ${optOut}.\n` +
55
+ `To follow symlinks and include their target contents, ${optIn}.\n` +
56
+ "Detected symlinks:\n" +
57
+ lines.join("\n")
58
+ );
59
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bestzip",
3
- "version": "4.0.1",
3
+ "version": "4.0.3",
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",
@@ -14,7 +14,7 @@
14
14
  "lint": "eslint .",
15
15
  "lint-fix": "eslint --fix .",
16
16
  "unit-test": "node --experimental-test-snapshots --test \"test/**/*.test.js\"",
17
- "update-snapshot": "npm run unit-test -- --test-update-snapshots",
17
+ "update-snapshot": "node --experimental-test-snapshots --test-update-snapshots --test \"test/**/*.test.js\"",
18
18
  "test": "npm run lint && npm run unit-test"
19
19
  },
20
20
  "author": "Nathan Friedly - http://nfriedly.com/",