@bitwarden/cli 2026.5.0 → 2026.7.0

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 ADDED
@@ -0,0 +1,68 @@
1
+ [![Github Workflow build on main](https://github.com/bitwarden/clients/actions/workflows/build-cli.yml/badge.svg?branch=main)](https://github.com/bitwarden/clients/actions/workflows/build-cli.yml?query=branch:main)
2
+
3
+ # Bitwarden Command-line Interface
4
+
5
+ [![Platforms](https://imgur.com/AnTLX0S.png "Platforms")](https://help.bitwarden.com/article/cli/#download--install)
6
+
7
+ The Bitwarden CLI is a powerful, full-featured command-line interface (CLI) tool to access and manage a Bitwarden vault. The CLI is written with TypeScript and Node.js and can be run on Windows, macOS, and Linux distributions.
8
+
9
+ ## Developer Documentation
10
+
11
+ Please refer to the [CLI section](https://contributing.bitwarden.com/getting-started/clients/cli/) of the [Contributing Documentation](https://contributing.bitwarden.com/) for build instructions, recommended tooling, code style tips, and lots of other great information to get you started.
12
+
13
+ ## User Documentation
14
+
15
+ ### Download/Install
16
+
17
+ You can install the Bitwarden CLI multiple different ways:
18
+
19
+ **NPM**
20
+
21
+ If you already have the Node.js runtime installed on your system, you can install the CLI using NPM. NPM makes it easy to keep your installation updated and should be the preferred installation method if you are already using Node.js.
22
+
23
+ ```bash
24
+ npm install -g @bitwarden/cli
25
+ ```
26
+
27
+ **Native Executable**
28
+
29
+ We provide natively packaged versions of the CLI for each platform which have no requirements on installing the Node.js runtime. You can obtain these from the [downloads section](https://help.bitwarden.com/article/cli/#download--install) in the documentation.
30
+
31
+ **Other Package Managers**
32
+
33
+ - [Chocolatey](https://chocolatey.org/packages/bitwarden-cli)
34
+ ```powershell
35
+ choco install bitwarden-cli
36
+ ```
37
+ - [Homebrew](https://formulae.brew.sh/formula/bitwarden-cli)
38
+ ```bash
39
+ brew install bitwarden-cli
40
+ ```
41
+ > ⚠️ The homebrew version is not recommended for all users.
42
+ >
43
+ > Homebrew pulls the CLI's GPL build and does not include device approval commands for Enterprise SSO customers.
44
+ - [Snap](https://snapcraft.io/bw)
45
+ ```bash
46
+ sudo snap install bw
47
+ ```
48
+
49
+ ### Help Command
50
+
51
+ The Bitwarden CLI is self-documented with `--help` content and examples for every command. You should start exploring the CLI by using the global `--help` option:
52
+
53
+ ```bash
54
+ bw --help
55
+ ```
56
+
57
+ This option will list all available commands that you can use with the CLI.
58
+
59
+ Additionally, you can run the `--help` option on a specific command to learn more about it:
60
+
61
+ ```bash
62
+ bw list --help
63
+ bw create --help
64
+ ```
65
+
66
+ ### Help Center
67
+
68
+ We provide detailed documentation and examples for using the CLI in our help center at https://help.bitwarden.com/article/cli/.
package/build/344.js ADDED
@@ -0,0 +1,623 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ exports.id = 344;
4
+ exports.ids = [344];
5
+ exports.modules = {
6
+
7
+ /***/ 53
8
+ (__unused_webpack_module, exports, __webpack_require__) {
9
+
10
+
11
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ var desc = Object.getOwnPropertyDescriptor(m, k);
14
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
+ desc = { enumerable: true, get: function() { return m[k]; } };
16
+ }
17
+ Object.defineProperty(o, k2, desc);
18
+ }) : (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ o[k2] = m[k];
21
+ }));
22
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
24
+ }) : function(o, v) {
25
+ o["default"] = v;
26
+ });
27
+ var __importStar = (this && this.__importStar) || function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
35
+ exports.req = exports.json = exports.toBuffer = void 0;
36
+ const http = __importStar(__webpack_require__(611));
37
+ const https = __importStar(__webpack_require__(692));
38
+ async function toBuffer(stream) {
39
+ let length = 0;
40
+ const chunks = [];
41
+ for await (const chunk of stream) {
42
+ length += chunk.length;
43
+ chunks.push(chunk);
44
+ }
45
+ return Buffer.concat(chunks, length);
46
+ }
47
+ exports.toBuffer = toBuffer;
48
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
+ async function json(stream) {
50
+ const buf = await toBuffer(stream);
51
+ const str = buf.toString('utf8');
52
+ try {
53
+ return JSON.parse(str);
54
+ }
55
+ catch (_err) {
56
+ const err = _err;
57
+ err.message += ` (input: ${str})`;
58
+ throw err;
59
+ }
60
+ }
61
+ exports.json = json;
62
+ function req(url, opts = {}) {
63
+ const href = typeof url === 'string' ? url : url.href;
64
+ const req = (href.startsWith('https:') ? https : http).request(url, opts);
65
+ const promise = new Promise((resolve, reject) => {
66
+ req
67
+ .once('response', resolve)
68
+ .once('error', reject)
69
+ .end();
70
+ });
71
+ req.then = promise.then.bind(promise);
72
+ return req;
73
+ }
74
+ exports.req = req;
75
+ //# sourceMappingURL=helpers.js.map
76
+
77
+ /***/ },
78
+
79
+ /***/ 112
80
+ (__unused_webpack_module, exports, __webpack_require__) {
81
+
82
+
83
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
84
+ if (k2 === undefined) k2 = k;
85
+ var desc = Object.getOwnPropertyDescriptor(m, k);
86
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
87
+ desc = { enumerable: true, get: function() { return m[k]; } };
88
+ }
89
+ Object.defineProperty(o, k2, desc);
90
+ }) : (function(o, m, k, k2) {
91
+ if (k2 === undefined) k2 = k;
92
+ o[k2] = m[k];
93
+ }));
94
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
95
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
96
+ }) : function(o, v) {
97
+ o["default"] = v;
98
+ });
99
+ var __importStar = (this && this.__importStar) || function (mod) {
100
+ if (mod && mod.__esModule) return mod;
101
+ var result = {};
102
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
103
+ __setModuleDefault(result, mod);
104
+ return result;
105
+ };
106
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
107
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
108
+ };
109
+ Object.defineProperty(exports, "__esModule", ({ value: true }));
110
+ exports.Agent = void 0;
111
+ const net = __importStar(__webpack_require__(278));
112
+ const http = __importStar(__webpack_require__(611));
113
+ const https_1 = __webpack_require__(692);
114
+ __exportStar(__webpack_require__(53), exports);
115
+ const INTERNAL = Symbol('AgentBaseInternalState');
116
+ class Agent extends http.Agent {
117
+ constructor(opts) {
118
+ super(opts);
119
+ this[INTERNAL] = {};
120
+ }
121
+ /**
122
+ * Determine whether this is an `http` or `https` request.
123
+ */
124
+ isSecureEndpoint(options) {
125
+ if (options) {
126
+ // First check the `secureEndpoint` property explicitly, since this
127
+ // means that a parent `Agent` is "passing through" to this instance.
128
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
129
+ if (typeof options.secureEndpoint === 'boolean') {
130
+ return options.secureEndpoint;
131
+ }
132
+ // If no explicit `secure` endpoint, check if `protocol` property is
133
+ // set. This will usually be the case since using a full string URL
134
+ // or `URL` instance should be the most common usage.
135
+ if (typeof options.protocol === 'string') {
136
+ return options.protocol === 'https:';
137
+ }
138
+ }
139
+ // Finally, if no `protocol` property was set, then fall back to
140
+ // checking the stack trace of the current call stack, and try to
141
+ // detect the "https" module.
142
+ const { stack } = new Error();
143
+ if (typeof stack !== 'string')
144
+ return false;
145
+ return stack
146
+ .split('\n')
147
+ .some((l) => l.indexOf('(https.js:') !== -1 ||
148
+ l.indexOf('node:https:') !== -1);
149
+ }
150
+ // In order to support async signatures in `connect()` and Node's native
151
+ // connection pooling in `http.Agent`, the array of sockets for each origin
152
+ // has to be updated synchronously. This is so the length of the array is
153
+ // accurate when `addRequest()` is next called. We achieve this by creating a
154
+ // fake socket and adding it to `sockets[origin]` and incrementing
155
+ // `totalSocketCount`.
156
+ incrementSockets(name) {
157
+ // If `maxSockets` and `maxTotalSockets` are both Infinity then there is no
158
+ // need to create a fake socket because Node.js native connection pooling
159
+ // will never be invoked.
160
+ if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
161
+ return null;
162
+ }
163
+ // All instances of `sockets` are expected TypeScript errors. The
164
+ // alternative is to add it as a private property of this class but that
165
+ // will break TypeScript subclassing.
166
+ if (!this.sockets[name]) {
167
+ // @ts-expect-error `sockets` is readonly in `@types/node`
168
+ this.sockets[name] = [];
169
+ }
170
+ const fakeSocket = new net.Socket({ writable: false });
171
+ this.sockets[name].push(fakeSocket);
172
+ // @ts-expect-error `totalSocketCount` isn't defined in `@types/node`
173
+ this.totalSocketCount++;
174
+ return fakeSocket;
175
+ }
176
+ decrementSockets(name, socket) {
177
+ if (!this.sockets[name] || socket === null) {
178
+ return;
179
+ }
180
+ const sockets = this.sockets[name];
181
+ const index = sockets.indexOf(socket);
182
+ if (index !== -1) {
183
+ sockets.splice(index, 1);
184
+ // @ts-expect-error `totalSocketCount` isn't defined in `@types/node`
185
+ this.totalSocketCount--;
186
+ if (sockets.length === 0) {
187
+ // @ts-expect-error `sockets` is readonly in `@types/node`
188
+ delete this.sockets[name];
189
+ }
190
+ }
191
+ }
192
+ // In order to properly update the socket pool, we need to call `getName()` on
193
+ // the core `https.Agent` if it is a secureEndpoint.
194
+ getName(options) {
195
+ const secureEndpoint = this.isSecureEndpoint(options);
196
+ if (secureEndpoint) {
197
+ // @ts-expect-error `getName()` isn't defined in `@types/node`
198
+ return https_1.Agent.prototype.getName.call(this, options);
199
+ }
200
+ // @ts-expect-error `getName()` isn't defined in `@types/node`
201
+ return super.getName(options);
202
+ }
203
+ createSocket(req, options, cb) {
204
+ const connectOpts = {
205
+ ...options,
206
+ secureEndpoint: this.isSecureEndpoint(options),
207
+ };
208
+ const name = this.getName(connectOpts);
209
+ const fakeSocket = this.incrementSockets(name);
210
+ Promise.resolve()
211
+ .then(() => this.connect(req, connectOpts))
212
+ .then((socket) => {
213
+ this.decrementSockets(name, fakeSocket);
214
+ if (socket instanceof http.Agent) {
215
+ try {
216
+ // @ts-expect-error `addRequest()` isn't defined in `@types/node`
217
+ return socket.addRequest(req, connectOpts);
218
+ }
219
+ catch (err) {
220
+ return cb(err);
221
+ }
222
+ }
223
+ this[INTERNAL].currentSocket = socket;
224
+ // @ts-expect-error `createSocket()` isn't defined in `@types/node`
225
+ super.createSocket(req, options, cb);
226
+ }, (err) => {
227
+ this.decrementSockets(name, fakeSocket);
228
+ cb(err);
229
+ });
230
+ }
231
+ createConnection() {
232
+ const socket = this[INTERNAL].currentSocket;
233
+ this[INTERNAL].currentSocket = undefined;
234
+ if (!socket) {
235
+ throw new Error('No socket was returned in the `connect()` function');
236
+ }
237
+ return socket;
238
+ }
239
+ get defaultPort() {
240
+ return (this[INTERNAL].defaultPort ??
241
+ (this.protocol === 'https:' ? 443 : 80));
242
+ }
243
+ set defaultPort(v) {
244
+ if (this[INTERNAL]) {
245
+ this[INTERNAL].defaultPort = v;
246
+ }
247
+ }
248
+ get protocol() {
249
+ return (this[INTERNAL].protocol ??
250
+ (this.isSecureEndpoint() ? 'https:' : 'http:'));
251
+ }
252
+ set protocol(v) {
253
+ if (this[INTERNAL]) {
254
+ this[INTERNAL].protocol = v;
255
+ }
256
+ }
257
+ }
258
+ exports.Agent = Agent;
259
+ //# sourceMappingURL=index.js.map
260
+
261
+ /***/ },
262
+
263
+ /***/ 344
264
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
265
+
266
+ // ESM COMPAT FLAG
267
+ __webpack_require__.r(__webpack_exports__);
268
+
269
+ // EXPORTS
270
+ __webpack_require__.d(__webpack_exports__, {
271
+ HttpsProxyAgent: () => (/* binding */ HttpsProxyAgent)
272
+ });
273
+
274
+ // EXTERNAL MODULE: external "net"
275
+ var external_net_ = __webpack_require__(278);
276
+ // EXTERNAL MODULE: external "tls"
277
+ var external_tls_ = __webpack_require__(756);
278
+ // EXTERNAL MODULE: external "assert"
279
+ var external_assert_ = __webpack_require__(613);
280
+ // EXTERNAL MODULE: external "debug"
281
+ var external_debug_ = __webpack_require__(263);
282
+ // EXTERNAL MODULE: ../../node_modules/agent-base/dist/index.js
283
+ var dist = __webpack_require__(112);
284
+ // EXTERNAL MODULE: external "url"
285
+ var external_url_ = __webpack_require__(857);
286
+ ;// ../../node_modules/https-proxy-agent/dist/parse-proxy-response.js
287
+
288
+ const debug = external_debug_('https-proxy-agent:parse-proxy-response');
289
+ function parseProxyResponse(socket) {
290
+ return new Promise((resolve, reject) => {
291
+ // we need to buffer any HTTP traffic that happens with the proxy before we get
292
+ // the CONNECT response, so that if the response is anything other than an "200"
293
+ // response code, then we can re-play the "data" events on the socket once the
294
+ // HTTP parser is hooked up...
295
+ let buffersLength = 0;
296
+ const buffers = [];
297
+ function read() {
298
+ const b = socket.read();
299
+ if (b)
300
+ ondata(b);
301
+ else
302
+ socket.once('readable', read);
303
+ }
304
+ function cleanup() {
305
+ socket.removeListener('end', onend);
306
+ socket.removeListener('error', onerror);
307
+ socket.removeListener('readable', read);
308
+ }
309
+ function onend() {
310
+ cleanup();
311
+ debug('onend');
312
+ reject(new Error('Proxy connection ended before receiving CONNECT response'));
313
+ }
314
+ function onerror(err) {
315
+ cleanup();
316
+ debug('onerror %o', err);
317
+ reject(err);
318
+ }
319
+ function ondata(b) {
320
+ buffers.push(b);
321
+ buffersLength += b.length;
322
+ const buffered = Buffer.concat(buffers, buffersLength);
323
+ const endOfHeaders = buffered.indexOf('\r\n\r\n');
324
+ if (endOfHeaders === -1) {
325
+ // keep buffering
326
+ debug('have not received end of HTTP headers yet...');
327
+ read();
328
+ return;
329
+ }
330
+ const headerParts = buffered
331
+ .slice(0, endOfHeaders)
332
+ .toString('ascii')
333
+ .split('\r\n');
334
+ const firstLine = headerParts.shift();
335
+ if (!firstLine) {
336
+ socket.destroy();
337
+ return reject(new Error('No header received from proxy CONNECT response'));
338
+ }
339
+ const firstLineParts = firstLine.split(' ');
340
+ const statusCode = +firstLineParts[1];
341
+ const statusText = firstLineParts.slice(2).join(' ');
342
+ const headers = {};
343
+ for (const header of headerParts) {
344
+ if (!header)
345
+ continue;
346
+ const firstColon = header.indexOf(':');
347
+ if (firstColon === -1) {
348
+ socket.destroy();
349
+ return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
350
+ }
351
+ const key = header.slice(0, firstColon).toLowerCase();
352
+ const value = header.slice(firstColon + 1).trimStart();
353
+ const current = headers[key];
354
+ if (typeof current === 'string') {
355
+ headers[key] = [current, value];
356
+ }
357
+ else if (Array.isArray(current)) {
358
+ current.push(value);
359
+ }
360
+ else {
361
+ headers[key] = value;
362
+ }
363
+ }
364
+ debug('got proxy server response: %o %o', firstLine, headers);
365
+ cleanup();
366
+ resolve({
367
+ connect: {
368
+ statusCode,
369
+ statusText,
370
+ headers,
371
+ },
372
+ buffered,
373
+ });
374
+ }
375
+ socket.on('error', onerror);
376
+ socket.on('end', onend);
377
+ read();
378
+ });
379
+ }
380
+ //# sourceMappingURL=parse-proxy-response.js.map
381
+ // EXTERNAL MODULE: external "proxy-agent-negotiate"
382
+ var external_proxy_agent_negotiate_ = __webpack_require__(337);
383
+ ;// ../../node_modules/https-proxy-agent/dist/index.js
384
+
385
+
386
+
387
+
388
+
389
+
390
+
391
+
392
+ const dist_debug = external_debug_('https-proxy-agent');
393
+ const setServernameFromNonIpHost = (options) => {
394
+ if (options.servername === undefined &&
395
+ options.host &&
396
+ !external_net_.isIP(options.host)) {
397
+ return {
398
+ ...options,
399
+ servername: options.host,
400
+ };
401
+ }
402
+ return options;
403
+ };
404
+ /**
405
+ * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
406
+ * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
407
+ *
408
+ * Outgoing HTTP requests are first tunneled through the proxy server using the
409
+ * `CONNECT` HTTP request method to establish a connection to the proxy server,
410
+ * and then the proxy server connects to the destination target and issues the
411
+ * HTTP request from the proxy server.
412
+ *
413
+ * `https:` requests have their socket connection upgraded to TLS once
414
+ * the connection to the proxy server has been established.
415
+ */
416
+ class HttpsProxyAgent extends dist.Agent {
417
+ constructor(proxy, opts) {
418
+ super(opts);
419
+ this.options = { path: undefined };
420
+ this.proxy = typeof proxy === 'string' ? new external_url_.URL(proxy) : proxy;
421
+ this.proxyHeaders = opts?.headers ?? {};
422
+ dist_debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
423
+ if (opts?.negotiate) {
424
+ this.onProxyAuth = (0,external_proxy_agent_negotiate_.createNegotiateAuth)();
425
+ }
426
+ else if (opts?.onProxyAuth) {
427
+ this.onProxyAuth = opts.onProxyAuth;
428
+ }
429
+ // Trim off the brackets from IPv6 addresses
430
+ const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
431
+ const port = this.proxy.port
432
+ ? parseInt(this.proxy.port, 10)
433
+ : this.proxy.protocol === 'https:'
434
+ ? 443
435
+ : 80;
436
+ this.connectOpts = {
437
+ // Attempt to negotiate http/1.1 for proxy servers that support http/2
438
+ ALPNProtocols: ['http/1.1'],
439
+ ...(opts
440
+ ? omit(opts, 'headers', 'onProxyAuth', 'negotiate')
441
+ : null),
442
+ host,
443
+ port,
444
+ };
445
+ }
446
+ /**
447
+ * Called when the node-core HTTP client library is creating a
448
+ * new HTTP request.
449
+ */
450
+ async connect(req, opts) {
451
+ const { proxy } = this;
452
+ if (!opts.host) {
453
+ throw new TypeError('No "host" provided');
454
+ }
455
+ // Create a socket connection to the proxy server.
456
+ let socket;
457
+ if (proxy.protocol === 'https:') {
458
+ dist_debug('Creating `tls.Socket`: %o', this.connectOpts);
459
+ socket = external_tls_.connect(setServernameFromNonIpHost(this.connectOpts));
460
+ }
461
+ else {
462
+ dist_debug('Creating `net.Socket`: %o', this.connectOpts);
463
+ socket = external_net_.connect(this.connectOpts);
464
+ }
465
+ const headers = typeof this.proxyHeaders === 'function'
466
+ ? this.proxyHeaders()
467
+ : { ...this.proxyHeaders };
468
+ const host = external_net_.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
469
+ let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
470
+ // Inject the `Proxy-Authorization` header if necessary.
471
+ if (proxy.username || proxy.password) {
472
+ const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
473
+ headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
474
+ }
475
+ headers.Host = `${host}:${opts.port}`;
476
+ if (!headers['Proxy-Connection']) {
477
+ headers['Proxy-Connection'] = this.keepAlive
478
+ ? 'Keep-Alive'
479
+ : 'close';
480
+ }
481
+ for (const name of Object.keys(headers)) {
482
+ payload += `${name}: ${headers[name]}\r\n`;
483
+ }
484
+ const proxyResponsePromise = parseProxyResponse(socket);
485
+ socket.write(`${payload}\r\n`);
486
+ const { connect, buffered } = await proxyResponsePromise;
487
+ req.emit('proxyConnect', connect);
488
+ this.emit('proxyConnect', connect, req);
489
+ req.emit('proxy', { proxy: this.proxy.href, socket });
490
+ if (connect.statusCode === 200) {
491
+ req.once('socket', resume);
492
+ if (opts.secureEndpoint) {
493
+ // The proxy is connecting to a TLS server, so upgrade
494
+ // this socket connection to a TLS connection.
495
+ dist_debug('Upgrading socket connection to TLS');
496
+ return external_tls_.connect({
497
+ ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'),
498
+ socket,
499
+ });
500
+ }
501
+ return socket;
502
+ }
503
+ // Handle 407 Proxy Authentication Required
504
+ if (connect.statusCode === 407 && this.onProxyAuth) {
505
+ dist_debug('Got 407 response, invoking onProxyAuth callback');
506
+ socket.destroy();
507
+ const proxyAuthenticate = connect.headers['proxy-authenticate'] || '';
508
+ const scheme = Array.isArray(proxyAuthenticate)
509
+ ? proxyAuthenticate[0].split(/\s/)[0]
510
+ : proxyAuthenticate.split(/\s/)[0];
511
+ const authResponse = await this.onProxyAuth({
512
+ response: connect,
513
+ scheme,
514
+ });
515
+ // Retry with the auth headers
516
+ return this._connectWithAuth(req, opts, authResponse.headers);
517
+ }
518
+ // Some other status code that's not 200... need to re-play the HTTP
519
+ // header "data" events onto the socket once the HTTP machinery is
520
+ // attached so that the node core `http` can parse and handle the
521
+ // error status code.
522
+ // Close the original socket, and a new "fake" socket is returned
523
+ // instead, so that the proxy doesn't get the HTTP request
524
+ // written to it (which may contain `Authorization` headers or other
525
+ // sensitive data).
526
+ //
527
+ // See: https://hackerone.com/reports/541502
528
+ socket.destroy();
529
+ const fakeSocket = new external_net_.Socket({ writable: false });
530
+ fakeSocket.readable = true;
531
+ // Need to wait for the "socket" event to re-play the "data" events.
532
+ req.once('socket', (s) => {
533
+ dist_debug('Replaying proxy buffer for failed request');
534
+ external_assert_(s.listenerCount('data') > 0);
535
+ // Replay the "buffered" Buffer onto the fake `socket`, since at
536
+ // this point the HTTP module machinery has been hooked up for
537
+ // the user.
538
+ s.push(buffered);
539
+ s.push(null);
540
+ });
541
+ return fakeSocket;
542
+ }
543
+ /**
544
+ * Retry a CONNECT request with additional auth headers.
545
+ */
546
+ async _connectWithAuth(req, opts, authHeaders) {
547
+ const { proxy } = this;
548
+ let socket;
549
+ if (proxy.protocol === 'https:') {
550
+ socket = external_tls_.connect(setServernameFromNonIpHost(this.connectOpts));
551
+ }
552
+ else {
553
+ socket = external_net_.connect(this.connectOpts);
554
+ }
555
+ const headers = typeof this.proxyHeaders === 'function'
556
+ ? this.proxyHeaders()
557
+ : { ...this.proxyHeaders };
558
+ const host = external_net_.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
559
+ let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
560
+ if (proxy.username || proxy.password) {
561
+ const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
562
+ headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
563
+ }
564
+ // Merge auth headers (overrides existing)
565
+ Object.assign(headers, authHeaders);
566
+ headers.Host = `${host}:${opts.port}`;
567
+ if (!headers['Proxy-Connection']) {
568
+ headers['Proxy-Connection'] = this.keepAlive
569
+ ? 'Keep-Alive'
570
+ : 'close';
571
+ }
572
+ for (const name of Object.keys(headers)) {
573
+ payload += `${name}: ${headers[name]}\r\n`;
574
+ }
575
+ const proxyResponsePromise = parseProxyResponse(socket);
576
+ socket.write(`${payload}\r\n`);
577
+ const { connect } = await proxyResponsePromise;
578
+ req.emit('proxyConnect', connect);
579
+ this.emit('proxyConnect', connect, req);
580
+ if (connect.statusCode === 200) {
581
+ req.once('socket', resume);
582
+ if (opts.secureEndpoint) {
583
+ dist_debug('Upgrading socket connection to TLS');
584
+ return external_tls_.connect({
585
+ ...omit(setServernameFromNonIpHost(opts), 'host', 'path', 'port'),
586
+ socket,
587
+ });
588
+ }
589
+ return socket;
590
+ }
591
+ // If still not 200, throw
592
+ socket.destroy();
593
+ throw new Error(`Proxy authentication failed with status ${connect.statusCode} after retry`);
594
+ }
595
+ }
596
+ HttpsProxyAgent.protocols = ['http', 'https'];
597
+ function resume(socket) {
598
+ // Defer the resume so that all 'socket' event handlers have a chance
599
+ // to attach their listeners (e.g. the HTTP client's 'data' handler)
600
+ // before data starts flowing. Without this, buffered proxy-response
601
+ // data can be emitted synchronously before listeners are ready.
602
+ // See: https://github.com/nicolo-ribaudo/tc39-proposal-await-dictionary/issues/7
603
+ setImmediate(() => {
604
+ socket.resume();
605
+ });
606
+ }
607
+ function omit(obj, ...keys) {
608
+ const ret = {};
609
+ let key;
610
+ for (key in obj) {
611
+ if (!keys.includes(key)) {
612
+ ret[key] = obj[key];
613
+ }
614
+ }
615
+ return ret;
616
+ }
617
+ //# sourceMappingURL=index.js.map
618
+
619
+ /***/ }
620
+
621
+ };
622
+ ;
623
+ //# sourceMappingURL=344.js.map