amicus 4.9.5 → 4.9.7

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.
@@ -0,0 +1,268 @@
1
+ /**
2
+ * ONE ENTRY of an in-memory archive, and the classified failures every caller
3
+ * acts on.
4
+ *
5
+ * SPLIT OUT of zip-from-buffer.js in the v4.9.6 third round: that file reached
6
+ * the repo's 300-line gate when the symlink-target control and the stall bound
7
+ * grew, and the seam is real. This module answers "what does one archive entry
8
+ * become on disk, and whose fault is it when that fails"; zip-from-buffer.js
9
+ * answers "how is the archive driven, and when do we give up on it". Nothing
10
+ * here knows about yauzl's event loop and nothing there writes a byte.
11
+ *
12
+ * ── ERROR CODES ARE A CAUSAL CLAIM, AND THE CALLER DELETES ON ONE OF THEM ──
13
+ * `UNZIP_BUFFER_FAILED` = the ARCHIVE is bad; it is the ONLY code that lets
14
+ * `electron-repair-cache` evict a user's cached artifact. `UNZIP_DEST_FAILED` =
15
+ * the DESTINATION is bad (no space, a read-only dist/, a path too long, a
16
+ * machine that cannot represent a symlink). `UNZIP_BUFFER_UNAVAILABLE` =
17
+ * neither; yauzl would not load. Every throw in this module goes through one of
18
+ * the three constructors below, so no unclassified error can reach a caller
19
+ * that reads "unclassified" as "the archive is bad" — council finding D2, and
20
+ * the leak that reopened it (a raw stream error out of `collect`) is closed by
21
+ * `collect` tagging its own rejection.
22
+ *
23
+ * @module sidecar/zip-entry-write
24
+ */
25
+
26
+ 'use strict';
27
+
28
+ const path = require('path');
29
+ const zlib = require('zlib');
30
+ const { pipeline } = require('stream/promises');
31
+ const { Transform } = require('stream');
32
+
33
+ const { collapseExcerpt } = require('../utils/text-sanitize');
34
+
35
+ /** @returns {Error} tagged with `code`, sanitized: every throw here is classified. */
36
+ function failure(code, message) {
37
+ return Object.assign(new Error(collapseExcerpt(message)), { code });
38
+ }
39
+
40
+ /** @returns {Error} an archive-is-bad failure: the caller MAY evict the artifact. */
41
+ const badArchive = (message) => failure('UNZIP_BUFFER_FAILED', message);
42
+
43
+ /** @returns {Error} a destination-is-bad failure: the caller must NOT evict anything. */
44
+ const badDestination = (message) => failure('UNZIP_DEST_FAILED', message);
45
+
46
+ /** @returns {Error} the TERMINAL path-traversal refusal, in extract-zip's own
47
+ * `Out of bound path ` wording so unzip.js's UNSAFE_PATTERNS still classifies it. */
48
+ const outOfBound = (where, fileName) => failure('UNZIP_UNSAFE_ARCHIVE', `Out of bound path "${where}" found while processing file ${fileName}`);
49
+
50
+ /**
51
+ * @returns {Error} yauzl would not load. NOT an archive failure and NOT a
52
+ * destination failure: the artifact is fine and so is the disk. unzip.js
53
+ * records the v4.5.2 outage where an undeclared `extract-zip` threw
54
+ * MODULE_NOT_FOUND out of a bare `require` and took a whole function with it;
55
+ * `yauzl` is declared for that reason, and this guard is what stops a hoisting
56
+ * surprise from turning into a DELETED cache entry.
57
+ */
58
+ const extractorUnavailable = (message) => failure('UNZIP_BUFFER_UNAVAILABLE', `the in-memory zip extractor is unavailable: ${message}`);
59
+
60
+ /**
61
+ * Collect a readable fully into one Buffer (a symlink target is a few bytes).
62
+ *
63
+ * CLASSIFIED, like every other throw here. This was the ONE throw site that
64
+ * rejected with the RAW yauzl/stream error, which carries no `code` — and
65
+ * `electron-repair-cache` read an unclassified extract failure as "the archive
66
+ * is bad" and DELETED the user's cached artifact. A read error on a symlink
67
+ * target IS an archive-side failure, so it is named as one rather than left to
68
+ * be guessed at.
69
+ */
70
+ function collect(stream, what) {
71
+ return new Promise((resolve, reject) => {
72
+ const chunks = [];
73
+ stream.on('data', (c) => chunks.push(c));
74
+ stream.on('error', (e) => reject(badArchive(`could not read ${what}: ${(e && e.message) || e}`)));
75
+ stream.on('end', () => resolve(Buffer.concat(chunks)));
76
+ });
77
+ }
78
+
79
+ /** One entry's payload stream, decompressed by yauzl exactly as extract-zip gets it. */
80
+ function entryStream(zipfile, entry) {
81
+ return new Promise((resolve, reject) => {
82
+ zipfile.openReadStream(entry, (err, stream) => {
83
+ if (err) { reject(badArchive(`${entry.fileName}: ${(err && err.message) || err}`)); return; }
84
+ resolve(stream);
85
+ });
86
+ });
87
+ }
88
+
89
+ /**
90
+ * Write one entry, checking its CRC-32 against the archive's own declaration.
91
+ * An INTEGRITY check, not a security control (CRC-32 is linear and forgeable):
92
+ * it catches a broken zlib or bad RAM, and is meaningful only because the
93
+ * whole-buffer sha256 already ran on these exact bytes. yauzl checks no CRC at
94
+ * all; `validateEntrySizes: true` covers the length half.
95
+ *
96
+ * `onBytes` AND `signal` ARE THE STALL BOUND'S TWO HALVES (round 3, seat A1 +
97
+ * B2), and both live here because this is the only function that writes.
98
+ *
99
+ * `onBytes(n)` reports WRITE PROGRESS, which is what the bound is armed against
100
+ * — the caller re-arms on bytes, never on entries, so a single 225 MB
101
+ * `electron.exe` on slow storage cannot look idle. It fires from the CRC
102
+ * transform, the stage immediately upstream of the sink, so it reports bytes the
103
+ * DESTINATION has accepted rather than bytes read out of the buffer. MEASURED
104
+ * (Node 24.18.0) against a sink whose `_write` never calls back: the counter
105
+ * stops, overshooting the sink by exactly one 64 KiB readable-side highWaterMark
106
+ * and no more, whether the wedge happens after 64 KiB or after 640 KiB. A hung
107
+ * destination therefore still stops the counter, which is what makes a genuine
108
+ * stall catchable.
109
+ *
110
+ * `signal` is what makes the bound STOP the work rather than merely report it.
111
+ * `pipeline` destroys every stream on abort — MEASURED: source and sink both
112
+ * `destroyed`, not one further byte counted or accepted — so no write can land
113
+ * after the caller has given up and started cleaning the incoming tree. The
114
+ * rejection it produces is a plain `AbortError` (`pipeline` does not carry the
115
+ * abort reason), which is why the caller keeps its own classified failure and
116
+ * discards this one.
117
+ */
118
+ async function writeEntry({ zipfile, entry, dest, mode, fs, onBytes, signal }) {
119
+ const source = await entryStream(zipfile, entry);
120
+ let crc = 0;
121
+ // Accumulated by a TRANSFORM in the pipeline, never by a `data` listener:
122
+ // attaching one starts the flow before `pipeline` has piped it, losing bytes.
123
+ const crcThrough = new Transform({
124
+ transform(chunk, _enc, cb) {
125
+ crc = zlib.crc32(chunk, crc);
126
+ if (onBytes) { onBytes(chunk.length); }
127
+ cb(null, chunk);
128
+ },
129
+ });
130
+ let sink;
131
+ try {
132
+ sink = fs.createWriteStream(dest, { mode });
133
+ } catch (e) {
134
+ throw badDestination(`could not write ${entry.fileName}: ${(e && e.message) || e}`);
135
+ }
136
+ // WHICH SIDE FAILED FIRST is the causal claim the caller acts on (D2): a bad
137
+ // archive may be evicted, a full disk must never be. `pipeline` destroys the
138
+ // other half after the first error, so both ends usually end up emitting —
139
+ // only the FIRST one recorded says what actually happened.
140
+ let first = null;
141
+ const note = (from) => (e) => { if (!first) { first = { from, e }; } };
142
+ source.on('error', note('archive'));
143
+ sink.on('error', note('dest'));
144
+ try {
145
+ await pipeline(source, crcThrough, sink, ...(signal ? [{ signal }] : []));
146
+ } catch (e) {
147
+ const cause = first ? first.e : e;
148
+ const detail = `${entry.fileName}: ${(cause && cause.message) || cause}`;
149
+ throw first && first.from === 'dest'
150
+ ? badDestination(`could not write ${detail}`)
151
+ : badArchive(`could not inflate ${detail}`);
152
+ }
153
+ if ((crc >>> 0) !== (entry.crc32 >>> 0)) {
154
+ throw badArchive(`crc32 mismatch for ${entry.fileName}`);
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Create one symlink, refusing a target that resolves outside `root`.
160
+ *
161
+ * `canonical` is `realpathSync` of the directory the link is ACTUALLY created
162
+ * in — never `path.dirname(dest)`. That distinction is the whole control, and
163
+ * getting it wrong was MEASURED to defeat the check completely: three entries
164
+ * naming `L0`, `L0/L1`, `L0/L1/L2`, each a symlink to `.`, make the LEXICAL
165
+ * dirname `<root>/L0/L1/L2` three levels deeper than the real one (`<root>`),
166
+ * so a fourth entry `L0/L1/L2/x -> ../../../victim` resolved to `<root>/victim`
167
+ * — inside, accepted — while the link really landed at `<root>/../../../victim`.
168
+ * Escape depth tracked chain length 1:1. Every one of those names passes
169
+ * yauzl's `validateFileName`, so one ordinary-looking archive was arbitrary
170
+ * same-user file write outside the extraction root.
171
+ *
172
+ * WHAT THIS DOES AND DOES NOT PROMISE. It resolves the target from the real
173
+ * directory and refuses anything that leaves `root`; it does NOT follow
174
+ * symlinks inside the target's own intermediate components, so a link pointing
175
+ * at an in-root path that some LATER entry turns into a link elsewhere is not
176
+ * caught here — that shape is caught by the per-entry `realpath` bound check in
177
+ * `placeEntry`, which re-runs after every earlier entry has been written.
178
+ *
179
+ * `signal` is checked immediately before the `symlinkSync`. A link target is a
180
+ * handful of bytes read through `collect`, which is not a `pipeline` and so is
181
+ * not destroyed by the abort — without this check the stall bound could fire and
182
+ * a symlink still appear in the tree the caller is about to delete.
183
+ */
184
+ async function writeSymlink({ zipfile, entry, canonical, root, fs, signal }) {
185
+ const target = (await collect(await entryStream(zipfile, entry), `the symlink target for ${entry.fileName}`)).toString('utf8');
186
+ const dest = path.join(canonical, path.basename(entry.fileName));
187
+ const resolved = path.resolve(canonical, target);
188
+ const rel = path.relative(root, resolved);
189
+ // SYMLINKESCAPE: `..` at the head, or an absolute answer (a different Windows
190
+ // drive), means the link points out of the tree amicus is allowed to write.
191
+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
192
+ throw outOfBound(resolved, entry.fileName);
193
+ }
194
+ if (signal && signal.aborted) { return; }
195
+ try {
196
+ fs.symlinkSync(target, dest);
197
+ } catch (e) {
198
+ throw badDestination(`could not create the symlink ${entry.fileName}: ${(e && e.message) || e}`);
199
+ }
200
+ }
201
+
202
+ /** stat mode constants, as extract-zip decodes them from externalFileAttributes. */
203
+ const IFMT = 61440;
204
+ const IFDIR = 16384;
205
+ const IFLNK = 40960;
206
+
207
+ /** extract-zip's getExtractedMode, with its 0755/0644 defaults. */
208
+ function extractedMode(entryMode, isDir) {
209
+ if (entryMode !== 0) { return entryMode; }
210
+ return isDir ? 0o755 : 0o644;
211
+ }
212
+
213
+ /**
214
+ * One entry, mirroring extract-zip's Extractor.extractEntry decision order.
215
+ *
216
+ * MOVED HERE from zip-from-buffer.js in the third council round, when the stall
217
+ * bound's repair pushed that file back over the 300-line gate. It is not a
218
+ * convenience move: this function answers "what does one archive entry become on
219
+ * disk, and whose fault is it when that fails", which is this module's whole
220
+ * subject, and it calls nothing but this module's own writers. What stays next
221
+ * door is the archive DRIVER — yauzl's event loop, the bound, and the decision
222
+ * to give up.
223
+ *
224
+ * `signal` is the stall bound's halt: an entry that arrives after the bound
225
+ * fired creates NOTHING — not the directory, not the file — because the caller
226
+ * is already deleting the incoming tree.
227
+ * @returns {Promise<boolean>} true if the entry was placed (false = skipped)
228
+ */
229
+ async function placeEntry({ zipfile, entry, root, fs, signal, onBytes }) {
230
+ // Nothing is created for an entry that arrives after the bound fired.
231
+ if (signal && signal.aborted) { return false; }
232
+ if (entry.fileName.startsWith('__MACOSX/')) { return false; }
233
+ if (entry.isEncrypted()) { throw badArchive(`${entry.fileName} is encrypted`); }
234
+ const dest = path.join(root, entry.fileName);
235
+ const mode = (entry.externalFileAttributes >> 16) & 0xFFFF;
236
+ const symlink = (mode & IFMT) === IFLNK;
237
+ let isDir = (mode & IFMT) === IFDIR;
238
+ if (!isDir && entry.fileName.endsWith('/')) { isDir = true; }
239
+ if (!isDir) { isDir = ((entry.versionMadeBy >> 8) === 0 && entry.externalFileAttributes === 16); }
240
+ const procMode = extractedMode(mode, isDir) & 0o777;
241
+ const destDir = isDir ? dest : path.dirname(dest);
242
+ let canonical;
243
+ try {
244
+ fs.mkdirSync(destDir, isDir ? { recursive: true, mode: procMode } : { recursive: true });
245
+ canonical = fs.realpathSync(destDir);
246
+ } catch (e) {
247
+ throw badDestination(`could not create ${destDir}: ${(e && e.message) || e}`);
248
+ }
249
+ // extract-zip's check, VERBATIM — re-run per entry, AFTER earlier entries were
250
+ // written, so a symlink an earlier entry created cannot redirect a later one.
251
+ if (path.relative(root, canonical).split(path.sep).includes('..')) {
252
+ throw outOfBound(canonical, entry.fileName);
253
+ }
254
+ if (isDir) { return true; }
255
+ if (symlink) {
256
+ // `canonical`, NEVER `dest`: the link's target is resolved against the
257
+ // directory realpath says it is created in (see writeSymlink).
258
+ await writeSymlink({ zipfile, entry, canonical, root, fs, signal });
259
+ } else {
260
+ await writeEntry({ zipfile, entry, dest, mode: procMode, fs, onBytes, signal });
261
+ }
262
+ return true;
263
+ }
264
+
265
+ module.exports = {
266
+ failure, badArchive, badDestination, outOfBound, extractorUnavailable,
267
+ collect, entryStream, writeEntry, writeSymlink, placeEntry,
268
+ };
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Extract an archive that is ALREADY IN MEMORY and ALREADY HASHED.
3
+ *
4
+ * There is no `zip` parameter because there is no file. The bytes arrive as a
5
+ * Buffer that `electron-custody.readArtifactBytes` read through a single
6
+ * descriptor and that `electron-trust.verifyArtifactBytes` hashed; nothing here
7
+ * resolves a path to the artifact, so there is no second read for a same-uid
8
+ * attacker to race. `electron-custody.js` carries the measured refutations of
9
+ * the two remedies this replaces. NO HAND-WRITTEN ZIP PARSING: a council judge
10
+ * killed a design that sliced local file headers by hand — "a terminal path with
11
+ * no rescue", since it would have had to re-derive ZIP64 local headers, data
12
+ * descriptors and the central-vs-local size disagreement `openReadStream`
13
+ * already handles. Every byte offset comes from `yauzl.openReadStream`, exactly
14
+ * as under extract-zip; only WHERE yauzl reads from changes.
15
+ *
16
+ * ── THE `autoClose` TRAP, MEASURED ────────────────────────────────────────
17
+ * `yauzl.fromBuffer` sets `options.autoClose = false` UNCONDITIONALLY
18
+ * (yauzl@2.10.0 index.js, line 67) — an explicit `{autoClose: true}` is silently
19
+ * discarded — and `extract-zip` resolves on the zipfile's `'close'` event
20
+ * (extract-zip@2.0.1 index.js, lines 32-37), so a naive port of extract-zip onto
21
+ * a buffer HANGS FOREVER. Both council judges hit it. MEASURED on the installed
22
+ * libraries (Windows 11, Node 24.18.0) it is worse than the brief recorded:
23
+ * `ZipFile.close()` only calls `reader.unref()`, and fd-slicer's BufferSlicer
24
+ * has no close and emits nothing on unref (fd-slicer index.js, lines 282-288)
25
+ * where FdSlicer closes the fd and emits `'close'` — so under `fromBuffer` that
26
+ * event is UNREACHABLE even if you call `close()` (500 ms after END fired, close
27
+ * had not). THE FIX, stated so nobody "tidies" it: this module resolves on
28
+ * `'end'`, which yauzl emits once the central directory is exhausted, and drives
29
+ * `readEntry()` only after the previous entry has been fully written, so `'end'`
30
+ * cannot arrive before the last write lands. `close()` is still called, for the
31
+ * reader refcount, but NOTHING waits on it. Pinned by YAUZLHANG.
32
+ *
33
+ * ── PARITY WITH extract-zip, AND THE ONE DELIBERATE DIFFERENCE ────────────
34
+ * The per-entry decisions all live in `./zip-entry-write :: placeEntry` now, and
35
+ * the `__MACOSX/` skip, the mode decode, both directory failsafes, the 0755/0644
36
+ * defaults and the per-entry `realpath(destDir)` out-of-bound check with its
37
+ * message VERBATIM are copied from extract-zip@2.0.1 index.js, lines 48-160, so
38
+ * `UNSAFE_PATTERNS` and `electron-refuse.isUnsafeArchive` classify exactly what
39
+ * they classified. The difference: a SYMLINK whose target resolves outside the
40
+ * extraction root is REFUSED here and is not by extract-zip, and it is resolved
41
+ * against the REALPATH of the directory the link lands in because the lexical
42
+ * `path.dirname` was measured to be defeated outright by a chain of
43
+ * directory-symlink entries earlier in the same archive. It is refused in the
44
+ * same `Out of bound path` wording and exercised against synthetic archives
45
+ * here; the darwin `.app` bundle is the only electron artifact with real
46
+ * symlinks, and since v4.9.7 `.github/workflows/darwin-bundle.yml` runs this
47
+ * path over the REAL artifact on a real Mac. The v4.9.6 worry that the check
48
+ * might REJECT a working layout is refuted by measurement: the real
49
+ * `electron-v43.1.1-darwin-arm64.zip` declares 585 records and 14 symlinks,
50
+ * every target relative, none carrying a `..` component, none absolute, and 0
51
+ * of the 585 entry names traversing a symlinked component. The linux artifacts
52
+ * hold ZERO symlink entries, so `writeSymlink` is unreachable there at all.
53
+ *
54
+ * `root = fs.realpathSync(dir)` below is load-bearing for that answer and no
55
+ * Windows probe would ever show it: on macOS the extraction root usually sits
56
+ * under `/var`, which is itself a symlink to `/private/var`, so comparing a
57
+ * resolved target against an UNRESOLVED root would read every link in a real
58
+ * `.app` as an escape.
59
+ *
60
+ * ── ERROR CODES ARE A CAUSAL CLAIM ───────────────────────────────────────
61
+ * `UNZIP_BUFFER_FAILED` = the ARCHIVE is bad. `UNZIP_DEST_FAILED` = the
62
+ * DESTINATION is (no space, a read-only dist, a path too long).
63
+ * `UNZIP_BUFFER_UNAVAILABLE` = neither, yauzl would not load.
64
+ * `UNZIP_BUFFER_STALLED` = no progress inside the bound; nobody learned anything
65
+ * about the archive OR the disk. The caller evicts on `UNZIP_BUFFER_FAILED`
66
+ * ONLY (finding D2). The constructors and the writers live in `./zip-entry-write`;
67
+ * `UNZIP_BUFFER_STALLED` and the windows that raise it live in `./zip-stall-bound`.
68
+ *
69
+ * @module sidecar/zip-from-buffer
70
+ */
71
+
72
+ 'use strict';
73
+
74
+ const fsDefault = require('fs');
75
+ const path = require('path');
76
+
77
+ // The classified failures, and `placeEntry` — everything that decides what ONE
78
+ // entry becomes on disk. THE ONE-WAY ARROW: zip-from-buffer -> zip-entry-write,
79
+ // never back. `placeEntry` moved across that seam in the third council round,
80
+ // when this file hit the 300-line gate again: it answers "what does one entry
81
+ // become on disk", which is the neighbouring module's whole subject, while what
82
+ // stays here is "how is the archive DRIVEN, and when do we give up on it".
83
+ const {
84
+ failure, badArchive, badDestination, extractorUnavailable, placeEntry,
85
+ } = require('./zip-entry-write');
86
+ // THE GIVE-UP POLICY, and the whole record of how it has been wrong: the two
87
+ // windows, the bounded wait for an aborted write to come apart, and the
88
+ // classified failure. Read `./zip-stall-bound` before touching any of it.
89
+ const {
90
+ IDLE_MS, MAX_MS, UNWIND_MS, stalled, awaitUnwind,
91
+ } = require('./zip-stall-bound');
92
+
93
+ /** yauzl's own validateFileName refusals — three of unzip.js's UNSAFE_PATTERNS. */
94
+ const NAME_REFUSAL = /^(absolute path|invalid relative path|invalid characters in fileName): /;
95
+
96
+ /** yauzl's callback API as a promise, with `fromBuffer`'s options pinned here. */
97
+ function openBuffer(yauzl, bytes) {
98
+ return new Promise((resolve, reject) => {
99
+ yauzl.fromBuffer(bytes, { lazyEntries: true, validateEntrySizes: true }, (err, zipfile) => {
100
+ if (err) { reject(badArchive(`could not read the archive: ${(err && err.message) || err}`)); return; }
101
+ resolve(zipfile);
102
+ });
103
+ });
104
+ }
105
+
106
+ /**
107
+ * Extract `bytes` into `dir`. The caller has ALREADY hashed `bytes`.
108
+ *
109
+ * BOUNDED, AND EVERY WAIT IN IT IS BOUNDED. See `./zip-stall-bound`, which
110
+ * carries the whole record: an idle watchdog armed against BYTES WRITTEN (not entries completed),
111
+ * a hard cap, and a bounded wait for the aborted write to unwind — each one a
112
+ * live `setTimeout` handle, so a write that never completes becomes a catchable
113
+ * rejection instead of a promise that never settles, and SOME handle is alive
114
+ * for the whole of it, which is what stops Node exiting 0 mid-stall with a
115
+ * partial extract and no message. When a bound fires it ABORTS the in-flight
116
+ * write first, so no byte lands after the failure is decided; it then waits up
117
+ * to `unwindMs` for that write to come apart, and throws whether or not it did.
118
+ *
119
+ * @param {Buffer} bytes the whole archive, in this process's heap
120
+ * @param {object} o
121
+ * @param {string} o.dir absolute destination (created if absent)
122
+ * @param {number} [o.idleMs] no-progress window before the extract is stalled
123
+ * @param {number} [o.maxMs] hard cap on the whole extraction
124
+ * @param {number} [o.unwindMs] how long an aborted write may take to come apart
125
+ * @param {object} [o.deps] { fs, yauzl, log, setTimeout, clearTimeout }
126
+ * @returns {Promise<{strategy:'buffer', entries:number}>}
127
+ * @throws {Error} code 'UNZIP_UNSAFE_ARCHIVE' — terminal; never retried
128
+ * @throws {Error} code 'UNZIP_BUFFER_FAILED' — the archive is bad
129
+ * @throws {Error} code 'UNZIP_DEST_FAILED' — the destination is bad
130
+ * @throws {Error} code 'UNZIP_BUFFER_UNAVAILABLE' — yauzl could not be loaded
131
+ * @throws {Error} code 'UNZIP_BUFFER_STALLED' — no progress; NOT an artifact verdict
132
+ */
133
+ async function extractZipBuffer(bytes, {
134
+ dir, idleMs = IDLE_MS, maxMs = MAX_MS, unwindMs = UNWIND_MS, deps = {},
135
+ } = {}) {
136
+ const fs = deps.fs || fsDefault;
137
+ const setTimer = deps.setTimeout || setTimeout;
138
+ const clearTimer = deps.clearTimeout || clearTimeout;
139
+ // GUARDED (the v4.5.2 lesson). `yauzl` IS declared in package.json; the guard
140
+ // keeps a broken install a refusal rather than a deleted cache entry.
141
+ let yauzl = deps.yauzl;
142
+ if (!yauzl) {
143
+ try { yauzl = require('yauzl'); } catch (e) { throw extractorUnavailable((e && e.message) || String(e)); }
144
+ }
145
+ if (!path.isAbsolute(dir)) { throw badDestination('Target directory is expected to be absolute'); }
146
+ let root;
147
+ try {
148
+ fs.mkdirSync(dir, { recursive: true });
149
+ root = fs.realpathSync(dir);
150
+ } catch (e) {
151
+ throw badDestination(`could not prepare ${dir}: ${(e && e.message) || e}`);
152
+ }
153
+
154
+ const zipfile = await openBuffer(yauzl, bytes);
155
+ let entries = 0;
156
+ let written = 0; // BYTES the destination accepted — the progress signal
157
+ let idleTimer = null;
158
+ let maxTimer = null;
159
+ let inFlight = null; // the entry being written when the bound fires
160
+ const halt = new AbortController();
161
+ const cancelTimers = () => {
162
+ if (idleTimer !== null) { clearTimer(idleTimer); idleTimer = null; }
163
+ if (maxTimer !== null) { clearTimer(maxTimer); maxTimer = null; }
164
+ };
165
+ let thrown = null;
166
+ try {
167
+ await new Promise((resolve, reject) => {
168
+ let settled = false;
169
+ const finish = (fn, value) => {
170
+ if (settled) { return; }
171
+ settled = true;
172
+ cancelTimers();
173
+ fn(value);
174
+ };
175
+ // STOP THE WORK FIRST, THEN REPORT IT. A control that reports a failure
176
+ // while the work continues is not a control (round 3, seat A1): the abort
177
+ // destroys the in-flight pipeline, and `placeEntry`/`writeSymlink` refuse
178
+ // to start or finish anything once the signal is set.
179
+ const fail = (e) => {
180
+ if (!halt.signal.aborted) { halt.abort(e); }
181
+ finish(reject, e);
182
+ };
183
+ // The idle WATCHDOG re-arms itself from the marks it took, so a single
184
+ // huge entry that is writing steadily is progress and never a stall.
185
+ const armIdle = () => {
186
+ const atBytes = written;
187
+ const atEntries = entries;
188
+ idleTimer = setTimer(() => {
189
+ if (written !== atBytes || entries !== atEntries) { armIdle(); return; }
190
+ fail(stalled(`no extract progress for ${idleMs}ms`));
191
+ }, idleMs);
192
+ };
193
+ maxTimer = setTimer(() => fail(stalled(`extraction exceeded ${maxMs}ms`)), maxMs);
194
+ armIdle();
195
+ // yauzl's own validateFileName refusals ('absolute path: ', 'invalid
196
+ // relative path: ', 'invalid characters in fileName: ') arrive here.
197
+ zipfile.on('error', (e) => fail(failure(
198
+ NAME_REFUSAL.test((e && e.message) || '') ? 'UNZIP_UNSAFE_ARCHIVE' : 'UNZIP_BUFFER_FAILED',
199
+ (e && e.message) || 'the archive could not be read',
200
+ )));
201
+ // RESOLVE ON 'end', NEVER ON 'close' — see the docblock. `close` is
202
+ // unreachable under fromBuffer, so waiting for it hangs forever.
203
+ zipfile.on('end', () => finish(resolve));
204
+ zipfile.on('entry', (entry) => {
205
+ inFlight = placeEntry({
206
+ zipfile, entry, root, fs, signal: halt.signal, onBytes: (n) => { written += n; },
207
+ });
208
+ inFlight.then((placed) => {
209
+ if (settled) { return; } // the bound already fired; stop driving
210
+ if (placed) { entries += 1; }
211
+ zipfile.readEntry();
212
+ }, fail);
213
+ });
214
+ zipfile.readEntry();
215
+ });
216
+ } catch (e) {
217
+ thrown = e;
218
+ } finally {
219
+ cancelTimers();
220
+ // The abort has been issued; give the destroyed pipeline a BOUNDED window to
221
+ // unwind, so the caller's cleanup (extractBytesToDist deletes the incoming
222
+ // tree in its own `finally`) does not usually race an open descriptor — and
223
+ // so a pipeline that can never unwind cannot hang this call. Round 4.
224
+ if (inFlight) { await awaitUnwind(inFlight, unwindMs, setTimer, clearTimer); }
225
+ try { zipfile.close(); } catch { /* the buffer reader holds no fd */ }
226
+ }
227
+ if (thrown) { throw thrown; }
228
+ return { strategy: 'buffer', entries };
229
+ }
230
+
231
+ module.exports = { extractZipBuffer };