bdy 1.25.44-stage → 1.26.0-dev

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.
@@ -1,4 +1,37 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
@@ -10,10 +43,37 @@ const child_process_1 = require("child_process");
10
43
  const node_net_1 = __importDefault(require("node:net"));
11
44
  const sftp_1 = __importDefault(require("./sftp"));
12
45
  const buddy_1 = __importDefault(require("../api/buddy"));
46
+ const node_stream_1 = __importStar(require("node:stream"));
47
+ const promises_1 = require("node:stream/promises");
13
48
  const utils_1 = require("../../utils");
14
49
  const sshChannelWindow_1 = require("../../sshChannelWindow");
15
50
  // The window is applied by the module this comes from, so ssh2 cannot be reached before it ran
16
51
  const ssh2 = (0, sshChannelWindow_1.requireSsh2)();
52
+ // The writing end of a process's stdin, for pipeline() from the client's session. It is a sink of
53
+ // its own rather than the stdin itself because the two sides end in either order, and pipeline
54
+ // would treat the normal one as a failure: a command that exits while the client still has stdin
55
+ // open (`ssh host ls`) closes its stdin first, and a pipeline into that stdin would then destroy
56
+ // the source - the client's session - before its last output and exit status reached it. Writes
57
+ // wait for the stdin's own callback, so a slow process still holds the client back; once the
58
+ // stdin is gone, what is left is dropped. The client's EOF ends the stdin, as pipe() did.
59
+ const stdinSink = (stdin) => new node_stream_1.Writable({
60
+ write(chunk, _enc, cb) {
61
+ if (stdin.destroyed || stdin.writableEnded) {
62
+ cb();
63
+ return;
64
+ }
65
+ stdin.write(chunk, () => cb());
66
+ },
67
+ final(cb) {
68
+ if (!stdin.destroyed && !stdin.writableEnded)
69
+ stdin.end();
70
+ cb();
71
+ },
72
+ });
73
+ // Client session <-> a channel of the proxy session to the local sshd (shell, exec, subsystem).
74
+ // Output goes with pipeline and end:false: the session is ended only once the process's exit status
75
+ // is out ('exit', then 'close' below), and a client that goes away mid-output now takes the proxy
76
+ // channel down with it - pipe() left it open behind a session that no longer existed.
17
77
  const pipeStreamToChannel = (stream, channel) => {
18
78
  channel.once('exit', (code, signal) => {
19
79
  logger_1.default.debug(`shell channel exit: ${code}, signal: ${signal}`);
@@ -27,8 +87,29 @@ const pipeStreamToChannel = (stream, channel) => {
27
87
  channel.on('close', () => {
28
88
  stream.end();
29
89
  });
30
- channel.pipe(stream, { end: false }).pipe(channel);
31
- channel.stderr.pipe(stream.stderr);
90
+ (0, promises_1.pipeline)(channel, stream, { end: false }).catch(() => { });
91
+ (0, promises_1.pipeline)(channel.stderr, stream.stderr, { end: false }).catch(() => { });
92
+ (0, promises_1.pipeline)(stream, stdinSink(channel)).catch(() => {
93
+ // The client went away before its EOF: the process gets no more input either
94
+ try {
95
+ channel.close();
96
+ }
97
+ catch {
98
+ // do nothing
99
+ }
100
+ });
101
+ };
102
+ // How long a local command gets between SIGTERM and SIGKILL once its client is gone
103
+ const LOCAL_EXEC_KILL_GRACE = 5000;
104
+ // Two-way byte bridge for a forwarded connection. pipeline, not pipe(): either side going away
105
+ // tears the other down - pipe() left the channel or the socket open behind a peer that was
106
+ // already gone, holding its file descriptor or its SSH channel. A normal end still only ends
107
+ // the other side's writing half, so half-close works as before.
108
+ const bridge = (a, b) => {
109
+ a.on('error', () => { });
110
+ b.on('error', () => { });
111
+ node_stream_1.default.pipeline(a, b, () => { });
112
+ node_stream_1.default.pipeline(b, a, () => { });
32
113
  };
33
114
  class ServerSsh extends events_1.default {
34
115
  agent;
@@ -74,7 +155,10 @@ class ServerSsh extends events_1.default {
74
155
  compress: ['none', 'zlib@openssh.com'],
75
156
  },
76
157
  }, (client) => this.processClient(client));
77
- this.server.listen();
158
+ // No listen(): every connection arrives through the tunnel and comes in by injectSocket, which
159
+ // only emits 'connection' on ssh2's internal net.Server and needs no listening socket. A bare
160
+ // listen() opened a real ephemeral port on every interface instead - a way into this server
161
+ // around the worker, its IP whitelist and its rate limit, for anyone who could reach the host.
78
162
  }
79
163
  stop() {
80
164
  if (this.server) {
@@ -147,7 +231,13 @@ class ServerSsh extends events_1.default {
147
231
  });
148
232
  }
149
233
  async authenticateClient(ctx) {
150
- const allowed = ['publickey', 'password'];
234
+ // Password login only when the tunnel was given both halves of one. Without them the expected
235
+ // values were '' and checkValueSafe matched two empty buffers, so anyone who reached the
236
+ // tunnel logged in with an empty user and password - into localExec, as the agent's own user.
237
+ const hasPassword = !!this.login && !!this.password;
238
+ const allowed = hasPassword
239
+ ? ['publickey', 'password']
240
+ : ['publickey'];
151
241
  logger_1.default.debug(`auth method: ${ctx.method}`);
152
242
  if (!allowed.includes(ctx.method)) {
153
243
  ctx.reject(allowed);
@@ -188,6 +278,15 @@ class ServerSsh extends events_1.default {
188
278
  ctx.reject(allowed);
189
279
  return null;
190
280
  }
281
+ // The unsigned query (RFC 4252 7) only asks whether this key would do: accept() answers
282
+ // PK_OK and logs nobody in. Nothing past this point may happen for it - the proxy session to
283
+ // sshd as resp.user used to be opened right here and kept for the connection, so a client
284
+ // that then logged in with the password ran as resp.user with only the public key, and every
285
+ // ordinary key login opened a second proxy session that was never closed.
286
+ if (!ctx.signature) {
287
+ ctx.accept();
288
+ return null;
289
+ }
191
290
  logger_1.default.debug('verified');
192
291
  try {
193
292
  const proxyClient = await this.createProxyConnection(privateKey, user);
@@ -237,14 +336,42 @@ class ServerSsh extends events_1.default {
237
336
  }
238
337
  else {
239
338
  opts.shell = true;
339
+ // A process group of its own, so the command can be ended as a whole: the child is the
340
+ // shell, and whatever it starts - `a && b`, a pipeline, or the command itself where the
341
+ // shell does not exec it (dash) - would outlive a signal sent to the shell alone
342
+ opts.detached = true;
240
343
  }
241
344
  try {
242
345
  const proc = (0, child_process_1.spawn)(command, opts);
346
+ let exited = false;
347
+ const killCommand = (signal) => {
348
+ try {
349
+ if (!(0, utils_1.isWindows)() && proc.pid)
350
+ process.kill(-proc.pid, signal);
351
+ else
352
+ proc.kill(signal);
353
+ }
354
+ catch {
355
+ // already gone
356
+ }
357
+ };
358
+ // A client that goes away takes its command with it. pipe() only ended stdin on the client's
359
+ // EOF, so a session that just closed - a dropped tunnel, a killed worker - left the command
360
+ // running with stdin open: one that reads it waited forever, as an orphan of this agent.
361
+ stream.once('close', () => {
362
+ if (exited)
363
+ return;
364
+ killCommand('SIGTERM');
365
+ setTimeout(() => {
366
+ if (!exited)
367
+ killCommand('SIGKILL');
368
+ }, LOCAL_EXEC_KILL_GRACE).unref();
369
+ });
243
370
  if (proc.stdin) {
244
- stream.pipe(proc.stdin);
245
371
  proc.stdin.on('error', () => {
246
372
  // ignore EPIPE on stdin close
247
373
  });
374
+ (0, promises_1.pipeline)(stream, stdinSink(proc.stdin)).catch(() => { });
248
375
  }
249
376
  if (proc.stdout) {
250
377
  proc.stdout.on('data', (data) => {
@@ -257,6 +384,7 @@ class ServerSsh extends events_1.default {
257
384
  });
258
385
  }
259
386
  proc.once('close', (code) => {
387
+ exited = true;
260
388
  stream.exit(code || 0);
261
389
  stream.end();
262
390
  const [seconds, nano] = process.hrtime(s);
@@ -483,6 +611,19 @@ class ServerSsh extends events_1.default {
483
611
  client.on('authentication', async (ctx) => {
484
612
  logger_1.default.debug('ssh authentication');
485
613
  const ac = await this.authenticateClient(ctx);
614
+ // Whatever proxy session an earlier attempt left must not outlive into a login that did not
615
+ // open it: closed before a new one is taken, and dropped when the password is what got in
616
+ if (proxyClient && (ac || (ctx.method === 'password' && ac === undefined))) {
617
+ try {
618
+ proxyClient.removeAllListeners();
619
+ proxyClient.end();
620
+ }
621
+ catch {
622
+ // do nothing
623
+ }
624
+ proxyClient = null;
625
+ globalEnv = {};
626
+ }
486
627
  if (ac) {
487
628
  proxyClient = ac.proxyClient;
488
629
  globalEnv = ac.env;
@@ -498,7 +639,7 @@ class ServerSsh extends events_1.default {
498
639
  return;
499
640
  }
500
641
  const stream = accept();
501
- channel.pipe(stream).pipe(channel);
642
+ bridge(channel, stream);
502
643
  });
503
644
  });
504
645
  }
@@ -529,11 +670,6 @@ class ServerSsh extends events_1.default {
529
670
  host: destIP,
530
671
  port: destPort,
531
672
  });
532
- socket.on('connect', () => {
533
- accepted = true;
534
- const channel = accept();
535
- channel.pipe(socket).pipe(channel);
536
- });
537
673
  const closeSocket = () => {
538
674
  try {
539
675
  socket.removeAllListeners();
@@ -545,6 +681,23 @@ class ServerSsh extends events_1.default {
545
681
  if (!accepted)
546
682
  reject();
547
683
  };
684
+ socket.on('connect', () => {
685
+ accepted = true;
686
+ // The listeners below are for the connect only. Left on, closeSocket's
687
+ // removeAllListeners would strip the bridge's own and leave the channel open
688
+ // after the socket is gone - and their 10s timeout cut every forward that went
689
+ // quiet for 10s, a pooled database connection among them.
690
+ socket.removeListener('timeout', closeSocket);
691
+ socket.removeListener('error', closeSocket);
692
+ socket.removeListener('close', closeSocket);
693
+ // Every byte either way passes through this socket, so its timer is the forward's
694
+ // idle timer. destroy() goes through the bridge and closes the channel with it.
695
+ socket.setTimeout(utils_1.TUNNEL_SSH_FORWARD_IDLE_TIMEOUT);
696
+ socket.once('timeout', () => socket.destroy());
697
+ const channel = accept();
698
+ bridge(channel, socket);
699
+ });
700
+ // How long the target may take to accept the connection
548
701
  socket.setTimeout(10000);
549
702
  socket.on('timeout', closeSocket);
550
703
  socket.on('error', closeSocket);
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const events_1 = __importDefault(require("events"));
7
7
  const logger_1 = __importDefault(require("../../logger"));
8
8
  const texts_1 = require("../../texts");
9
+ const workerHostKey_1 = require("./workerHostKey");
9
10
  const utils_1 = require("../../utils");
10
11
  const sshChannelWindow_1 = require("../../sshChannelWindow");
11
12
  const tunnel_1 = require("../../types/tunnel");
@@ -71,6 +72,7 @@ class SshClient extends events_1.default {
71
72
  }
72
73
  reject(err);
73
74
  });
75
+ const client = this.client;
74
76
  try {
75
77
  this.client.connect({
76
78
  algorithms: {
@@ -87,6 +89,17 @@ class SshClient extends events_1.default {
87
89
  port: this.port,
88
90
  username: this.username,
89
91
  password: this.password,
92
+ // Before the password goes anywhere: the server has to prove it is the worker the manager
93
+ // deployed on this address (workerHostKey.ts). ssh2 keeps the server's identification
94
+ // line on its protocol object - its own SFTP code reads it the same way.
95
+ hostVerifier: (key) => {
96
+ const identRaw = client
97
+ ._protocol?._remoteIdentRaw;
98
+ const ok = (0, workerHostKey_1.verifyWorkerHostKey)(this.ip, key, identRaw);
99
+ if (!ok)
100
+ logger_1.default.error((0, texts_1.LOG_WORKER_HOST_KEY_REJECTED)(this.ip, this.port));
101
+ return ok;
102
+ },
90
103
  });
91
104
  // ssh2 only forwards setNoDelay to a socket it already has, and connect() is what creates
92
105
  // it - called before connect() this was a silent no-op, leaving Nagle on the tunnel. With
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.verifyWorkerHostKey = exports.isLocalWorkerAddress = exports.WORKER_HOST_KEY_CA = void 0;
7
+ const node_crypto_1 = __importDefault(require("node:crypto"));
8
+ const node_net_1 = __importDefault(require("node:net"));
9
+ // Public halves of the keys the manager signs each edge worker's SSH host key with (manager
10
+ // workerHostKey.js). A list so a new key can be added ahead of a rotation.
11
+ exports.WORKER_HOST_KEY_CA = [
12
+ 'MCowBQYDK2VwAyEA2fgQwY2Ey9PRsJKdcAL4cGXkWmrVZsMJTww3lsUVYWE=',
13
+ ].map((der) => node_crypto_1.default.createPublicKey({ key: Buffer.from(der, 'base64'), format: 'der', type: 'spki' }));
14
+ const SIGNATURE = / bdy-sig:([A-Za-z0-9+/=]+)\s*$/;
15
+ // Workers nobody deploys through the manager - a developer's local stack, the e2e one - have no
16
+ // signed key. Only ever reachable on an address of one's own network, so only those are let off.
17
+ const isLocalWorkerAddress = (ip) => {
18
+ if (ip === 'localhost')
19
+ return true;
20
+ const v = node_net_1.default.isIP(ip);
21
+ if (v === 4) {
22
+ const [a, b] = ip.split('.').map(Number);
23
+ return (a === 10 ||
24
+ a === 127 ||
25
+ (a === 172 && b >= 16 && b <= 31) ||
26
+ (a === 192 && b === 168) ||
27
+ (a === 169 && b === 254));
28
+ }
29
+ if (v === 6) {
30
+ const lower = ip.toLowerCase();
31
+ return lower === '::1' || /^f[cd]/.test(lower) || /^fe[89ab]/.test(lower);
32
+ }
33
+ return false;
34
+ };
35
+ exports.isLocalWorkerAddress = isLocalWorkerAddress;
36
+ // Whether the server on `ip` is a worker the manager deployed. Without this the agent accepted any
37
+ // host key and gave its tunnel credentials to whoever answered on the worker's address: anyone on
38
+ // the network path could take the session, relay it to the real worker and read or inject every
39
+ // connection. The signature covers the address and the exact key the server showed, so it proves
40
+ // nothing anywhere else, and it comes in the identification string, which the key exchange hashes
41
+ // and the server's host key signs - it cannot be swapped on the way either.
42
+ const verifyWorkerHostKey = (ip, key, identRaw) => {
43
+ if ((0, exports.isLocalWorkerAddress)(ip))
44
+ return true;
45
+ const m = String(identRaw || '').match(SIGNATURE);
46
+ if (!m)
47
+ return false;
48
+ const message = Buffer.from(`bdy-worker-host-key\n${ip}\n${key.toString('base64')}`);
49
+ const signature = Buffer.from(m[1], 'base64');
50
+ return exports.WORKER_HOST_KEY_CA.some((ca) => {
51
+ try {
52
+ return node_crypto_1.default.verify(null, message, ca, signature);
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ });
58
+ };
59
+ exports.verifyWorkerHostKey = verifyWorkerHostKey;
@@ -49,6 +49,7 @@ const log_1 = __importDefault(require("./http/log"));
49
49
  const auth_1 = __importDefault(require("./http/auth"));
50
50
  const config_1 = __importDefault(require("./config"));
51
51
  const format_1 = __importDefault(require("../format"));
52
+ const node_stream_1 = __importDefault(require("node:stream"));
52
53
  const texts_1 = require("../texts");
53
54
  const dns_1 = __importDefault(require("./dns"));
54
55
  const tunnel_1 = require("../types/tunnel");
@@ -320,7 +321,8 @@ class Tunnel extends events_1.default {
320
321
  res.end(msg);
321
322
  }
322
323
  else {
323
- req.pipe(log.requestBody);
324
+ // pipeline, so a client that goes away mid-body also tears the log copy down
325
+ node_stream_1.default.pipeline(req, log.requestBody, () => { });
324
326
  log.requestBody.pipeToNothing(() => {
325
327
  if (this.httpLog)
326
328
  this.httpLog.newResponse(statusCode, headers, log);
@@ -3,13 +3,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.UNZIPPER_FORMAT = exports.UNZIPPER_ENTRY_TYPE = void 0;
6
+ exports.UNZIPPER_FORMAT = exports.UNZIPPER_ENTRY_TYPE = exports.resolveEntryPath = void 0;
7
7
  const unzipper_1 = __importDefault(require("unzipper"));
8
8
  const tar_stream_1 = __importDefault(require("tar-stream"));
9
9
  const node_zlib_1 = __importDefault(require("node:zlib"));
10
10
  const node_path_1 = __importDefault(require("node:path"));
11
11
  const node_stream_1 = require("node:stream");
12
+ const promises_1 = require("node:stream/promises");
12
13
  const node_fs_1 = __importDefault(require("node:fs"));
14
+ const archivePath_1 = require("./archivePath");
15
+ Object.defineProperty(exports, "resolveEntryPath", { enumerable: true, get: function () { return archivePath_1.resolveEntryPath; } });
13
16
  var UNZIPPER_ENTRY_TYPE;
14
17
  (function (UNZIPPER_ENTRY_TYPE) {
15
18
  UNZIPPER_ENTRY_TYPE["DIRECTORY"] = "Directory";
@@ -30,9 +33,10 @@ const extractZipPathEntry = async (inPath, outPath, onEntry) => {
30
33
  if (onEntry) {
31
34
  await onEntry(name, type);
32
35
  }
33
- const fullPath = node_path_1.default.join(outPath, name);
36
+ const fullPath = (0, archivePath_1.resolveEntryPath)(outPath, name, type === UNZIPPER_ENTRY_TYPE.DIRECTORY);
34
37
  if (type === UNZIPPER_ENTRY_TYPE.DIRECTORY) {
35
- await removePath(fullPath);
38
+ if (!(0, archivePath_1.isDestination)(outPath, fullPath))
39
+ await removePath(fullPath);
36
40
  await createDirectory(fullPath);
37
41
  }
38
42
  else if (type === UNZIPPER_ENTRY_TYPE.FILE) {
@@ -63,101 +67,82 @@ const createDirectory = async (fullPath) => {
63
67
  recursive: true,
64
68
  });
65
69
  };
66
- const extractTarStream = (stream, middle, outPath, onEntry) => {
67
- return new Promise((resolve, reject) => {
68
- const extract = tar_stream_1.default.extract();
69
- const closeStream = (err) => {
70
- if (err)
71
- reject(err);
72
- else
73
- resolve();
74
- resolve = () => {
75
- };
76
- reject = () => {
77
- };
78
- if (stream) {
79
- try {
80
- stream.removeAllListeners();
81
- stream.destroy();
82
- }
83
- catch {
84
- // do nothing
85
- }
86
- }
87
- if (middle) {
88
- try {
89
- middle.removeAllListeners();
90
- middle.close();
91
- }
92
- catch {
93
- // do nothing
94
- }
95
- }
96
- if (extract) {
97
- try {
98
- extract.removeAllListeners();
99
- extract.destroy();
100
- }
101
- catch {
102
- // do nothing
103
- }
104
- }
105
- };
106
- extract.on('entry', async (header, stream, next) => {
107
- let name;
108
- let type;
109
- let str;
110
- if (header && header.type === 'directory') {
111
- type = UNZIPPER_ENTRY_TYPE.DIRECTORY;
112
- name = header.name;
113
- stream.resume();
114
- }
115
- else if (header && header.type === 'file') {
116
- type = UNZIPPER_ENTRY_TYPE.FILE;
117
- name = header.name;
118
- str = stream;
119
- }
120
- else if (header && header.type === 'symlink' && header.linkname) {
121
- type = UNZIPPER_ENTRY_TYPE.FILE;
122
- name = header.name;
123
- stream.resume();
124
- str = streamFromString(header.linkname);
125
- }
126
- else {
127
- stream.resume();
128
- next();
129
- return;
130
- }
131
- if (onEntry) {
132
- await onEntry(name, type);
133
- }
134
- const fullPath = node_path_1.default.join(outPath, name);
135
- if (type === UNZIPPER_ENTRY_TYPE.DIRECTORY) {
136
- await removePath(fullPath);
137
- await createDirectory(fullPath);
138
- }
139
- else if (type === UNZIPPER_ENTRY_TYPE.FILE && str) {
140
- const parentPath = node_path_1.default.resolve(fullPath, '..');
141
- await createDirectory(parentPath);
142
- await removePath(fullPath);
143
- await writeStream(fullPath, stream);
144
- }
145
- next();
146
- });
147
- extract.on('error', (err) => {
148
- closeStream(err);
149
- });
150
- extract.on('finish', () => {
151
- closeStream();
152
- });
153
- middle.on('error', (err) => {
154
- extract.emit('error', err);
155
- });
156
- stream.on('error', (err) => {
157
- extract.emit('error', err);
158
- });
159
- stream.pipe(middle).pipe(extract);
160
- });
70
+ const extractTarEntry = async (entry, outPath, onEntry) => {
71
+ const header = entry.header;
72
+ let name;
73
+ let type;
74
+ let content = null;
75
+ if (header.type === 'directory') {
76
+ type = UNZIPPER_ENTRY_TYPE.DIRECTORY;
77
+ name = header.name;
78
+ entry.resume();
79
+ }
80
+ else if (header.type === 'file') {
81
+ type = UNZIPPER_ENTRY_TYPE.FILE;
82
+ name = header.name;
83
+ // The entry is a streamx stream, and node cannot tell one that is already destroyed - which it
84
+ // is when the archive broke while this was still creating directories - so a write from it
85
+ // would wait for a close that already happened. A node stream in front of it rejects instead.
86
+ content = node_stream_1.Readable.from(entry);
87
+ }
88
+ else if (header.type === 'symlink' && header.linkname) {
89
+ // Not made a link: a link the archive chose could point a later entry anywhere. Its target is
90
+ // written as the file's content instead - what this always meant to do, but it wrote the
91
+ // already drained entry and every such file came out empty.
92
+ type = UNZIPPER_ENTRY_TYPE.FILE;
93
+ name = header.name;
94
+ entry.resume();
95
+ content = streamFromString(header.linkname);
96
+ }
97
+ else {
98
+ entry.resume();
99
+ return;
100
+ }
101
+ if (onEntry) {
102
+ await onEntry(name, type);
103
+ }
104
+ const fullPath = (0, archivePath_1.resolveEntryPath)(outPath, name, type === UNZIPPER_ENTRY_TYPE.DIRECTORY);
105
+ if (type === UNZIPPER_ENTRY_TYPE.DIRECTORY) {
106
+ // `./` - the destination itself: made sure of, never removed
107
+ if (!(0, archivePath_1.isDestination)(outPath, fullPath))
108
+ await removePath(fullPath);
109
+ await createDirectory(fullPath);
110
+ }
111
+ else if (content) {
112
+ const parentPath = node_path_1.default.resolve(fullPath, '..');
113
+ await createDirectory(parentPath);
114
+ await removePath(fullPath);
115
+ await writeStream(fullPath, content);
116
+ }
117
+ };
118
+ // pipeline rather than pipe(): an archive that breaks, or an entry this refuses, takes the file
119
+ // handle and the decompressor down with it instead of leaving them open
120
+ const extractTarStream = async (stream, middle, outPath, onEntry) => {
121
+ const extract = tar_stream_1.default.extract();
122
+ const parsing = (0, promises_1.pipeline)(stream, middle, extract);
123
+ // parsing can reject while an entry is still being handled below, well before it is awaited
124
+ parsing.catch(() => { });
125
+ let entryErr;
126
+ try {
127
+ for await (const entry of extract) {
128
+ await extractTarEntry(entry, outPath, onEntry);
129
+ }
130
+ }
131
+ catch (err) {
132
+ entryErr = err;
133
+ }
134
+ try {
135
+ await parsing;
136
+ }
137
+ catch (err) {
138
+ // A broken archive fails the pipeline first and only then the entry being written, so the
139
+ // pipeline has the cause. The other way round - an entry refused, the loop stopped and
140
+ // destroyed extract - the pipeline only reports a premature close and the entry has the cause.
141
+ if (!entryErr || err.code !== 'ERR_STREAM_PREMATURE_CLOSE')
142
+ throw err;
143
+ }
144
+ if (entryErr)
145
+ throw entryErr;
161
146
  };
162
147
  const extractTarGzPathEntry = async (inPath, outPath, onEntry) => {
163
148
  return await extractTarStream(node_fs_1.default.createReadStream(inPath), node_zlib_1.default.createGunzip(), outPath, onEntry);