@nwutils/getter 0.2.4 → 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/README.md CHANGED
@@ -6,7 +6,6 @@ Download NW.js and related binaries for Linux, MacOS and Windows.
6
6
 
7
7
  ## Getting Started
8
8
 
9
- 1. Install [Volta](https://volta.sh)
10
9
  1. `npm i` to install third party dependencies
11
10
 
12
11
  ## Usage
@@ -15,17 +14,17 @@ Download NW.js and related binaries for Linux, MacOS and Windows.
15
14
  import get from "@nwutils/getter";
16
15
 
17
16
  await get({
18
- version: "latest",
19
- flavor: "normal",
20
- platform: "linux",
21
- arch: "x64",
22
- downloadUrl: "https://dl.nwjs.io",
23
- manifestUrl: "https://nwjs.io/versions.json",
24
- cacheDir: "./cache",
25
- cache: true,
26
- ffmpeg: false,
27
- nativeAddon: false,
28
- shaSum: true,
17
+ version: "latest",
18
+ flavor: "normal",
19
+ platform: "linux",
20
+ arch: "x64",
21
+ downloadUrl: "https://dl.nwjs.io",
22
+ manifestUrl: "https://nwjs.io/versions.json",
23
+ cacheDir: "./cache",
24
+ cache: true,
25
+ ffmpeg: false,
26
+ nativeAddon: false,
27
+ shaSum: true,
29
28
  });
30
29
  ```
31
30
 
@@ -33,22 +32,24 @@ await get({
33
32
 
34
33
  Options
35
34
 
36
- | Name | Type | Description |
37
- | ---- | ------- | ----------- |
38
- | version | `string \| "latest" \| "stable"` | Runtime version |
39
- | flavor | `"normal" \| "sdk"` | Runtime flavor |
40
- | platform | `"linux" \| "osx" \| "win"` | Host platform |
41
- | arch | `"ia32" \| "x64" \| "arm64"` | Host architecture |
35
+ | Name | Type | Description |
36
+ | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
37
+ | version | `string \| "latest" \| "stable"` | Runtime version |
38
+ | flavor | `"normal" \| "sdk"` | Runtime flavor |
39
+ | platform | `"linux" \| "osx" \| "win"` | Host platform |
40
+ | arch | `"ia32" \| "x64" \| "arm64"` | Host architecture |
42
41
  | downloadUrl | `"https://dl.nwjs.io" \| "https://npm.taobao.org/mirrors/nwjs" \| https://npmmirror.com/mirrors/nwjs \| "https://github.com/corwin-of-amber/nw.js/releases/"` | Download server. Supports file systems too (for example `file:///home/user/nwjs_mirror`) |
43
- | manifestUrl | `"https://nwjs.io/versions.json" \| "https://raw.githubusercontent.com/nwutils/nw-builder/main/src/util/osx.arm.versions.json"` | Versions manifest |
44
- | cacheDir | `string` | Directory to cache NW binaries |
45
- | cache | `boolean` | If true the existing cache is used. Otherwise it removes and redownloads it. |
46
- | ffmpeg | `boolean` | If true the chromium ffmpeg is replaced by community version with proprietary codecs. |
47
- | nativeAddon | `boolean` | If true download NW.js Node headers. |
48
- | shaSum | `boolean` | Flag to enable/disable shasum checks. |
42
+ | manifestUrl | `"https://nwjs.io/versions.json" \| "https://raw.githubusercontent.com/nwutils/nw-builder/main/src/util/osx.arm.versions.json"` | Versions manifest |
43
+ | cacheDir | `string` | Directory to cache NW binaries |
44
+ | cache | `boolean` | If true the existing cache is used. Otherwise it removes and redownloads it. |
45
+ | ffmpeg | `boolean` | If true the chromium ffmpeg is replaced by community version with proprietary codecs. |
46
+ | nativeAddon | `boolean` | If true download NW.js Node headers. |
47
+ | shaSum | `boolean` | Flag to enable/disable shasum checks. |
49
48
 
50
49
  ## Contributing
51
50
 
51
+ - [ ] Extract code coverage into seperate action
52
+
52
53
  ### External contributor
53
54
 
54
55
  - Use Node.js standard libraries whenever possible.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nwutils/getter",
3
- "version": "0.2.4",
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",
@@ -39,27 +39,45 @@
39
39
  "url": "git+https://github.com/nwutils/getter.git"
40
40
  },
41
41
  "scripts": {
42
+ "format": "prettier --check .",
43
+ "format:fix": "prettier --write .",
42
44
  "lint": "eslint .",
45
+ "lint:fix": "eslint . --fix",
43
46
  "type": "tsc",
44
47
  "test": "node --test --experimental-test-coverage --test-coverage-exclude=\"tests/**/*\" \"tests/specs/*.test.js\""
45
48
  },
46
- "volta": {
47
- "node": "25.1.0",
48
- "npm": "11.7.0"
49
- },
50
49
  "dependencies": {
51
- "semver": "^7.7.4",
52
- "tar": "^7.5.11",
50
+ "semver": "^7.8.5",
51
+ "tar": "^7.5.22",
53
52
  "yauzl-promise": "^4.0.0"
54
53
  },
55
54
  "devDependencies": {
56
55
  "@eslint/js": "^10.0.1",
57
- "@types/node": "^25.3.3",
58
- "@types/semver": "^7.7.1",
56
+ "@types/node": "^26.4.0",
57
+ "@types/semver": "^7.8.0",
59
58
  "@types/yauzl-promise": "^4.0.1",
60
- "eslint": "^10.0.2",
61
- "eslint-plugin-jsdoc": "^62.7.1",
62
- "globals": "^17.4.0",
63
- "typescript": "^5.9.3"
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",
63
+ "eslint-plugin-simple-import-sort": "^14.0.0",
64
+ "globals": "^17.11.0",
65
+ "prettier": "^3.9.6",
66
+ "typescript": "^7.0.2"
67
+ },
68
+ "devEngines": {
69
+ "runtime": {
70
+ "name": "node",
71
+ "version": "26.1.0",
72
+ "onFail": "warn"
73
+ },
74
+ "packageManager": {
75
+ "name": "npm",
76
+ "version": "12.0.1",
77
+ "onFail": "warn"
78
+ }
79
+ },
80
+ "prettier": {
81
+ "endOfLine": "lf"
64
82
  }
65
83
  }
package/src/decompress.js CHANGED
@@ -1,31 +1,119 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import stream from "node:stream";
1
4
 
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import stream from 'node:stream';
5
+ import * as tar from "tar";
6
+ import yauzl from "yauzl-promise";
5
7
 
6
- import * as tar from 'tar';
7
- import yauzl from 'yauzl-promise';
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;
8
30
 
9
31
  /**
10
32
  * Decompresses a file at `filePath` to `cacheDir` directory.
11
33
  * @async
12
34
  * @function
13
- * @param {string} filePath - file path to compressed binary
14
- * @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}
15
40
  * @throws {Error}
16
41
  * @returns {Promise<void>}
17
42
  */
18
- export default async function decompress(filePath, cacheDir) {
19
- if (filePath.endsWith('.zip')) {
20
- await unzip(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
+
48
+ if (filePath.endsWith(".zip")) {
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);
21
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
22
71
  await tar.extract({
23
72
  file: filePath,
24
- C: cacheDir
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
+ },
25
94
  });
26
95
  }
27
96
  }
28
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
+
29
117
  /**
30
118
  * Get file mode from entry. Reference implementation is [here](https://github.com/fpsqdb/zip-lib/blob/ac447d269218d396e05cd7072d0e9cd82b5ec52c/src/unzip.ts#L380).
31
119
  * @async
@@ -37,7 +125,7 @@ function modeFromEntry(entry) {
37
125
  const attr = entry.externalFileAttributes >> 16 || 33188;
38
126
 
39
127
  return [448 /* S_IRWXU */, 56 /* S_IRWXG */, 7 /* S_IRWXO */]
40
- .map(mask => attr & mask)
128
+ .map((mask) => attr & mask)
41
129
  .reduce((a, b) => a + b, attr & 61440 /* S_IFMT */);
42
130
  }
43
131
 
@@ -45,61 +133,124 @@ function modeFromEntry(entry) {
45
133
  * Unzip `zippedFile` to `cacheDir`.
46
134
  * @async
47
135
  * @function
48
- * @param {string} zippedFile - file path to .zip file
49
- * @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
50
140
  * @throws {Error}
51
141
  * @returns {Promise<void>}
52
142
  */
53
- async function unzip(zippedFile, cacheDir) {
143
+ async function unzip(zippedFile, cacheDir, maxEntries, maxTotalExtractedSize) {
54
144
  const zip = await yauzl.open(zippedFile);
55
- let entry = await zip.readEntry();
56
- /* Array to hold symbolic link entries */
57
- const symlinks = [];
58
-
59
- while (entry !== null) {
60
- let entryPathAbs = path.join(cacheDir, entry.filename);
61
- /* Check if entry is a symbolic link */
62
- const isSymlink = ((modeFromEntry(entry) & 0o170000) === 0o120000);
63
-
64
- if (isSymlink) {
65
- /* Store symlink entries to process later */
66
- symlinks.push(entry);
67
- } else {
68
- /* Handle regular files and directories */
69
- await fs.promises.mkdir(path.dirname(entryPathAbs), {recursive: true});
70
- /* Skip directories */
71
- if (!entry.filename.endsWith('/')) {
72
- const readStream = await entry.openReadStream();
73
- const writeStream = fs.createWriteStream(entryPathAbs);
74
- await stream.promises.pipeline(readStream, writeStream);
75
-
76
- /* Set file permissions after the file has been written */
77
- const mode = modeFromEntry(entry);
78
- 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
+ );
79
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
+ }
199
+ }
200
+
201
+ /* Read next entry */
202
+ entry = await zip.readEntry();
80
203
  }
81
204
 
82
- /* Read next entry */
83
- entry = await zip.readEntry();
84
- }
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
+ );
85
244
 
86
- /* Process symbolic links after all other files have been extracted */
87
- for (const symlinkEntry of symlinks) {
88
- let entryPathAbs = path.join(cacheDir, symlinkEntry.filename);
89
- const readStream = await symlinkEntry.openReadStream();
90
- /** @type {Buffer[]} */
91
- const chunks = [];
92
- readStream.on('data', (chunk) => chunks.push(chunk));
93
- await new Promise(resolve => readStream.on('end', resolve));
94
- const linkTarget = Buffer.concat(chunks).toString('utf8').trim();
95
-
96
- /* Check if the symlink or a file/directory already exists at the destination */
97
- if (fs.existsSync(entryPathAbs)) {
98
- /* skip */
99
- } else {
100
- /* Create symbolic link */
101
- 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
+ }
102
252
  }
253
+ } finally {
254
+ await zip.close();
103
255
  }
104
- await zip.close();
105
256
  }
package/src/ffmpeg.js CHANGED
@@ -1,6 +1,6 @@
1
- import path from 'node:path';
1
+ import path from "node:path";
2
2
 
3
- import request from './request.js';
3
+ import request from "./request.js";
4
4
 
5
5
  /**
6
6
  * Download community FFmpeg binary from `https://github.com/nwjs-ffmpeg-prebuilt/nwjs-ffmpeg-prebuilt`.
@@ -14,26 +14,29 @@ import request from './request.js';
14
14
  * @throws {Error} - When download fails
15
15
  * @returns {Promise<string>} - Path of compressed file which containscommunity FFmpeg binary.
16
16
  */
17
- export default async function ffmpeg(downloadUrl, version, platform, arch, cacheDir) {
17
+ export default async function ffmpeg(
18
+ downloadUrl,
19
+ version,
20
+ platform,
21
+ arch,
22
+ cacheDir,
23
+ ) {
24
+ /**
25
+ * URL to download specific FFmpeg binary from.
26
+ * @type {string}
27
+ */
28
+ const url = [downloadUrl, version, `${version}-${platform}-${arch}.zip`].join(
29
+ "/",
30
+ );
18
31
 
19
- /**
20
- * URL to download specific FFmpeg binary from.
21
- * @type {string}
22
- */
23
- const url = [
24
- downloadUrl,
25
- version,
26
- `${version}-${platform}-${arch}.zip`,
27
- ].join('/');
32
+ /**
33
+ * Absolute path of compressed file which contains FFmpeg binary.
34
+ */
35
+ const ffmpegFileAbs = path.resolve(
36
+ cacheDir,
37
+ `ffmpeg-${version}-${platform}-${arch}.zip`,
38
+ );
28
39
 
29
- /**
30
- * Absolute path of compressed file which contains FFmpeg binary.
31
- */
32
- const ffmpegFileAbs = path.resolve(
33
- cacheDir,
34
- `ffmpeg-${version}-${platform}-${arch}.zip`,
35
- );
36
-
37
- await request(url, ffmpegFileAbs);
38
- return ffmpegFileAbs;
40
+ await request(url, ffmpegFileAbs);
41
+ return ffmpegFileAbs;
39
42
  }
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";
@@ -34,24 +34,41 @@ import verify from "./verify.js";
34
34
  * @returns {Promise<void>}
35
35
  */
36
36
  async function get(options) {
37
-
38
37
  /* If `options.cacheDir` exists, then `true`. Otherwise, it is `false`. */
39
38
  if (fs.existsSync(options.cacheDir) === false) {
40
39
  await fs.promises.mkdir(options.cacheDir, { recursive: true });
41
40
  }
42
41
 
43
42
  const manifestFilePath = path.resolve(options.cacheDir, "manifest.json");
44
- if (options.manifestUrl.startsWith('file://')) {
43
+ if (options.manifestUrl.startsWith("file://")) {
45
44
  const filePath = url.fileURLToPath(options.manifestUrl);
46
- 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);
47
61
  } else {
48
62
  await request(options.manifestUrl, manifestFilePath);
49
63
  }
50
- const manifestData = JSON.parse(await fs.promises.readFile(manifestFilePath, "utf-8"));
64
+ const manifestData = JSON.parse(
65
+ await fs.promises.readFile(manifestFilePath, "utf-8"),
66
+ );
51
67
 
52
- if (options.version === "latest"
53
- || options.version === "stable"
54
- || options.version === "lts"
68
+ if (
69
+ options.version === "latest" ||
70
+ options.version === "stable" ||
71
+ options.version === "lts"
55
72
  ) {
56
73
  options.version = manifestData[options.version].slice(1);
57
74
  } else {
@@ -59,63 +76,121 @@ async function get(options) {
59
76
  if (coerced && semver.valid(coerced)) {
60
77
  options.version = coerced.version;
61
78
  } else {
62
- throw new Error('Expected "options.version" to be "latest", "stable", "lts" or a valid semver version. Received: ' + options.version);
79
+ throw new Error(
80
+ 'Expected "options.version" to be "latest", "stable", "lts" or a valid semver version. Received: ' +
81
+ options.version,
82
+ );
63
83
  }
64
84
  }
65
85
 
66
86
  if (options.flavor !== "normal" && options.flavor !== "sdk") {
67
- throw new Error('Expected "options.flavor" to be "normal" or "sdk". Received: ' + options.flavor);
87
+ throw new Error(
88
+ 'Expected "options.flavor" to be "normal" or "sdk". Received: ' +
89
+ options.flavor,
90
+ );
68
91
  }
69
92
 
70
- if (options.platform !== "linux" && options.platform !== "osx" && options.platform !== "win") {
71
- throw new Error('Expected "options.platform" to be "linux", "osx" or "win". Received: ' + options.platform);
93
+ if (
94
+ options.platform !== "linux" &&
95
+ options.platform !== "osx" &&
96
+ options.platform !== "win"
97
+ ) {
98
+ throw new Error(
99
+ 'Expected "options.platform" to be "linux", "osx" or "win". Received: ' +
100
+ options.platform,
101
+ );
72
102
  }
73
103
 
74
- if (options.arch !== "ia32" && options.arch !== "x64" && options.arch !== "arm64") {
75
- throw new Error('Expected "options.arch" to be "ia32", "x64" or "arm64". Received: ' + options.arch);
104
+ if (
105
+ options.arch !== "ia32" &&
106
+ options.arch !== "x64" &&
107
+ options.arch !== "arm64"
108
+ ) {
109
+ throw new Error(
110
+ 'Expected "options.arch" to be "ia32", "x64" or "arm64". Received: ' +
111
+ options.arch,
112
+ );
76
113
  }
77
114
 
78
115
  if (typeof options.downloadUrl !== "string") {
79
- throw new Error('Expected "options.downloadUrl" to be a string. Received: ' + options.downloadUrl);
116
+ throw new Error(
117
+ 'Expected "options.downloadUrl" to be a string. Received: ' +
118
+ options.downloadUrl,
119
+ );
80
120
  }
81
121
 
82
122
  if (typeof options.manifestUrl !== "string") {
83
- throw new Error('Expected "options.manifestUrl" to be a string. Received: ' + options.manifestUrl);
123
+ throw new Error(
124
+ 'Expected "options.manifestUrl" to be a string. Received: ' +
125
+ options.manifestUrl,
126
+ );
84
127
  }
85
128
 
86
- if (typeof options.manifestUrl == "string"
87
- && options.manifestUrl.startsWith('file://') === false
88
- && options.manifestUrl.startsWith('http://') === false
89
- && options.manifestUrl.startsWith('https://') === false
129
+ if (
130
+ typeof options.manifestUrl == "string" &&
131
+ options.manifestUrl.startsWith("file://") === false &&
132
+ options.manifestUrl.startsWith("http://") === false &&
133
+ options.manifestUrl.startsWith("https://") === false
90
134
  ) {
91
- throw new Error('Expected "options.manifestUrl" to be a string starting with "file://", "http://", or "https://". Received: ' + options.manifestUrl);
135
+ throw new Error(
136
+ 'Expected "options.manifestUrl" to be a string starting with "file://", "http://", or "https://". Received: ' +
137
+ options.manifestUrl,
138
+ );
92
139
  }
93
140
 
94
141
  if (typeof options.cacheDir !== "string") {
95
- throw new Error('Expected "options.cacheDir" to be a string. Received: ' + options.cacheDir);
142
+ throw new Error(
143
+ 'Expected "options.cacheDir" to be a string. Received: ' +
144
+ options.cacheDir,
145
+ );
96
146
  }
97
147
 
98
148
  if (typeof options.cache !== "boolean") {
99
- throw new Error('Expected "options.cache" to be a boolean. Received: ' + options.cache);
149
+ throw new Error(
150
+ 'Expected "options.cache" to be a boolean. Received: ' + options.cache,
151
+ );
100
152
  }
101
153
 
102
154
  if (typeof options.ffmpeg !== "boolean") {
103
- throw new Error('Expected "options.ffmpeg" to be a boolean. Received: ' + options.ffmpeg);
155
+ throw new Error(
156
+ 'Expected "options.ffmpeg" to be a boolean. Received: ' + options.ffmpeg,
157
+ );
104
158
  }
105
159
 
106
160
  if (typeof options.nativeAddon !== "boolean") {
107
- throw new Error('Expected "options.nativeAddon" to be a boolean. Received: ' + options.nativeAddon);
161
+ throw new Error(
162
+ 'Expected "options.nativeAddon" to be a boolean. Received: ' +
163
+ options.nativeAddon,
164
+ );
108
165
  }
109
166
 
110
167
  if (typeof options.shaSum !== "boolean") {
111
- throw new Error('Expected "options.shaSum" to be a boolean. Received: ' + options.shaSum);
168
+ throw new Error(
169
+ 'Expected "options.shaSum" to be a boolean. Received: ' + options.shaSum,
170
+ );
112
171
  }
113
172
 
114
173
  const uri = new url.URL(options.downloadUrl);
115
174
 
116
175
  /* Download server is the cached directory. */
117
176
  if (uri.protocol === "file:") {
118
- options.cacheDir = path.resolve(decodeURIComponent(options.downloadUrl.slice("file://".length)));
177
+ const mirrorDir = path.resolve(
178
+ decodeURIComponent(options.downloadUrl.slice("file://".length)),
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;
119
194
  }
120
195
 
121
196
  /**
@@ -124,7 +199,8 @@ async function get(options) {
124
199
  */
125
200
  let nwFilePath = path.resolve(
126
201
  options.cacheDir,
127
- `nwjs${options.flavor === "sdk" ? "-sdk" : ""}-v${options.version}-${options.platform}-${options.arch}.${options.platform === "linux" ? "tar.gz" : "zip"
202
+ `nwjs${options.flavor === "sdk" ? "-sdk" : ""}-v${options.version}-${options.platform}-${options.arch}.${
203
+ options.platform === "linux" ? "tar.gz" : "zip"
128
204
  }`,
129
205
  );
130
206
 
@@ -153,21 +229,40 @@ async function get(options) {
153
229
 
154
230
  /* If the compressed binary exists, then `true`. Otherwise, it is `false`. */
155
231
  if (fs.existsSync(nwFilePath) === false) {
156
- nwFilePath = await nw(options.downloadUrl, options.version, options.flavor, options.platform, options.arch, options.cacheDir);
232
+ nwFilePath = await nw(
233
+ options.downloadUrl,
234
+ options.version,
235
+ options.flavor,
236
+ options.platform,
237
+ options.arch,
238
+ options.cacheDir,
239
+ );
157
240
  }
158
241
 
159
- 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";
160
252
 
253
+ /* Verify the archive's checksum before extracting its contents. */
161
254
  await verify(
162
- `${options.downloadUrl}/v${options.version}/SHASUMS256.txt`,
255
+ `${checksumHost}/v${options.version}/SHASUMS256.txt`,
163
256
  `${options.cacheDir}/shasum/${options.version}.txt`,
164
257
  options.cacheDir,
165
258
  options.ffmpeg,
166
259
  options.shaSum,
260
+ path.basename(nwFilePath),
167
261
  );
168
262
 
169
- if (options.ffmpeg === true) {
263
+ await decompress(nwFilePath, options.cacheDir);
170
264
 
265
+ if (options.ffmpeg === true) {
171
266
  /**
172
267
  * File path to compressed binary which contains community FFmpeg binary.
173
268
  * @type {string}
@@ -190,7 +285,13 @@ async function get(options) {
190
285
  // Do not update the options.downloadUrl with the ffmpeg URL here. Doing so would lead to error when options.ffmpeg and options.nativeAddon are both enabled.
191
286
  const downloadUrl =
192
287
  "https://github.com/nwjs-ffmpeg-prebuilt/nwjs-ffmpeg-prebuilt/releases/download";
193
- ffmpegFilePath = await ffmpeg(downloadUrl, options.version, options.platform, options.arch, options.cacheDir);
288
+ ffmpegFilePath = await ffmpeg(
289
+ downloadUrl,
290
+ options.version,
291
+ options.platform,
292
+ options.arch,
293
+ options.cacheDir,
294
+ );
194
295
  }
195
296
 
196
297
  await decompress(ffmpegFilePath, options.cacheDir);
@@ -239,18 +340,16 @@ async function get(options) {
239
340
  }
240
341
 
241
342
  await fs.promises.copyFile(ffmpegBinaryPath, ffmpegBinaryDest);
242
-
243
343
  }
244
344
 
245
345
  if (options.nativeAddon === true) {
246
-
247
346
  /**
248
347
  * File path to NW.js Node headers tarball.
249
348
  * @type {string}
250
349
  */
251
350
  let nodeFilePath = path.resolve(
252
351
  options.cacheDir,
253
- `headers-v${options.version}.tar.gz`,
352
+ headersFileName(options.version),
254
353
  );
255
354
 
256
355
  // If `options.cache` is false, then remove the compressed binary.
@@ -263,9 +362,27 @@ async function get(options) {
263
362
 
264
363
  /* If the compressed binary exists, then `true`. Otherwise, it is `false`. */
265
364
  if (fs.existsSync(nodeFilePath) === false) {
266
- nodeFilePath = await node(options.downloadUrl, options.version, options.cacheDir);
365
+ nodeFilePath = await node(
366
+ options.downloadUrl,
367
+ options.version,
368
+ options.cacheDir,
369
+ );
267
370
  }
268
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
+
269
386
  await decompress(nodeFilePath, options.cacheDir);
270
387
  }
271
388
  }
package/src/node.js CHANGED
@@ -1,6 +1,20 @@
1
- import path from 'node:path';
1
+ import path from "node:path";
2
2
 
3
- import request from './request.js';
3
+ import semver from "semver";
4
+
5
+ import request from "./request.js";
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
+ }
4
18
 
5
19
  /**
6
20
  * Download NW.js's Node.js headers.
@@ -13,36 +27,24 @@ import request from './request.js';
13
27
  * @returns {Promise<string>} - path of compressed file which contains the Node headers.
14
28
  */
15
29
  export default async function nw(downloadUrl, version, cacheDir) {
16
-
17
- /**
18
- * Name of directory which contains Node headers.
19
- * @type {string}
20
- */
21
- const nodeDir = `node-v${version}`;
22
-
23
30
  /**
24
- * 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.
25
34
  * @type {string}
26
35
  */
27
- const nwFile = `${nodeDir}.tar.gz`;
36
+ const nwFile = headersFileName(version);
28
37
 
29
38
  /**
30
39
  * URL to download specific Node headers from.
31
40
  * @type {string}
32
41
  */
33
- const url = [
34
- downloadUrl,
35
- `v${version}`,
36
- `nw-headers-v${version}.tar.gz`
37
- ].join('/');
42
+ const url = [downloadUrl, `v${version}`, nwFile].join("/");
38
43
 
39
44
  /**
40
45
  * Absolute path of compressed file which contains Node headers.
41
46
  */
42
- const nwFileAbs = path.resolve(
43
- cacheDir,
44
- nwFile
45
- );
47
+ const nwFileAbs = path.resolve(cacheDir, nwFile);
46
48
 
47
49
  await request(url, nwFileAbs);
48
50
  return nwFileAbs;
package/src/nw.js CHANGED
@@ -1,7 +1,6 @@
1
+ import path from "node:path";
1
2
 
2
- import path from 'node:path';
3
-
4
- import request from './request.js';
3
+ import request from "./request.js";
5
4
 
6
5
  /**
7
6
  * Download NW.js binary.
@@ -16,46 +15,42 @@ import request from './request.js';
16
15
  * @throws {Error} - When download fails
17
16
  * @returns {Promise<string>} - Path of compressed file which contains NW.js binaries.
18
17
  */
19
- export default async function nw(downloadUrl, version, flavor, platform, arch, cacheDir) {
20
-
21
- /**
22
- * Name of directory which contains NW.js binaries.
23
- * @type {string}
24
- */
25
- const nwDir = [
26
- 'nwjs',
27
- flavor === 'sdk' ? '-sdk' : '',
28
- `-v${version}-${platform}-${arch}`,
29
- ].join('');
30
-
31
- /**
32
- * Name of compressed file which contains NW.js binaries.
33
- * @type {string}
34
- */
35
- const nwFile = [
36
- nwDir,
37
- platform === 'linux' ? 'tar.gz' : 'zip'
38
- ].join('.');
39
-
40
- /**
41
- * URL to download specific NW.js binary from.
42
- * @type {string}
43
- */
44
- const url = [
45
- downloadUrl,
46
- `v${version}`,
47
- nwFile,
48
- ].join('/');
49
-
50
- /**
51
- * Absolute path of compressed file which contains NW.js binaries.
52
- */
53
- const nwFileAbs = path.resolve(
54
- cacheDir,
55
- nwFile
56
- );
57
-
58
- await request(url, nwFileAbs);
59
-
60
- return nwFileAbs;
18
+ export default async function nw(
19
+ downloadUrl,
20
+ version,
21
+ flavor,
22
+ platform,
23
+ arch,
24
+ cacheDir,
25
+ ) {
26
+ /**
27
+ * Name of directory which contains NW.js binaries.
28
+ * @type {string}
29
+ */
30
+ const nwDir = [
31
+ "nwjs",
32
+ flavor === "sdk" ? "-sdk" : "",
33
+ `-v${version}-${platform}-${arch}`,
34
+ ].join("");
35
+
36
+ /**
37
+ * Name of compressed file which contains NW.js binaries.
38
+ * @type {string}
39
+ */
40
+ const nwFile = [nwDir, platform === "linux" ? "tar.gz" : "zip"].join(".");
41
+
42
+ /**
43
+ * URL to download specific NW.js binary from.
44
+ * @type {string}
45
+ */
46
+ const url = [downloadUrl, `v${version}`, nwFile].join("/");
47
+
48
+ /**
49
+ * Absolute path of compressed file which contains NW.js binaries.
50
+ */
51
+ const nwFileAbs = path.resolve(cacheDir, nwFile);
52
+
53
+ await request(url, nwFileAbs);
54
+
55
+ return nwFileAbs;
61
56
  }
package/src/request.js CHANGED
@@ -1,24 +1,31 @@
1
- import fs from 'node:fs';
2
- import process from 'node:process';
3
- import http from 'node:http';
4
- import https from 'node:https';
5
- import { URL } from 'node:url';
1
+ import fs from "node:fs";
2
+ import http from "node:http";
3
+ import https from "node:https";
4
+ import process from "node:process";
5
+ import { URL } from "node:url";
6
+
7
+ /**
8
+ * Maximum number of HTTP redirects to follow before giving up.
9
+ * @type {number}
10
+ */
11
+ const MAX_REDIRECTS = 5;
6
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
- const client = parsedUrl.protocol === 'https:' ? https : http;
22
+ const client = parsedUrl.protocol === "https:" ? https : http;
16
23
 
17
24
  return new Promise((resolve, reject) => {
18
25
  const writeStream = fs.createWriteStream(filePath);
19
26
 
20
27
  /* Handle writeStream errors immediately */
21
- writeStream.on('error', (err) => {
28
+ writeStream.on("error", (err) => {
22
29
  cleanup();
23
30
  reject(err);
24
31
  });
@@ -26,57 +33,98 @@ 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
  };
34
- process.once('SIGINT', onSigInt);
48
+ process.once("SIGINT", onSigInt);
35
49
 
36
50
  const req = client.get(
37
51
  {
38
52
  hostname: parsedUrl.hostname,
39
- port: parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80),
53
+ port: parsedUrl.port || (parsedUrl.protocol === "https:" ? 443 : 80),
40
54
  path: parsedUrl.pathname + parsedUrl.search,
41
55
  headers: {
42
- 'User-Agent': 'node:http(s)'
43
- }
56
+ "User-Agent": "node:http(s)",
57
+ },
44
58
  },
45
59
  (res) => {
46
60
  /* Redirect handling */
47
- if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
61
+ if (
62
+ res.statusCode &&
63
+ res.statusCode >= 300 &&
64
+ res.statusCode < 400 &&
65
+ res.headers.location
66
+ ) {
48
67
  cleanup();
49
68
 
50
- const redirectedUrl = new URL(res.headers.location, parsedUrl).toString();
51
- 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
+ );
52
98
  }
53
99
 
54
100
  if (res.statusCode !== 200) {
55
101
  cleanup();
56
- return reject(new Error(`Request failed. Status code: ${res.statusCode}`));
102
+ return reject(
103
+ new Error(`Request failed. Status code: ${res.statusCode}`),
104
+ );
57
105
  }
58
106
 
59
107
  res.pipe(writeStream);
60
108
 
61
- writeStream.on('finish', () => {
109
+ writeStream.on("finish", () => {
62
110
  cleanup();
63
111
  resolve();
64
112
  });
65
113
 
66
- res.on('error', (err) => {
114
+ res.on("error", (err) => {
67
115
  cleanup();
68
116
  reject(err);
69
117
  });
70
- }
118
+ },
71
119
  );
72
120
 
73
- req.on('error', (err) => {
121
+ req.on("error", (err) => {
74
122
  cleanup();
75
123
  reject(err);
76
124
  });
77
125
 
78
126
  function cleanup() {
79
- process.removeListener('SIGINT', onSigInt);
127
+ process.removeListener("SIGINT", onSigInt);
80
128
  req.destroy();
81
129
  writeStream.destroy();
82
130
  }
package/src/verify.js CHANGED
@@ -1,8 +1,8 @@
1
- import crypto from 'node:crypto';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
4
 
5
- import request from './request.js';
5
+ import request from "./request.js";
6
6
 
7
7
  /**
8
8
  * Verify the SHA256 checksum of downloaded artifacts.
@@ -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) {
@@ -28,20 +36,33 @@ export default async function verify(shaUrl, shaOut, cacheDir, ffmpeg, shaSum) {
28
36
  }
29
37
 
30
38
  /* Read SHASUM text file */
31
- const shasum = await fs.promises.readFile(shaOut, { encoding: 'utf-8' });
32
- const shasums = shasum.trim().split('\n');
39
+ const shasum = await fs.promises.readFile(shaOut, { encoding: "utf-8" });
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
- const hash = crypto.createHash('sha256');
53
+ const hash = crypto.createHash("sha256");
40
54
  hash.update(fileBuffer);
41
- const generatedSha = hash.digest('hex');
42
- if (!crypto.timingSafeEqual(Buffer.from(generatedSha, 'hex'), Buffer.from(storedSha, 'hex'))) {
43
- if (filePath.includes('ffmpeg') && ffmpeg) {
44
- console.warn(`The generated shasum for the community ffmpeg at ${filePath} is ${generatedSha}. The integrity of this file should be manually verified.`);
55
+ const generatedSha = hash.digest("hex");
56
+ if (
57
+ !crypto.timingSafeEqual(
58
+ Buffer.from(generatedSha, "hex"),
59
+ Buffer.from(storedSha, "hex"),
60
+ )
61
+ ) {
62
+ if (filePath.includes("ffmpeg") && ffmpeg) {
63
+ console.warn(
64
+ `The generated shasum for the community ffmpeg at ${filePath} is ${generatedSha}. The integrity of this file should be manually verified.`,
65
+ );
45
66
  } else {
46
67
  const message = `SHA256 checksums do not match. The file ${filePath} expected shasum is ${storedSha} but the actual shasum is ${generatedSha}.`;
47
68
  if (shaSum) {
@@ -54,5 +75,20 @@ export default async function verify(shaUrl, shaOut, cacheDir, ffmpeg, shaSum) {
54
75
  }
55
76
  }
56
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
+
57
93
  return true;
58
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/main.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- export default get;
2
1
  export type Options = {
3
2
  /**
4
3
  * Runtime version
@@ -67,3 +66,4 @@ export type Options = {
67
66
  * @returns {Promise<void>}
68
67
  */
69
68
  declare function get(options: Options): Promise<void>;
69
+ export default get;
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>;