dsh-remote-vs 0.28.0 → 0.29.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/src/proxy.ts ADDED
@@ -0,0 +1,673 @@
1
+ /**
2
+ * Outbound proxy support for SSH dials.
3
+ *
4
+ * Why this is not just `HTTP_PROXY`: ssh2 dials a raw TCP socket, and the
5
+ * harness's proxy plumbing (`@deepseek-ai/dsh-http-proxy`) only wraps `fetch`,
6
+ * so a host that can only be reached through a proxy needs the tunnel built
7
+ * here. Three flavours, in the order a user meets them:
8
+ *
9
+ * - `http` — `CONNECT host:port`, optional `Proxy-Authorization: Basic …`;
10
+ * - `socks5` — greeting / optional user+password sub-negotiation / CONNECT;
11
+ * - jump (`ProxyJump` / `ProxyCommand ssh -W`) — NOT dialled here: the pool
12
+ * opens a `direct-tcpip` channel on ANOTHER pooled connection and hands it
13
+ * to ssh2 as its socket. This module only parses those specs into a target.
14
+ *
15
+ * **Error taxonomy is the point.** "The proxy refused the tunnel" and "the
16
+ * target closed the port" and "your password is wrong" all fail the dial, and
17
+ * the user debugs the wrong thing if they all read "connection failed". Each
18
+ * failure therefore leaves as a `ProxyError` with a stable `reason` and one
19
+ * actionable sentence.
20
+ *
21
+ * **Bytes are never lost.** A proxy may send tunnel bytes in the same packet as
22
+ * its handshake reply; everything read past the handshake is pushed back onto
23
+ * the socket before it is handed to ssh2, or the SSH banner would be swallowed
24
+ * and the handshake would stall.
25
+ *
26
+ * @module
27
+ */
28
+ import { createConnection, type Socket } from 'node:net'
29
+
30
+ /** Proxy flavours this plugin dials itself. A jump host is not one of them. */
31
+ export type ProxyKind = 'http' | 'socks5'
32
+
33
+ /** One validated proxy endpoint (secrets included: host-side only). */
34
+ export interface ProxyConfig {
35
+ kind: ProxyKind
36
+ /** Proxy hostname / IPv4 / IPv6 literal. */
37
+ host: string
38
+ port: number
39
+ /** Basic auth (http) or user/password sub-negotiation (socks5). */
40
+ username?: string
41
+ password?: string
42
+ }
43
+
44
+ /** A `ProxyJump` / `ProxyCommand ssh -W` hop, parsed but not yet resolved. */
45
+ export interface JumpTarget {
46
+ /** Login user named in the spec, when it had one. */
47
+ user?: string
48
+ host: string
49
+ port: number
50
+ }
51
+
52
+ /** Every way a proxy dial can fail, as a stable value (not a message). */
53
+ export type ProxyFailure =
54
+ /** The proxy itself could not be reached (TCP refused/unreachable). */
55
+ | 'unreachable'
56
+ /** The proxy accepted TCP but never finished talking to us. */
57
+ | 'timeout'
58
+ /** The proxy demanded credentials we do not have, or rejected ours. */
59
+ | 'auth'
60
+ /** The proxy answered, and refused the tunnel (bad status / SOCKS reply). */
61
+ | 'refused'
62
+ /** The proxy answered with something that is not the protocol we speak. */
63
+ | 'protocol'
64
+ /** The destination is not a legal target (bad port, empty host). */
65
+ | 'target'
66
+
67
+ /** A proxy dial failure that knows which layer broke. */
68
+ export class ProxyError extends Error {
69
+ constructor(
70
+ readonly reason: ProxyFailure,
71
+ message: string,
72
+ /** Which proxy kind was attempted (absent for target validation). */
73
+ readonly kind?: ProxyKind,
74
+ ) {
75
+ super(message)
76
+ this.name = 'ProxyError'
77
+ }
78
+ }
79
+
80
+ /** Hostname / IPv4 / IPv6 accepted as a proxy or destination. */
81
+ const HOST_RE = /^[A-Za-z0-9._:[\]%-]{1,255}$/
82
+
83
+ /** Longest credential string accepted (a proxy config, not a password manager). */
84
+ const MAX_CREDENTIAL = 255
85
+
86
+ function cleanCredential(value: unknown): string | undefined {
87
+ if (typeof value !== 'string') return undefined
88
+ if (value === '') return undefined
89
+ return value.length > MAX_CREDENTIAL ? value.slice(0, MAX_CREDENTIAL) : value
90
+ }
91
+
92
+ /**
93
+ * Validate one proxy endpoint.
94
+ *
95
+ * @param input - value as it arrived from the browser / store file.
96
+ * @returns the normalized config (empty credentials dropped).
97
+ * @throws {ProxyError} `target` when a field is unusable, with the field named.
98
+ */
99
+ export function normalizeProxy(input: unknown): ProxyConfig {
100
+ if (typeof input !== 'object' || input === null) {
101
+ throw new ProxyError('target', 'proxy must be an object')
102
+ }
103
+ const raw = input as Record<string, unknown>
104
+ const kind = raw.kind
105
+ if (kind !== 'http' && kind !== 'socks5') {
106
+ throw new ProxyError('target', "proxy.kind must be 'http' or 'socks5'")
107
+ }
108
+ if (typeof raw.host !== 'string' || !HOST_RE.test(raw.host)) {
109
+ throw new ProxyError('target', 'proxy.host must be a hostname or IP address')
110
+ }
111
+ const port = raw.port
112
+ if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535) {
113
+ throw new ProxyError('target', 'proxy.port must be an integer between 1 and 65535')
114
+ }
115
+ const username = cleanCredential(raw.username)
116
+ const password = cleanCredential(raw.password)
117
+ return {
118
+ kind,
119
+ host: raw.host,
120
+ port,
121
+ ...(username === undefined ? {} : { username }),
122
+ ...(password === undefined ? {} : { password }),
123
+ }
124
+ }
125
+
126
+ /** True when a value looks like a proxy config at all (shape, not validity). */
127
+ export function looksLikeProxy(value: unknown): boolean {
128
+ return typeof value === 'object' && value !== null
129
+ && ((value as { kind?: unknown }).kind === 'http' || (value as { kind?: unknown }).kind === 'socks5')
130
+ }
131
+
132
+ /** One `user@host:port` hop of a ProxyJump chain. */
133
+ function parseHop(token: string): JumpTarget | undefined {
134
+ const at = token.lastIndexOf('@')
135
+ const user = at < 0 ? undefined : token.slice(0, at)
136
+ const rest = at < 0 ? token : token.slice(at + 1)
137
+ if (rest === '') return undefined
138
+ if (rest.includes(' [') || /\s/.test(rest)) return undefined
139
+ let host = rest
140
+ let port = 22
141
+ // A bare IPv6 literal has colons of its own; only `[v6]:port` and
142
+ // `host:port` carry a real port.
143
+ const bracket = /^\[(.+)\]:(\d+)$/.exec(rest)
144
+ if (bracket !== null) {
145
+ host = `[${bracket[1]}]`
146
+ port = Number.parseInt(bracket[2] ?? '', 10)
147
+ } else if (rest.startsWith('[') && rest.endsWith(']')) {
148
+ host = rest
149
+ } else {
150
+ const colon = rest.lastIndexOf(':')
151
+ if (colon > 0) {
152
+ const tail = rest.slice(colon + 1)
153
+ if (/^\d+$/.test(tail)) {
154
+ host = rest.slice(0, colon)
155
+ port = Number.parseInt(tail, 10)
156
+ }
157
+ }
158
+ }
159
+ if (!HOST_RE.test(host)) return undefined
160
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined
161
+ return { ...(user === undefined || user === '' ? {} : { user }), host, port }
162
+ }
163
+
164
+ /**
165
+ * Parse an OpenSSH `ProxyJump` value (`jump`, `user@jump:2222`, `a,b`).
166
+ *
167
+ * Only a single hop is supported: the pool builds the tunnel on one existing
168
+ * pooled connection, and a chain would need nested channels whose failure modes
169
+ * we cannot explain to the user yet. Multi-hop is therefore a named refusal
170
+ * rather than a silent half-feature.
171
+ */
172
+ export function parseProxyJump(value: string): { ok: true; target: JumpTarget } | { ok: false; reason: string } {
173
+ const hops = value.split(',').map(hop => hop.trim()).filter(hop => hop !== '')
174
+ if (hops.length === 0) return { ok: false, reason: 'ProxyJump names no host' }
175
+ if (hops.length > 1) {
176
+ return { ok: false, reason: `ProxyJump with ${hops.length} hops is not supported (one jump host only)` }
177
+ }
178
+ const target = parseHop(hops[0] ?? '')
179
+ if (target === undefined) return { ok: false, reason: 'ProxyJump must look like user@host:port' }
180
+ return { ok: true, target }
181
+ }
182
+
183
+ /** One tokenized ProxyCommand word (quotes dropped, `%h`/`%p` kept verbatim). */
184
+ function tokenize(command: string): string[] {
185
+ const out: string[] = []
186
+ let current = ''
187
+ let quote: '"' | "'" | undefined
188
+ for (const char of command) {
189
+ if (quote !== undefined) {
190
+ if (char === quote) quote = undefined
191
+ else current += char
192
+ continue
193
+ }
194
+ if (char === '"' || char === "'") {
195
+ quote = char
196
+ continue
197
+ }
198
+ if (/\s/.test(char)) {
199
+ if (current !== '') out.push(current)
200
+ current = ''
201
+ continue
202
+ }
203
+ current += char
204
+ }
205
+ if (current !== '') out.push(current)
206
+ return out
207
+ }
208
+
209
+ /** `host:port` used by nc/ncat proxy arguments. */
210
+ function parseProxyAddress(value: string): { host: string; port: number } | undefined {
211
+ const colon = value.lastIndexOf(':')
212
+ if (colon <= 0) return undefined
213
+ const host = value.slice(0, colon)
214
+ const port = Number.parseInt(value.slice(colon + 1), 10)
215
+ if (!HOST_RE.test(host)) return undefined
216
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined
217
+ return { host, port }
218
+ }
219
+
220
+ /** What a `ProxyCommand` line means to this plugin. */
221
+ export type ProxyCommandPlan =
222
+ | { kind: 'proxy'; proxy: Omit<ProxyConfig, 'username' | 'password'> }
223
+ | { kind: 'jump'; target: JumpTarget }
224
+ | { kind: 'unsupported'; reason: string }
225
+
226
+ /**
227
+ * Map the ProxyCommand forms users actually write onto a tunnel we can build.
228
+ *
229
+ * Recognised: `ssh … -W %h:%p [user@]host`, `nc -X connect -x host:port %h %p`
230
+ * (http), `nc -x host:port %h %p` (socks5), `ncat --proxy … --proxy-type …`.
231
+ * Everything else is refused by name — a ProxyCommand is a shell command, and
232
+ * running one from a browser-supplied config is not a feature this plugin
233
+ * offers.
234
+ */
235
+ export function parseProxyCommand(command: string): ProxyCommandPlan {
236
+ const words = tokenize(command)
237
+ if (words.length === 0) return { kind: 'unsupported', reason: 'ProxyCommand is empty' }
238
+ const program = (words[0] ?? '').split(/[\\/]/).pop() ?? ''
239
+ if (program === 'ssh') {
240
+ /**
241
+ * `ssh -W %h:%p bastion` — the canonical ProxyCommand — puts the DESTINATION
242
+ * in `-W`'s argument and the JUMP HOST in the positional argument. Reading
243
+ * `-W`'s value as the jump host is the mistake this loop exists to avoid:
244
+ * it is always the literal `%h:%p`.
245
+ */
246
+ let forwards = false
247
+ let user: string | undefined
248
+ let port: number | undefined
249
+ let destination: string | undefined
250
+ for (let index = 1; index < words.length; index += 1) {
251
+ const word = words[index] ?? ''
252
+ if (word === '-W' || word.startsWith('-W')) {
253
+ forwards = true
254
+ // `-W` takes `%h:%p` (what to forward), never the jump host. OpenSSH also
255
+ // accepts the value attached (`ssh -W%h:%p bastion`), which is one word.
256
+ if (word === '-W') index += 1
257
+ continue
258
+ }
259
+ // Options that consume a following value we do not need.
260
+ if (word === '-l' || word === '-p' || word === '-o' || word === '-i' || word === '-F' || word === '-J') {
261
+ const value = words[index + 1]
262
+ if (word === '-l') user = value
263
+ if (word === '-p') {
264
+ const parsedPort = Number.parseInt(value ?? '', 10)
265
+ if (Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535) port = parsedPort
266
+ }
267
+ index += 1
268
+ continue
269
+ }
270
+ if (word.startsWith('-')) continue
271
+ destination ??= word
272
+ }
273
+ if (!forwards) return { kind: 'unsupported', reason: 'ProxyCommand ssh must use -W %h:%p' }
274
+ if (destination === undefined) return { kind: 'unsupported', reason: 'ProxyCommand ssh -W names no jump host' }
275
+ const parsed = parseHop(user === undefined || user === '' ? destination : `${user}@${destination}`)
276
+ if (parsed === undefined) {
277
+ return { kind: 'unsupported', reason: 'ProxyCommand ssh -W: the jump host is not a host name' }
278
+ }
279
+ return { kind: 'jump', target: { ...parsed, ...(port === undefined ? {} : { port }) } }
280
+ }
281
+ if (program === 'nc' || program === 'netcat') {
282
+ const x = words.indexOf('-X')
283
+ const xMode = x < 0 ? undefined : (words[x + 1] ?? '')
284
+ const dash = words.indexOf('-x')
285
+ const address = dash < 0 ? undefined : parseProxyAddress(words[dash + 1] ?? '')
286
+ if (address === undefined) return { kind: 'unsupported', reason: 'ProxyCommand nc must name a proxy with -x host:port' }
287
+ if (xMode === 'connect' || xMode === 'http') return { kind: 'proxy', proxy: { kind: 'http', ...address } }
288
+ if (xMode === undefined || xMode === '5' || xMode === 'socks5') {
289
+ return { kind: 'proxy', proxy: { kind: 'socks5', ...address } }
290
+ }
291
+ return { kind: 'unsupported', reason: `ProxyCommand nc -X ${xMode} is not supported` }
292
+ }
293
+ if (program === 'ncat') {
294
+ const at = words.indexOf('--proxy')
295
+ const address = at < 0 ? undefined : parseProxyAddress(words[at + 1] ?? '')
296
+ if (address === undefined) return { kind: 'unsupported', reason: 'ProxyCommand ncat must name --proxy host:port' }
297
+ const typeAt = words.indexOf('--proxy-type')
298
+ const type = typeAt < 0 ? 'http' : (words[typeAt + 1] ?? 'http')
299
+ if (type === 'http') return { kind: 'proxy', proxy: { kind: 'http', ...address } }
300
+ if (type === 'socks5') return { kind: 'proxy', proxy: { kind: 'socks5', ...address } }
301
+ return { kind: 'unsupported', reason: `ProxyCommand ncat --proxy-type ${type} is not supported` }
302
+ }
303
+ return {
304
+ kind: 'unsupported',
305
+ reason: `ProxyCommand program ${program === '' ? '(none)' : program} is not supported`
306
+ + ' (only ssh -W, nc -X connect -x and ncat --proxy)',
307
+ }
308
+ }
309
+
310
+ /** How this module reaches a TCP socket (a seam for the gates). */
311
+ export type SocketFactory = (host: string, port: number) => Socket
312
+
313
+ /** One tunnel request. */
314
+ export interface OpenProxyOptions {
315
+ /** Total budget for connect + handshake (default 8000 ms). */
316
+ timeoutMs?: number
317
+ /** Test seam: replaces `net.createConnection`. */
318
+ connect?: SocketFactory
319
+ }
320
+
321
+ /** Default budget: a proxy that cannot answer in this long is not worth waiting for. */
322
+ export const PROXY_TIMEOUT_MS = 8_000
323
+
324
+ /** Buffered reads over one socket, keeping every byte it saw. */
325
+ class Reader {
326
+ private buffer = Buffer.alloc(0)
327
+ private waiter: (() => void) | undefined
328
+ private ended = false
329
+ private failure: Error | undefined
330
+ /** Bound handlers, kept so `detach` can remove exactly what was added. */
331
+ private readonly onData = (chunk: Buffer): void => {
332
+ this.buffer = Buffer.concat([this.buffer, chunk])
333
+ this.wake()
334
+ }
335
+
336
+ private readonly onError = (error: Error): void => {
337
+ this.failure = error
338
+ this.wake()
339
+ }
340
+
341
+ private readonly onClose = (): void => {
342
+ this.ended = true
343
+ this.wake()
344
+ }
345
+
346
+ constructor(private readonly socket: Socket) {
347
+ socket.on('data', this.onData)
348
+ socket.once('error', this.onError)
349
+ socket.once('close', this.onClose)
350
+ }
351
+
352
+ private wake(): void {
353
+ const waiter = this.waiter
354
+ this.waiter = undefined
355
+ waiter?.()
356
+ }
357
+
358
+ /** Wait for more bytes; false when the socket closed or failed. */
359
+ private async more(): Promise<void> {
360
+ if (this.failure !== undefined) throw this.failure
361
+ if (this.ended) return
362
+ await new Promise<void>((resolve) => { this.waiter = resolve })
363
+ }
364
+
365
+ /** Read until `marker` inclusive (used for the HTTP header block). */
366
+ async until(marker: string): Promise<Buffer> {
367
+ for (;;) {
368
+ const at = this.buffer.indexOf(marker)
369
+ if (at >= 0) {
370
+ const end = at + marker.length
371
+ const head = this.buffer.subarray(0, end)
372
+ this.buffer = this.buffer.subarray(end)
373
+ return head
374
+ }
375
+ await this.more()
376
+ if (this.failure !== undefined) throw this.failure
377
+ if (this.ended) throw new ProxyError('protocol', 'the proxy closed the tunnel before answering')
378
+ }
379
+ }
380
+
381
+ /** Read exactly `count` bytes (SOCKS replies). */
382
+ async exact(count: number): Promise<Buffer> {
383
+ for (;;) {
384
+ if (this.buffer.length >= count) {
385
+ const head = this.buffer.subarray(0, count)
386
+ this.buffer = this.buffer.subarray(count)
387
+ return head
388
+ }
389
+ await this.more()
390
+ if (this.failure !== undefined) throw this.failure
391
+ if (this.ended) throw new ProxyError('protocol', 'the proxy closed the tunnel before answering')
392
+ }
393
+ }
394
+
395
+ /** Push back tunnel bytes that arrived with the handshake reply. */
396
+ release(): void {
397
+ if (this.buffer.length > 0) {
398
+ const leftover = this.buffer
399
+ this.buffer = Buffer.alloc(0)
400
+ this.socket.unshift(leftover)
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Stop observing the socket after a successful handshake.
406
+ *
407
+ * Without this the `data` listener keeps appending every tunnelled byte to
408
+ * `buffer` for the whole life of the connection — an unbounded leak on an SSH
409
+ * session that moves a few files. The socket belongs to the caller from here on
410
+ * (ssh2 becomes its only reader).
411
+ *
412
+ * Called BEFORE `release()`: an attached `data` listener would immediately
413
+ * consume the pushed-back bytes into `buffer` again, and the handover would lose
414
+ * the SSH banner it just rescued.
415
+ */
416
+ detach(): void {
417
+ this.socket.off('data', this.onData)
418
+ this.socket.off('error', this.onError)
419
+ this.socket.off('close', this.onClose)
420
+ }
421
+ }
422
+
423
+ /** The four octets of a dotted-quad IPv4 literal, or `undefined`. */
424
+ function ipv4Octets(value: string): number[] | undefined {
425
+ const parts = value.split('.')
426
+ if (parts.length !== 4) return undefined
427
+ const octets: number[] = []
428
+ for (const part of parts) {
429
+ if (!/^\d{1,3}$/.test(part)) return undefined
430
+ const octet = Number.parseInt(part, 10)
431
+ if (octet > 255) return undefined
432
+ octets.push(octet)
433
+ }
434
+ return octets
435
+ }
436
+
437
+ /**
438
+ * Expand one IPv6 literal into its eight 16-bit groups, or `undefined`.
439
+ *
440
+ * A SOCKS5 CONNECT carries the target as BYTES, so the literal has to be
441
+ * expanded before it is encoded — and `::` is what makes that non-obvious. The
442
+ * first cut appended a single `'0'` group wherever the text was short, so every
443
+ * compressed form encoded a DIFFERENT address than it names (`2001:db8::1` became
444
+ * `2001:db8:0:0:1:0:0:0`, `::1` became `0:0:0:1:0:0:0:0`): the tunnel opened,
445
+ * nothing errored, and the dial reached a host nobody asked for. Handing back
446
+ * `undefined` for an unexpandable literal is the point — the caller refuses the
447
+ * dial instead of encoding something.
448
+ *
449
+ * Accepted: exactly one `::` anywhere (leading / middle / trailing), eight
450
+ * explicit groups when there is no `::`, and a dotted IPv4 in the LAST group
451
+ * (RFC 4291 §2.2.3, e.g. `::ffff:1.2.3.4`). Two `::`, too many or too few
452
+ * groups, bad hex and a bad quad are all `undefined`, never a guess.
453
+ */
454
+ function expandIPv6(value: string): number[] | undefined {
455
+ const halves = value.split('::')
456
+ if (halves.length > 2) return undefined
457
+ const compressed = halves.length === 2
458
+ const readGroups = (part: string | undefined): number[] | undefined => {
459
+ if (part === undefined || part === '') return []
460
+ const groups = part.split(':')
461
+ const out: number[] = []
462
+ for (let index = 0; index < groups.length; index += 1) {
463
+ const group = groups[index] as string
464
+ if (group.includes('.')) {
465
+ // A dotted quad may only be the LAST group of the whole literal.
466
+ if (index !== groups.length - 1) return undefined
467
+ const octets = ipv4Octets(group)
468
+ if (octets === undefined) return undefined
469
+ const [a = 0, b = 0, c = 0, d = 0] = octets
470
+ out.push((a << 8) | b, (c << 8) | d)
471
+ continue
472
+ }
473
+ if (!/^[0-9A-Fa-f]{1,4}$/.test(group)) return undefined
474
+ out.push(Number.parseInt(group, 16))
475
+ }
476
+ return out
477
+ }
478
+ const head = readGroups(halves[0])
479
+ const tail = compressed ? readGroups(halves[1]) : []
480
+ if (head === undefined || tail === undefined) return undefined
481
+ const explicit = head.length + tail.length
482
+ if (!compressed) return explicit === 8 ? head : undefined
483
+ // `::` must stand for at least ONE zero group: `1:2:3:4:5:6:7:8::` is invalid.
484
+ if (explicit > 7) return undefined
485
+ return [...head, ...Array.from({ length: 8 - explicit }, () => 0), ...tail]
486
+ }
487
+
488
+ /** Encode one SOCKS5 target address (domain / IPv4 / IPv6). */
489
+ function socksAddress(host: string, port: number): Buffer {
490
+ const bare = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host
491
+ const portBytes = Buffer.alloc(2)
492
+ portBytes.writeUInt16BE(port, 0)
493
+ const octets = ipv4Octets(bare)
494
+ if (octets !== undefined) {
495
+ return Buffer.concat([Buffer.from([0x01]), Buffer.from(octets), portBytes])
496
+ }
497
+ if (bare.includes(':')) {
498
+ const groups = expandIPv6(bare)
499
+ if (groups === undefined) {
500
+ // Encoding it as a DOMAIN NAME would silently dial a host the user did not
501
+ // name, which is exactly how the compressed-form bug above behaved.
502
+ // A scoped literal (`fe80::1%eth0`) is refused for a real reason — a zone
503
+ // id means nothing once the bytes leave this machine — so say that rather
504
+ // than calling a well-formed address "invalid".
505
+ throw new ProxyError(
506
+ 'target',
507
+ bare.includes('%')
508
+ ? `destination ${JSON.stringify(host)} is scoped (link-local); SOCKS5 cannot carry a zone id`
509
+ : `destination ${JSON.stringify(host)} is not a valid IPv6 address`,
510
+ 'socks5',
511
+ )
512
+ }
513
+ const bytes = groups.flatMap(group => [(group >> 8) & 0xff, group & 0xff])
514
+ return Buffer.concat([Buffer.from([0x04]), Buffer.from(bytes), portBytes])
515
+ }
516
+ const name = Buffer.from(bare, 'utf8')
517
+ return Buffer.concat([Buffer.from([0x03, name.length]), name, portBytes])
518
+ }
519
+
520
+ /** One SOCKS5 reply code as an actionable failure. */
521
+ function socksReplyError(code: number): ProxyError {
522
+ switch (code) {
523
+ case 0x02: return new ProxyError('refused', 'the proxy does not allow this connection (SOCKS5 rule denied)', 'socks5')
524
+ case 0x03: return new ProxyError('refused', 'the proxy cannot reach the network (SOCKS5: network unreachable)', 'socks5')
525
+ case 0x04: return new ProxyError('refused', 'the proxy cannot reach the host (SOCKS5: host unreachable)', 'socks5')
526
+ case 0x05: return new ProxyError('refused', 'the connection was refused by the target host (via SOCKS5)', 'socks5')
527
+ case 0x06: return new ProxyError('refused', 'the connection timed out at the proxy (SOCKS5: TTL expired)', 'socks5')
528
+ case 0x07: return new ProxyError('refused', 'the proxy does not support CONNECT (SOCKS5: command not supported)', 'socks5')
529
+ case 0x08: return new ProxyError('protocol', 'the proxy does not accept this address type (SOCKS5)', 'socks5')
530
+ default: return new ProxyError('refused', `the proxy refused the tunnel (SOCKS5 reply ${code})`, 'socks5')
531
+ }
532
+ }
533
+
534
+ /**
535
+ * Dial `host:port` through `proxy` and hand back the tunnelled socket.
536
+ *
537
+ * The caller owns the socket (ssh2 takes it as its transport). Everything read
538
+ * past the handshake is pushed back, so the SSH banner is not swallowed.
539
+ *
540
+ * @throws {ProxyError} when the proxy layer — not SSH — is what failed.
541
+ */
542
+ export async function openProxySocket(
543
+ proxy: ProxyConfig,
544
+ host: string,
545
+ port: number,
546
+ options: OpenProxyOptions = {},
547
+ ): Promise<Socket> {
548
+ if (host === '' || !HOST_RE.test(host) || !Number.isInteger(port) || port < 1 || port > 65535) {
549
+ throw new ProxyError('target', `destination must be host:port, got ${JSON.stringify(`${host}:${port}`)}`)
550
+ }
551
+ const budget = options.timeoutMs ?? PROXY_TIMEOUT_MS
552
+ const connect = options.connect ?? ((target, targetPort) => createConnection({ host: target, port: targetPort }))
553
+ const socket = connect(proxy.host, proxy.port)
554
+ const reader = new Reader(socket)
555
+ const timer = setTimeout(() => {
556
+ socket.destroy(new ProxyError('timeout', `the proxy ${proxy.host}:${proxy.port} did not answer within ${budget / 1000}s`, proxy.kind))
557
+ }, budget)
558
+ timer.unref?.()
559
+ try {
560
+ await new Promise<void>((resolve, reject) => {
561
+ socket.once('connect', () => resolve())
562
+ socket.once('error', (error: Error) => {
563
+ const code = (error as NodeJS.ErrnoException).code
564
+ const unreachable = code === 'ECONNREFUSED' || code === 'EHOSTUNREACH' || code === 'ENETUNREACH'
565
+ || code === 'EACCES' || code === 'ENOTFOUND' || code === 'EAI_AGAIN' || code === 'ETIMEDOUT'
566
+ reject(unreachable
567
+ ? new ProxyError('unreachable', `cannot reach the proxy ${proxy.host}:${proxy.port} (${code ?? error.message})`, proxy.kind)
568
+ : error)
569
+ })
570
+ })
571
+ if (proxy.kind === 'http') await httpTunnel(socket, reader, proxy, host, port)
572
+ else await socks5Tunnel(socket, reader, proxy, host, port)
573
+ reader.detach()
574
+ reader.release()
575
+ return socket
576
+ } catch (error) {
577
+ try {
578
+ socket.destroy()
579
+ } catch {
580
+ // Already gone.
581
+ }
582
+ throw error instanceof ProxyError ? error : new ProxyError('protocol', error instanceof Error ? error.message : String(error), proxy.kind)
583
+ } finally {
584
+ clearTimeout(timer)
585
+ }
586
+ }
587
+
588
+ /** HTTP CONNECT: one request line, optional Basic auth, then a 2xx. */
589
+ async function httpTunnel(
590
+ socket: Socket,
591
+ reader: Reader,
592
+ proxy: ProxyConfig,
593
+ host: string,
594
+ port: number,
595
+ ): Promise<void> {
596
+ const authority = host.includes(':') && !host.startsWith('[') ? `[${host}]:${port}` : `${host}:${port}`
597
+ const lines = [`CONNECT ${authority} HTTP/1.1`, `Host: ${authority}`]
598
+ if (proxy.username !== undefined) {
599
+ const token = Buffer.from(`${proxy.username}:${proxy.password ?? ''}`, 'utf8').toString('base64')
600
+ lines.push(`Proxy-Authorization: Basic ${token}`)
601
+ }
602
+ socket.write(`${lines.join('\r\n')}\r\n\r\n`)
603
+ const head = (await reader.until('\r\n\r\n')).toString('latin1')
604
+ const statusLine = head.split('\r\n')[0] ?? ''
605
+ const match = /^HTTP\/1\.[01] (\d{3})/.exec(statusLine)
606
+ if (match === null) {
607
+ throw new ProxyError('protocol', `the proxy did not answer with HTTP (got ${JSON.stringify(statusLine.slice(0, 60))})`, 'http')
608
+ }
609
+ const status = Number.parseInt(match[1] ?? '', 10)
610
+ if (status === 200 || status === 201) return
611
+ if (status === 407) {
612
+ throw new ProxyError(
613
+ 'auth',
614
+ proxy.username === undefined
615
+ ? 'the proxy requires a username and password (HTTP 407)'
616
+ : 'the proxy rejected the username and password (HTTP 407)',
617
+ 'http',
618
+ )
619
+ }
620
+ if (status === 403) throw new ProxyError('refused', 'the proxy refused this destination (HTTP 403)', 'http')
621
+ if (status === 405) throw new ProxyError('refused', 'the proxy does not allow CONNECT (HTTP 405)', 'http')
622
+ if (status === 502 || status === 503 || status === 504) {
623
+ throw new ProxyError('refused', `the proxy could not reach ${authority} (HTTP ${status})`, 'http')
624
+ }
625
+ throw new ProxyError('refused', `the proxy refused the tunnel (HTTP ${status})`, 'http')
626
+ }
627
+
628
+ /** SOCKS5: greeting, optional user/password, CONNECT, reply. */
629
+ async function socks5Tunnel(
630
+ socket: Socket,
631
+ reader: Reader,
632
+ proxy: ProxyConfig,
633
+ host: string,
634
+ port: number,
635
+ ): Promise<void> {
636
+ const wantsAuth = proxy.username !== undefined
637
+ socket.write(Buffer.from(wantsAuth ? [0x05, 0x02, 0x00, 0x02] : [0x05, 0x01, 0x00]))
638
+ const greeting = await reader.exact(2)
639
+ if (greeting[0] !== 0x05) {
640
+ throw new ProxyError('protocol', 'the proxy did not answer SOCKS5 (version byte mismatch)', 'socks5')
641
+ }
642
+ const method = greeting[1]
643
+ if (method === 0xff) {
644
+ throw new ProxyError(
645
+ 'auth',
646
+ wantsAuth ? 'the proxy rejected the offered SOCKS5 auth methods' : 'the proxy requires SOCKS5 username/password',
647
+ 'socks5',
648
+ )
649
+ }
650
+ if (method === 0x02) {
651
+ if (proxy.username === undefined) {
652
+ throw new ProxyError('auth', 'the proxy requires a SOCKS5 username and password', 'socks5')
653
+ }
654
+ const user = Buffer.from(proxy.username, 'utf8').subarray(0, 255)
655
+ const pass = Buffer.from(proxy.password ?? '', 'utf8').subarray(0, 255)
656
+ socket.write(Buffer.concat([Buffer.from([0x01, user.length]), user, Buffer.from([pass.length]), pass]))
657
+ const reply = await reader.exact(2)
658
+ if (reply[0] !== 0x01 || reply[1] !== 0x00) {
659
+ throw new ProxyError('auth', 'the proxy rejected the SOCKS5 username and password', 'socks5')
660
+ }
661
+ } else if (method !== 0x00) {
662
+ throw new ProxyError('protocol', `the proxy chose an unknown SOCKS5 auth method (${method})`, 'socks5')
663
+ }
664
+ socket.write(Buffer.concat([Buffer.from([0x05, 0x01, 0x00]), socksAddress(host, port)]))
665
+ const head = await reader.exact(4)
666
+ if (head[0] !== 0x05) throw new ProxyError('protocol', 'the proxy answered SOCKS5 CONNECT with a bad version', 'socks5')
667
+ const code = head[1] ?? 0
668
+ const atyp = head[3]
669
+ const addressBytes = atyp === 0x01 ? 4 : atyp === 0x04 ? 16 : atyp === 0x03 ? (await reader.exact(1))[0] ?? 0 : -1
670
+ if (addressBytes < 0) throw new ProxyError('protocol', 'the proxy answered SOCKS5 with an unknown address type', 'socks5')
671
+ await reader.exact(addressBytes + 2)
672
+ if (code !== 0x00) throw socksReplyError(code)
673
+ }