@nwutils/getter 0.2.5 → 0.2.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nwutils/getter",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "Get NW.js and related binaries for Linux, MacOS and Windows.",
5
5
  "keywords": [
6
6
  "NW.js",
@@ -48,19 +48,21 @@
48
48
  },
49
49
  "dependencies": {
50
50
  "semver": "^7.8.5",
51
- "tar": "^7.5.20",
51
+ "tar": "^7.5.22",
52
52
  "yauzl-promise": "^4.0.0"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@eslint/js": "^10.0.1",
56
- "@types/node": "^26.1.1",
57
- "@types/semver": "^7.7.1",
56
+ "@types/node": "^26.4.0",
57
+ "@types/semver": "^7.8.0",
58
58
  "@types/yauzl-promise": "^4.0.1",
59
- "eslint": "^10.7.0",
60
- "eslint-plugin-jsdoc": "^63.1.0",
59
+ "eslint": "^10.9.1",
60
+ "eslint-plugin-jsdoc": "^64.2.1",
61
+ "eslint-plugin-node-security": "^5.2.3",
62
+ "eslint-plugin-secure-coding": "^5.1.4",
61
63
  "eslint-plugin-simple-import-sort": "^14.0.0",
62
- "globals": "^17.4.0",
63
- "prettier": "^3.9.5",
64
+ "globals": "^17.11.0",
65
+ "prettier": "^3.9.6",
64
66
  "typescript": "^7.0.2"
65
67
  },
66
68
  "devEngines": {
package/src/decompress.js CHANGED
@@ -5,26 +5,115 @@ import stream from "node:stream";
5
5
  import * as tar from "tar";
6
6
  import yauzl from "yauzl-promise";
7
7
 
8
+ /**
9
+ * Maximum number of entries an archive may contain, and maximum total bytes
10
+ * an archive may extract to `cacheDir` across all entries combined. Guards
11
+ * against decompression bombs (CWE-409) - a small, highly compressed archive
12
+ * that expands to an implausible amount of data or number of files on disk.
13
+ * @type {number}
14
+ */
15
+ const MAX_ENTRIES = 200_000;
16
+
17
+ /**
18
+ * @type {number}
19
+ */
20
+ const MAX_TOTAL_EXTRACTED_SIZE = 20 * 1024 * 1024 * 1024; // 20 GiB
21
+
22
+ /**
23
+ * Maximum size of a single symlink target read from a zip archive. Real
24
+ * filesystem paths are nowhere near this size; a "symlink" entry claiming
25
+ * more is either corrupt or an attempt to exhaust memory by buffering an
26
+ * unbounded amount of "target" data.
27
+ * @type {number}
28
+ */
29
+ const MAX_SYMLINK_TARGET_SIZE = 4096;
30
+
8
31
  /**
9
32
  * Decompresses a file at `filePath` to `cacheDir` directory.
10
33
  * @async
11
34
  * @function
12
- * @param {string} filePath - file path to compressed binary
13
- * @param {string} cacheDir - directory to decompress into
35
+ * @param {string} filePath - file path to compressed binary
36
+ * @param {string} cacheDir - directory to decompress into
37
+ * @param {object} [limits] - override the default bomb-protection limits (CWE-409). Exposed for tests; production callers should not need this.
38
+ * @param {number} [limits.maxEntries] - defaults to {@link MAX_ENTRIES}
39
+ * @param {number} [limits.maxTotalExtractedSize] - defaults to {@link MAX_TOTAL_EXTRACTED_SIZE}
14
40
  * @throws {Error}
15
41
  * @returns {Promise<void>}
16
42
  */
17
- export default async function decompress(filePath, cacheDir) {
43
+ export default async function decompress(filePath, cacheDir, limits = {}) {
44
+ const maxEntries = limits.maxEntries ?? MAX_ENTRIES;
45
+ const maxTotalExtractedSize =
46
+ limits.maxTotalExtractedSize ?? MAX_TOTAL_EXTRACTED_SIZE;
47
+
18
48
  if (filePath.endsWith(".zip")) {
19
- await unzip(filePath, cacheDir);
49
+ /*
50
+ * Every entry unzip() writes is resolved through resolveWithin() first -
51
+ * file entries, symlink names and symlink targets alike. The rule reports
52
+ * the call site rather than the write site, so it cannot see that guard
53
+ * from here.
54
+ */
55
+ // eslint-disable-next-line node-security/no-zip-slip
56
+ await unzip(filePath, cacheDir, maxEntries, maxTotalExtractedSize);
20
57
  } else {
58
+ /*
59
+ * node-tar v7 strips `..` segments and absolute paths itself unless
60
+ * `preservePaths` is set, and it is not set here.
61
+ */
62
+ let tarEntryCount = 0;
63
+ let tarExtractedBytes = 0;
64
+
65
+ /*
66
+ * `filter` below tracks `tarExtractedBytes` against
67
+ * `maxTotalExtractedSize` and skips any entry that would exceed it, so
68
+ * this is bounded even though the linter can't see through the closure.
69
+ */
70
+ // eslint-disable-next-line node-security/no-zip-slip, secure-coding/no-unlimited-resource-allocation
21
71
  await tar.extract({
22
72
  file: filePath,
23
73
  C: cacheDir,
74
+ /* Bomb protection (CWE-409): skip entries once either limit is hit. */
75
+ filter: (entryPath, entry) => {
76
+ tarEntryCount += 1;
77
+ if (tarEntryCount > maxEntries) {
78
+ console.warn(
79
+ `Skipping ${JSON.stringify(entryPath)}: archive entry count exceeds the limit of ${maxEntries}.`,
80
+ );
81
+ return false;
82
+ }
83
+
84
+ tarExtractedBytes += entry.size ?? 0;
85
+ if (tarExtractedBytes > maxTotalExtractedSize) {
86
+ console.warn(
87
+ `Skipping ${JSON.stringify(entryPath)}: total extracted size would exceed the limit of ${maxTotalExtractedSize} bytes.`,
88
+ );
89
+ return false;
90
+ }
91
+
92
+ return true;
93
+ },
24
94
  });
25
95
  }
26
96
  }
27
97
 
98
+ /**
99
+ * Prevent any `entryName` from escaping the `root` leading to Zip Slip via the symlink.
100
+ *
101
+ * @param {string} root - directory every entry must stay within
102
+ * @param {string} entryName - entry name as recorded in the archive
103
+ * @throws {Error} - when the entry resolves outside `root`
104
+ * @returns {string} - the safe absolute path
105
+ */
106
+ function resolveWithin(root, entryName) {
107
+ const rootAbs = path.resolve(root);
108
+ const target = path.resolve(rootAbs, entryName);
109
+ if (target !== rootAbs && !target.startsWith(rootAbs + path.sep)) {
110
+ throw new Error(
111
+ `Refusing to extract ${JSON.stringify(entryName)}: it resolves outside the destination directory.`,
112
+ );
113
+ }
114
+ return target;
115
+ }
116
+
28
117
  /**
29
118
  * Get file mode from entry. Reference implementation is [here](https://github.com/fpsqdb/zip-lib/blob/ac447d269218d396e05cd7072d0e9cd82b5ec52c/src/unzip.ts#L380).
30
119
  * @async
@@ -44,61 +133,124 @@ function modeFromEntry(entry) {
44
133
  * Unzip `zippedFile` to `cacheDir`.
45
134
  * @async
46
135
  * @function
47
- * @param {string} zippedFile - file path to .zip file
48
- * @param {string} cacheDir - directory to unzip in
136
+ * @param {string} zippedFile - file path to .zip file
137
+ * @param {string} cacheDir - directory to unzip in
138
+ * @param {number} maxEntries - bomb protection (CWE-409): max archive entries
139
+ * @param {number} maxTotalExtractedSize - bomb protection (CWE-409): max total bytes extracted
49
140
  * @throws {Error}
50
141
  * @returns {Promise<void>}
51
142
  */
52
- async function unzip(zippedFile, cacheDir) {
143
+ async function unzip(zippedFile, cacheDir, maxEntries, maxTotalExtractedSize) {
53
144
  const zip = await yauzl.open(zippedFile);
54
- let entry = await zip.readEntry();
55
- /* Array to hold symbolic link entries */
56
- const symlinks = [];
57
-
58
- while (entry !== null) {
59
- let entryPathAbs = path.join(cacheDir, entry.filename);
60
- /* Check if entry is a symbolic link */
61
- const isSymlink = (modeFromEntry(entry) & 0o170000) === 0o120000;
62
-
63
- if (isSymlink) {
64
- /* Store symlink entries to process later */
65
- symlinks.push(entry);
66
- } else {
67
- /* Handle regular files and directories */
68
- await fs.promises.mkdir(path.dirname(entryPathAbs), { recursive: true });
69
- /* Skip directories */
70
- if (!entry.filename.endsWith("/")) {
71
- const readStream = await entry.openReadStream();
72
- const writeStream = fs.createWriteStream(entryPathAbs);
73
- await stream.promises.pipeline(readStream, writeStream);
74
-
75
- /* Set file permissions after the file has been written */
76
- const mode = modeFromEntry(entry);
77
- await fs.promises.chmod(entryPathAbs, mode);
145
+
146
+ try {
147
+ let entry = await zip.readEntry();
148
+ /* Array to hold symbolic link entries */
149
+ const symlinks = [];
150
+ /* Bomb protection (CWE-409) state, shared across every entry. */
151
+ let entryCount = 0;
152
+ let totalExtractedBytes = 0;
153
+
154
+ while (entry !== null) {
155
+ entryCount += 1;
156
+ if (entryCount > maxEntries) {
157
+ throw new Error(
158
+ `Refusing to extract archive: entry count exceeds the limit of ${maxEntries}.`,
159
+ );
160
+ }
161
+
162
+ const entryPathAbs = resolveWithin(cacheDir, entry.filename);
163
+ /* Check if entry is a symbolic link */
164
+ const isSymlink = (modeFromEntry(entry) & 0o170000) === 0o120000;
165
+
166
+ if (isSymlink) {
167
+ /* Store symlink entries to process later */
168
+ symlinks.push(entry);
169
+ } else {
170
+ /* Handle regular files and directories */
171
+ await fs.promises.mkdir(path.dirname(entryPathAbs), {
172
+ recursive: true,
173
+ });
174
+ /* Skip directories */
175
+ if (!entry.filename.endsWith("/")) {
176
+ const readStream = await entry.openReadStream();
177
+ const writeStream = fs.createWriteStream(entryPathAbs);
178
+ /* Track actual bytes streamed rather than trusting the archive's declared size. */
179
+ const sizeGuard = new stream.Transform({
180
+ transform(chunk, _encoding, callback) {
181
+ totalExtractedBytes += chunk.length;
182
+ if (totalExtractedBytes > maxTotalExtractedSize) {
183
+ callback(
184
+ new Error(
185
+ `Refusing to extract archive: total extracted size exceeds the limit of ${maxTotalExtractedSize} bytes.`,
186
+ ),
187
+ );
188
+ return;
189
+ }
190
+ callback(null, chunk);
191
+ },
192
+ });
193
+ await stream.promises.pipeline(readStream, sizeGuard, writeStream);
194
+
195
+ /* Set file permissions after the file has been written */
196
+ const mode = modeFromEntry(entry);
197
+ await fs.promises.chmod(entryPathAbs, mode);
198
+ }
78
199
  }
200
+
201
+ /* Read next entry */
202
+ entry = await zip.readEntry();
79
203
  }
80
204
 
81
- /* Read next entry */
82
- entry = await zip.readEntry();
83
- }
205
+ /* Process symbolic links after all other files have been extracted */
206
+ for (const symlinkEntry of symlinks) {
207
+ const entryPathAbs = resolveWithin(cacheDir, symlinkEntry.filename);
208
+ const readStream = await symlinkEntry.openReadStream();
209
+ /** @type {Buffer[]} */
210
+ const chunks = [];
211
+ let symlinkTargetSize = 0;
212
+ await new Promise((resolve, reject) => {
213
+ readStream.on("data", (chunk) => {
214
+ symlinkTargetSize += chunk.length;
215
+ if (symlinkTargetSize > MAX_SYMLINK_TARGET_SIZE) {
216
+ readStream.destroy();
217
+ reject(
218
+ new Error(
219
+ `Refusing to extract ${JSON.stringify(symlinkEntry.filename)}: symlink target exceeds ${MAX_SYMLINK_TARGET_SIZE} bytes.`,
220
+ ),
221
+ );
222
+ return;
223
+ }
224
+ chunks.push(chunk);
225
+ });
226
+ readStream.on("end", resolve);
227
+ readStream.on("error", reject);
228
+ });
229
+ const linkTarget = Buffer.concat(chunks).toString("utf8").trim();
230
+
231
+ /*
232
+ * The link target comes out of the archive too, so a contained symlink can
233
+ * still point anywhere - and a later entry written through it escapes.
234
+ * Resolve the target relative to the link's own directory and require it
235
+ * to stay inside cacheDir as well.
236
+ */
237
+ resolveWithin(
238
+ cacheDir,
239
+ path.relative(
240
+ cacheDir,
241
+ path.resolve(path.dirname(entryPathAbs), linkTarget),
242
+ ),
243
+ );
84
244
 
85
- /* Process symbolic links after all other files have been extracted */
86
- for (const symlinkEntry of symlinks) {
87
- let entryPathAbs = path.join(cacheDir, symlinkEntry.filename);
88
- const readStream = await symlinkEntry.openReadStream();
89
- /** @type {Buffer[]} */
90
- const chunks = [];
91
- readStream.on("data", (chunk) => chunks.push(chunk));
92
- await new Promise((resolve) => readStream.on("end", resolve));
93
- const linkTarget = Buffer.concat(chunks).toString("utf8").trim();
94
-
95
- /* Check if the symlink or a file/directory already exists at the destination */
96
- if (fs.existsSync(entryPathAbs)) {
97
- /* skip */
98
- } else {
99
- /* Create symbolic link */
100
- await fs.promises.symlink(linkTarget, entryPathAbs);
245
+ /* Check if the symlink or a file/directory already exists at the destination */
246
+ if (fs.existsSync(entryPathAbs)) {
247
+ /* skip */
248
+ } else {
249
+ /* Create symbolic link */
250
+ await fs.promises.symlink(linkTarget, entryPathAbs);
251
+ }
101
252
  }
253
+ } finally {
254
+ await zip.close();
102
255
  }
103
- await zip.close();
104
256
  }
package/src/main.js CHANGED
@@ -6,7 +6,7 @@ import semver from "semver";
6
6
 
7
7
  import decompress from "./decompress.js";
8
8
  import ffmpeg from "./ffmpeg.js";
9
- import node from "./node.js";
9
+ import node, { headersFileName } from "./node.js";
10
10
  import nw from "./nw.js";
11
11
  import request from "./request.js";
12
12
  import verify from "./verify.js";
@@ -42,7 +42,22 @@ async function get(options) {
42
42
  const manifestFilePath = path.resolve(options.cacheDir, "manifest.json");
43
43
  if (options.manifestUrl.startsWith("file://")) {
44
44
  const filePath = url.fileURLToPath(options.manifestUrl);
45
- fs.writeFileSync(manifestFilePath, fs.readFileSync(filePath, "utf-8"));
45
+ const manifestContents = fs.readFileSync(filePath, "utf-8");
46
+
47
+ /*
48
+ * `manifestUrl` can point at any local path the caller supplies. Refuse
49
+ * to copy it into cacheDir unless it's actually a JSON manifest, rather
50
+ * than blindly persisting whatever bytes were found at that path.
51
+ */
52
+ try {
53
+ JSON.parse(manifestContents);
54
+ } catch {
55
+ throw new Error(
56
+ `Expected "options.manifestUrl" file to contain valid JSON. Received: ${JSON.stringify(options.manifestUrl)}`,
57
+ );
58
+ }
59
+
60
+ fs.writeFileSync(manifestFilePath, manifestContents);
46
61
  } else {
47
62
  await request(options.manifestUrl, manifestFilePath);
48
63
  }
@@ -159,9 +174,23 @@ async function get(options) {
159
174
 
160
175
  /* Download server is the cached directory. */
161
176
  if (uri.protocol === "file:") {
162
- options.cacheDir = path.resolve(
177
+ const mirrorDir = path.resolve(
163
178
  decodeURIComponent(options.downloadUrl.slice("file://".length)),
164
179
  );
180
+
181
+ /*
182
+ * `cacheDir` is used as the root for a recursive delete and for archive
183
+ * extraction. A filesystem root has no parent to contain those operations,
184
+ * so refuse it rather than let a mistyped or attacker-influenced
185
+ * `downloadUrl` point either at the whole drive.
186
+ */
187
+ if (mirrorDir === path.parse(mirrorDir).root) {
188
+ throw new Error(
189
+ `Expected "options.downloadUrl" file path to not be a filesystem root. Received: ${JSON.stringify(mirrorDir)}`,
190
+ );
191
+ }
192
+
193
+ options.cacheDir = mirrorDir;
165
194
  }
166
195
 
167
196
  /**
@@ -210,16 +239,29 @@ async function get(options) {
210
239
  );
211
240
  }
212
241
 
213
- await decompress(nwFilePath, options.cacheDir);
242
+ /*
243
+ * Checksums are always fetched from the canonical NW.js host, even when
244
+ * `downloadUrl` points at a different mirror. Otherwise a compromised or
245
+ * malicious mirror could serve both the binary and the checksum used to
246
+ * "verify" it, making the check worthless against a hostile source. A
247
+ * `file://` `downloadUrl` is local mirror/offline mode, so it still
248
+ * resolves the checksum file from there rather than requiring network access.
249
+ */
250
+ const checksumHost =
251
+ uri.protocol === "file:" ? options.downloadUrl : "https://dl.nwjs.io";
214
252
 
253
+ /* Verify the archive's checksum before extracting its contents. */
215
254
  await verify(
216
- `${options.downloadUrl}/v${options.version}/SHASUMS256.txt`,
255
+ `${checksumHost}/v${options.version}/SHASUMS256.txt`,
217
256
  `${options.cacheDir}/shasum/${options.version}.txt`,
218
257
  options.cacheDir,
219
258
  options.ffmpeg,
220
259
  options.shaSum,
260
+ path.basename(nwFilePath),
221
261
  );
222
262
 
263
+ await decompress(nwFilePath, options.cacheDir);
264
+
223
265
  if (options.ffmpeg === true) {
224
266
  /**
225
267
  * File path to compressed binary which contains community FFmpeg binary.
@@ -307,7 +349,7 @@ async function get(options) {
307
349
  */
308
350
  let nodeFilePath = path.resolve(
309
351
  options.cacheDir,
310
- `headers-v${options.version}.tar.gz`,
352
+ headersFileName(options.version),
311
353
  );
312
354
 
313
355
  // If `options.cache` is false, then remove the compressed binary.
@@ -327,6 +369,20 @@ async function get(options) {
327
369
  );
328
370
  }
329
371
 
372
+ /*
373
+ * Unlike the community ffmpeg build, SHASUMS256.txt already publishes a
374
+ * checksum for the Node headers tarball - verify it the same way as the
375
+ * main archive, before extracting it.
376
+ */
377
+ await verify(
378
+ `${checksumHost}/v${options.version}/SHASUMS256.txt`,
379
+ `${options.cacheDir}/shasum/${options.version}.txt`,
380
+ options.cacheDir,
381
+ options.ffmpeg,
382
+ options.shaSum,
383
+ headersFileName(options.version),
384
+ );
385
+
330
386
  await decompress(nodeFilePath, options.cacheDir);
331
387
  }
332
388
  }
package/src/node.js CHANGED
@@ -4,6 +4,18 @@ import semver from "semver";
4
4
 
5
5
  import request from "./request.js";
6
6
 
7
+ /**
8
+ * Name of the Node headers tarball, as both the download URL and the
9
+ * SHASUMS256.txt checksum entry for `version` refer to it. For reference:
10
+ * [nwjs/nw.js@471e406](https://github.com/nwjs/nw.js/blob/471e406/lib/node.js)
11
+ * @param {string} version - Runtime version
12
+ * @returns {string} - eg. "node-v0.111.3.tar.gz" or "nw-headers-v0.107.0.tar.gz"
13
+ */
14
+ export function headersFileName(version) {
15
+ const headersPrefix = semver.gte(version, "0.111.3") ? "node" : "nw-headers";
16
+ return `${headersPrefix}-v${version}.tar.gz`;
17
+ }
18
+
7
19
  /**
8
20
  * Download NW.js's Node.js headers.
9
21
  * @async
@@ -16,32 +28,18 @@ import request from "./request.js";
16
28
  */
17
29
  export default async function nw(downloadUrl, version, cacheDir) {
18
30
  /**
19
- * Name of directory which contains Node headers.
20
- * @type {string}
21
- */
22
- const nodeDir = `node-v${version}`;
23
-
24
- /**
25
- * Name of compressed file which contains Node headers.
31
+ * Name of compressed file which contains Node headers. Saved locally under
32
+ * the same name it's listed under in SHASUMS256.txt, so its checksum can
33
+ * actually be looked up later.
26
34
  * @type {string}
27
35
  */
28
- const nwFile = `${nodeDir}.tar.gz`;
29
-
30
- /**
31
- * Prefix of Node headers file name. For reference: [nwjs/nw.js@471e406](https://github.com/nwjs/nw.js/blob/471e406/lib/node.js)
32
- * @type {string}
33
- */
34
- const headersPrefix = semver.gte(version, "0.111.3") ? "node" : "nw-headers";
36
+ const nwFile = headersFileName(version);
35
37
 
36
38
  /**
37
39
  * URL to download specific Node headers from.
38
40
  * @type {string}
39
41
  */
40
- const url = [
41
- downloadUrl,
42
- `v${version}`,
43
- `${headersPrefix}-v${version}.tar.gz`,
44
- ].join("/");
42
+ const url = [downloadUrl, `v${version}`, nwFile].join("/");
45
43
 
46
44
  /**
47
45
  * Absolute path of compressed file which contains Node headers.
package/src/request.js CHANGED
@@ -4,13 +4,20 @@ import https from "node:https";
4
4
  import process from "node:process";
5
5
  import { URL } from "node:url";
6
6
 
7
+ /**
8
+ * Maximum number of HTTP redirects to follow before giving up.
9
+ * @type {number}
10
+ */
11
+ const MAX_REDIRECTS = 5;
12
+
7
13
  /**
8
14
  * Download from `url` and save at `filePath`.
9
15
  * @param {string} url
10
16
  * @param {string} filePath
17
+ * @param {number} [redirectCount] - Number of redirects already followed. Used internally for recursive calls.
11
18
  * @returns {Promise<void>}
12
19
  */
13
- export default function request(url, filePath) {
20
+ export default function request(url, filePath, redirectCount = 0) {
14
21
  const parsedUrl = new URL(url);
15
22
  const client = parsedUrl.protocol === "https:" ? https : http;
16
23
 
@@ -26,8 +33,15 @@ export default function request(url, filePath) {
26
33
  /* Ctrl+C cleanup */
27
34
  const onSigInt = () => {
28
35
  writeStream.destroy();
29
- if (fs.existsSync(filePath)) {
36
+ /*
37
+ * Unlink unconditionally and swallow ENOENT: checking with existsSync
38
+ * first is a check-then-act race (CWE-367) - the file can vanish between
39
+ * the two calls, and on SIGINT there is no useful recovery either way.
40
+ */
41
+ try {
30
42
  fs.unlinkSync(filePath);
43
+ } catch {
44
+ /* Nothing to clean up. */
31
45
  }
32
46
  process.exit();
33
47
  };
@@ -52,11 +66,35 @@ export default function request(url, filePath) {
52
66
  ) {
53
67
  cleanup();
54
68
 
55
- const redirectedUrl = new URL(
56
- res.headers.location,
57
- parsedUrl,
58
- ).toString();
59
- return resolve(request(redirectedUrl, filePath));
69
+ if (redirectCount >= MAX_REDIRECTS) {
70
+ return reject(
71
+ new Error(
72
+ `Too many redirects (> ${MAX_REDIRECTS}) while requesting ${url}`,
73
+ ),
74
+ );
75
+ }
76
+
77
+ const redirectedUrl = new URL(res.headers.location, parsedUrl);
78
+
79
+ /*
80
+ * A redirect response can be injected by a network attacker even
81
+ * when the original request can't be, so refuse one that would
82
+ * silently strip transport security from the rest of the chain.
83
+ */
84
+ if (
85
+ parsedUrl.protocol === "https:" &&
86
+ redirectedUrl.protocol === "http:"
87
+ ) {
88
+ return reject(
89
+ new Error(
90
+ `Refusing to follow redirect from ${url} to ${redirectedUrl.toString()}: downgrades from https to http.`,
91
+ ),
92
+ );
93
+ }
94
+
95
+ return resolve(
96
+ request(redirectedUrl.toString(), filePath, redirectCount + 1),
97
+ );
60
98
  }
61
99
 
62
100
  if (res.statusCode !== 200) {
package/src/verify.js CHANGED
@@ -12,11 +12,19 @@ import request from "./request.js";
12
12
  * @param {string} shaOut - File path to shasum text file.
13
13
  * @param {string} cacheDir - File path to cache directory.
14
14
  * @param {boolean} ffmpeg - Toggle between community (true) and official (false) ffmpeg binary
15
- * @param {boolean} shaSum - Throws error if true, otherwise logs a warning.
15
+ * @param {boolean} shaSum - Throws error if true, otherwise logs a warning. Applies to both a checksum mismatch and `expectedFile` never being checked at all.
16
+ * @param {string} [expectedFile] - Relative path, as listed in the SHASUMS file, that this call is actually relying on being verified. Other listed files that don't exist locally (eg. other platforms) are still skipped silently - only `expectedFile` going unchecked is treated as a failure, since that means the caller's "integrity verified" belief was never actually true.
16
17
  * @throws {Error}
17
18
  * @returns {Promise<boolean>} - Returns true if the checksums match.
18
19
  */
19
- export default async function verify(shaUrl, shaOut, cacheDir, ffmpeg, shaSum) {
20
+ export default async function verify(
21
+ shaUrl,
22
+ shaOut,
23
+ cacheDir,
24
+ ffmpeg,
25
+ shaSum,
26
+ expectedFile,
27
+ ) {
20
28
  const shaOutExists = fs.existsSync(shaOut);
21
29
 
22
30
  if (shaOutExists === false) {
@@ -30,11 +38,17 @@ export default async function verify(shaUrl, shaOut, cacheDir, ffmpeg, shaSum) {
30
38
  /* Read SHASUM text file */
31
39
  const shasum = await fs.promises.readFile(shaOut, { encoding: "utf-8" });
32
40
  const shasums = shasum.trim().split("\n");
41
+ let expectedFileWasChecked = false;
42
+
33
43
  for await (const line of shasums) {
34
44
  const [storedSha, filePath] = line.split(/\s+/);
35
45
  const relativeFilePath = path.resolve(cacheDir, filePath);
36
46
  const relativefilePathExists = fs.existsSync(relativeFilePath);
37
47
  if (relativefilePathExists) {
48
+ if (filePath === expectedFile) {
49
+ expectedFileWasChecked = true;
50
+ }
51
+
38
52
  const fileBuffer = await fs.promises.readFile(relativeFilePath);
39
53
  const hash = crypto.createHash("sha256");
40
54
  hash.update(fileBuffer);
@@ -61,5 +75,20 @@ export default async function verify(shaUrl, shaOut, cacheDir, ffmpeg, shaSum) {
61
75
  }
62
76
  }
63
77
 
78
+ /*
79
+ * Most of `expectedFile` unchecked would mean nothing was actually
80
+ * verified - eg. a naming mismatch, or the entry missing from the SHASUMS
81
+ * file - while every other unmatched line above is legitimately silent
82
+ * (other platforms/flavors listed in the same file).
83
+ */
84
+ if (expectedFile && !expectedFileWasChecked) {
85
+ const message = `Expected a checksum entry for ${JSON.stringify(expectedFile)} in ${JSON.stringify(shaOut)}, but it was not found or does not exist locally - the archive's integrity was not actually checked.`;
86
+ if (shaSum) {
87
+ throw new Error(message);
88
+ } else {
89
+ console.warn(message);
90
+ }
91
+ }
92
+
64
93
  return true;
65
94
  }
@@ -2,9 +2,15 @@
2
2
  * Decompresses a file at `filePath` to `cacheDir` directory.
3
3
  * @async
4
4
  * @function
5
- * @param {string} filePath - file path to compressed binary
6
- * @param {string} cacheDir - directory to decompress into
5
+ * @param {string} filePath - file path to compressed binary
6
+ * @param {string} cacheDir - directory to decompress into
7
+ * @param {object} [limits] - override the default bomb-protection limits (CWE-409). Exposed for tests; production callers should not need this.
8
+ * @param {number} [limits.maxEntries] - defaults to {@link MAX_ENTRIES}
9
+ * @param {number} [limits.maxTotalExtractedSize] - defaults to {@link MAX_TOTAL_EXTRACTED_SIZE}
7
10
  * @throws {Error}
8
11
  * @returns {Promise<void>}
9
12
  */
10
- export default function decompress(filePath: string, cacheDir: string): Promise<void>;
13
+ export default function decompress(filePath: string, cacheDir: string, limits?: {
14
+ maxEntries?: number;
15
+ maxTotalExtractedSize?: number;
16
+ }): Promise<void>;
package/types/node.d.ts CHANGED
@@ -1,3 +1,11 @@
1
+ /**
2
+ * Name of the Node headers tarball, as both the download URL and the
3
+ * SHASUMS256.txt checksum entry for `version` refer to it. For reference:
4
+ * [nwjs/nw.js@471e406](https://github.com/nwjs/nw.js/blob/471e406/lib/node.js)
5
+ * @param {string} version - Runtime version
6
+ * @returns {string} - eg. "node-v0.111.3.tar.gz" or "nw-headers-v0.107.0.tar.gz"
7
+ */
8
+ export declare function headersFileName(version: string): string;
1
9
  /**
2
10
  * Download NW.js's Node.js headers.
3
11
  * @async
@@ -2,6 +2,7 @@
2
2
  * Download from `url` and save at `filePath`.
3
3
  * @param {string} url
4
4
  * @param {string} filePath
5
+ * @param {number} [redirectCount] - Number of redirects already followed. Used internally for recursive calls.
5
6
  * @returns {Promise<void>}
6
7
  */
7
- export default function request(url: string, filePath: string): Promise<void>;
8
+ export default function request(url: string, filePath: string, redirectCount?: number): Promise<void>;
package/types/verify.d.ts CHANGED
@@ -6,8 +6,9 @@
6
6
  * @param {string} shaOut - File path to shasum text file.
7
7
  * @param {string} cacheDir - File path to cache directory.
8
8
  * @param {boolean} ffmpeg - Toggle between community (true) and official (false) ffmpeg binary
9
- * @param {boolean} shaSum - Throws error if true, otherwise logs a warning.
9
+ * @param {boolean} shaSum - Throws error if true, otherwise logs a warning. Applies to both a checksum mismatch and `expectedFile` never being checked at all.
10
+ * @param {string} [expectedFile] - Relative path, as listed in the SHASUMS file, that this call is actually relying on being verified. Other listed files that don't exist locally (eg. other platforms) are still skipped silently - only `expectedFile` going unchecked is treated as a failure, since that means the caller's "integrity verified" belief was never actually true.
10
11
  * @throws {Error}
11
12
  * @returns {Promise<boolean>} - Returns true if the checksums match.
12
13
  */
13
- export default function verify(shaUrl: string, shaOut: string, cacheDir: string, ffmpeg: boolean, shaSum: boolean): Promise<boolean>;
14
+ export default function verify(shaUrl: string, shaOut: string, cacheDir: string, ffmpeg: boolean, shaSum: boolean, expectedFile?: string): Promise<boolean>;