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/lib/index.js CHANGED
@@ -4,13 +4,619 @@ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readF
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { dirname, join, posix } from "node:path";
6
6
  import { homedir } from "node:os";
7
+ import { createConnection, createServer } from "node:net";
7
8
  import { StringDecoder } from "node:string_decoder";
8
9
  import { fileURLToPath } from "node:url";
9
- import { createServer } from "node:net";
10
10
  import { WebSocketServer } from "ws";
11
11
  import { execFile } from "node:child_process";
12
12
  import { promisify } from "node:util";
13
13
  import { defineTool } from "@deepseek-ai/dsh-tools";
14
+ //#region src/proxy.ts
15
+ /**
16
+ * Outbound proxy support for SSH dials.
17
+ *
18
+ * Why this is not just `HTTP_PROXY`: ssh2 dials a raw TCP socket, and the
19
+ * harness's proxy plumbing (`@deepseek-ai/dsh-http-proxy`) only wraps `fetch`,
20
+ * so a host that can only be reached through a proxy needs the tunnel built
21
+ * here. Three flavours, in the order a user meets them:
22
+ *
23
+ * - `http` — `CONNECT host:port`, optional `Proxy-Authorization: Basic …`;
24
+ * - `socks5` — greeting / optional user+password sub-negotiation / CONNECT;
25
+ * - jump (`ProxyJump` / `ProxyCommand ssh -W`) — NOT dialled here: the pool
26
+ * opens a `direct-tcpip` channel on ANOTHER pooled connection and hands it
27
+ * to ssh2 as its socket. This module only parses those specs into a target.
28
+ *
29
+ * **Error taxonomy is the point.** "The proxy refused the tunnel" and "the
30
+ * target closed the port" and "your password is wrong" all fail the dial, and
31
+ * the user debugs the wrong thing if they all read "connection failed". Each
32
+ * failure therefore leaves as a `ProxyError` with a stable `reason` and one
33
+ * actionable sentence.
34
+ *
35
+ * **Bytes are never lost.** A proxy may send tunnel bytes in the same packet as
36
+ * its handshake reply; everything read past the handshake is pushed back onto
37
+ * the socket before it is handed to ssh2, or the SSH banner would be swallowed
38
+ * and the handshake would stall.
39
+ *
40
+ * @module
41
+ */
42
+ /** A proxy dial failure that knows which layer broke. */
43
+ var ProxyError = class extends Error {
44
+ reason;
45
+ kind;
46
+ constructor(reason, message, kind) {
47
+ super(message);
48
+ this.reason = reason;
49
+ this.kind = kind;
50
+ this.name = "ProxyError";
51
+ }
52
+ };
53
+ /** Hostname / IPv4 / IPv6 accepted as a proxy or destination. */
54
+ const HOST_RE = /^[A-Za-z0-9._:[\]%-]{1,255}$/;
55
+ /** Longest credential string accepted (a proxy config, not a password manager). */
56
+ const MAX_CREDENTIAL = 255;
57
+ function cleanCredential(value) {
58
+ if (typeof value !== "string") return void 0;
59
+ if (value === "") return void 0;
60
+ return value.length > MAX_CREDENTIAL ? value.slice(0, MAX_CREDENTIAL) : value;
61
+ }
62
+ /**
63
+ * Validate one proxy endpoint.
64
+ *
65
+ * @param input - value as it arrived from the browser / store file.
66
+ * @returns the normalized config (empty credentials dropped).
67
+ * @throws {ProxyError} `target` when a field is unusable, with the field named.
68
+ */
69
+ function normalizeProxy(input) {
70
+ if (typeof input !== "object" || input === null) throw new ProxyError("target", "proxy must be an object");
71
+ const raw = input;
72
+ const kind = raw.kind;
73
+ if (kind !== "http" && kind !== "socks5") throw new ProxyError("target", "proxy.kind must be 'http' or 'socks5'");
74
+ if (typeof raw.host !== "string" || !HOST_RE.test(raw.host)) throw new ProxyError("target", "proxy.host must be a hostname or IP address");
75
+ const port = raw.port;
76
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) throw new ProxyError("target", "proxy.port must be an integer between 1 and 65535");
77
+ const username = cleanCredential(raw.username);
78
+ const password = cleanCredential(raw.password);
79
+ return {
80
+ kind,
81
+ host: raw.host,
82
+ port,
83
+ ...username === void 0 ? {} : { username },
84
+ ...password === void 0 ? {} : { password }
85
+ };
86
+ }
87
+ /** One `user@host:port` hop of a ProxyJump chain. */
88
+ function parseHop(token) {
89
+ const at = token.lastIndexOf("@");
90
+ const user = at < 0 ? void 0 : token.slice(0, at);
91
+ const rest = at < 0 ? token : token.slice(at + 1);
92
+ if (rest === "") return void 0;
93
+ if (rest.includes(" [") || /\s/.test(rest)) return void 0;
94
+ let host = rest;
95
+ let port = 22;
96
+ const bracket = /^\[(.+)\]:(\d+)$/.exec(rest);
97
+ if (bracket !== null) {
98
+ host = `[${bracket[1]}]`;
99
+ port = Number.parseInt(bracket[2] ?? "", 10);
100
+ } else if (rest.startsWith("[") && rest.endsWith("]")) host = rest;
101
+ else {
102
+ const colon = rest.lastIndexOf(":");
103
+ if (colon > 0) {
104
+ const tail = rest.slice(colon + 1);
105
+ if (/^\d+$/.test(tail)) {
106
+ host = rest.slice(0, colon);
107
+ port = Number.parseInt(tail, 10);
108
+ }
109
+ }
110
+ }
111
+ if (!HOST_RE.test(host)) return void 0;
112
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
113
+ return {
114
+ ...user === void 0 || user === "" ? {} : { user },
115
+ host,
116
+ port
117
+ };
118
+ }
119
+ /**
120
+ * Parse an OpenSSH `ProxyJump` value (`jump`, `user@jump:2222`, `a,b`).
121
+ *
122
+ * Only a single hop is supported: the pool builds the tunnel on one existing
123
+ * pooled connection, and a chain would need nested channels whose failure modes
124
+ * we cannot explain to the user yet. Multi-hop is therefore a named refusal
125
+ * rather than a silent half-feature.
126
+ */
127
+ function parseProxyJump(value) {
128
+ const hops = value.split(",").map((hop) => hop.trim()).filter((hop) => hop !== "");
129
+ if (hops.length === 0) return {
130
+ ok: false,
131
+ reason: "ProxyJump names no host"
132
+ };
133
+ if (hops.length > 1) return {
134
+ ok: false,
135
+ reason: `ProxyJump with ${hops.length} hops is not supported (one jump host only)`
136
+ };
137
+ const target = parseHop(hops[0] ?? "");
138
+ if (target === void 0) return {
139
+ ok: false,
140
+ reason: "ProxyJump must look like user@host:port"
141
+ };
142
+ return {
143
+ ok: true,
144
+ target
145
+ };
146
+ }
147
+ /** One tokenized ProxyCommand word (quotes dropped, `%h`/`%p` kept verbatim). */
148
+ function tokenize(command) {
149
+ const out = [];
150
+ let current = "";
151
+ let quote;
152
+ for (const char of command) {
153
+ if (quote !== void 0) {
154
+ if (char === quote) quote = void 0;
155
+ else current += char;
156
+ continue;
157
+ }
158
+ if (char === "\"" || char === "'") {
159
+ quote = char;
160
+ continue;
161
+ }
162
+ if (/\s/.test(char)) {
163
+ if (current !== "") out.push(current);
164
+ current = "";
165
+ continue;
166
+ }
167
+ current += char;
168
+ }
169
+ if (current !== "") out.push(current);
170
+ return out;
171
+ }
172
+ /** `host:port` used by nc/ncat proxy arguments. */
173
+ function parseProxyAddress(value) {
174
+ const colon = value.lastIndexOf(":");
175
+ if (colon <= 0) return void 0;
176
+ const host = value.slice(0, colon);
177
+ const port = Number.parseInt(value.slice(colon + 1), 10);
178
+ if (!HOST_RE.test(host)) return void 0;
179
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
180
+ return {
181
+ host,
182
+ port
183
+ };
184
+ }
185
+ /**
186
+ * Map the ProxyCommand forms users actually write onto a tunnel we can build.
187
+ *
188
+ * Recognised: `ssh … -W %h:%p [user@]host`, `nc -X connect -x host:port %h %p`
189
+ * (http), `nc -x host:port %h %p` (socks5), `ncat --proxy … --proxy-type …`.
190
+ * Everything else is refused by name — a ProxyCommand is a shell command, and
191
+ * running one from a browser-supplied config is not a feature this plugin
192
+ * offers.
193
+ */
194
+ function parseProxyCommand(command) {
195
+ const words = tokenize(command);
196
+ if (words.length === 0) return {
197
+ kind: "unsupported",
198
+ reason: "ProxyCommand is empty"
199
+ };
200
+ const program = (words[0] ?? "").split(/[\\/]/).pop() ?? "";
201
+ if (program === "ssh") {
202
+ /**
203
+ * `ssh -W %h:%p bastion` — the canonical ProxyCommand — puts the DESTINATION
204
+ * in `-W`'s argument and the JUMP HOST in the positional argument. Reading
205
+ * `-W`'s value as the jump host is the mistake this loop exists to avoid:
206
+ * it is always the literal `%h:%p`.
207
+ */
208
+ let forwards = false;
209
+ let user;
210
+ let port;
211
+ let destination;
212
+ for (let index = 1; index < words.length; index += 1) {
213
+ const word = words[index] ?? "";
214
+ if (word === "-W" || word.startsWith("-W")) {
215
+ forwards = true;
216
+ if (word === "-W") index += 1;
217
+ continue;
218
+ }
219
+ if (word === "-l" || word === "-p" || word === "-o" || word === "-i" || word === "-F" || word === "-J") {
220
+ const value = words[index + 1];
221
+ if (word === "-l") user = value;
222
+ if (word === "-p") {
223
+ const parsedPort = Number.parseInt(value ?? "", 10);
224
+ if (Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535) port = parsedPort;
225
+ }
226
+ index += 1;
227
+ continue;
228
+ }
229
+ if (word.startsWith("-")) continue;
230
+ destination ??= word;
231
+ }
232
+ if (!forwards) return {
233
+ kind: "unsupported",
234
+ reason: "ProxyCommand ssh must use -W %h:%p"
235
+ };
236
+ if (destination === void 0) return {
237
+ kind: "unsupported",
238
+ reason: "ProxyCommand ssh -W names no jump host"
239
+ };
240
+ const parsed = parseHop(user === void 0 || user === "" ? destination : `${user}@${destination}`);
241
+ if (parsed === void 0) return {
242
+ kind: "unsupported",
243
+ reason: "ProxyCommand ssh -W: the jump host is not a host name"
244
+ };
245
+ return {
246
+ kind: "jump",
247
+ target: {
248
+ ...parsed,
249
+ ...port === void 0 ? {} : { port }
250
+ }
251
+ };
252
+ }
253
+ if (program === "nc" || program === "netcat") {
254
+ const x = words.indexOf("-X");
255
+ const xMode = x < 0 ? void 0 : words[x + 1] ?? "";
256
+ const dash = words.indexOf("-x");
257
+ const address = dash < 0 ? void 0 : parseProxyAddress(words[dash + 1] ?? "");
258
+ if (address === void 0) return {
259
+ kind: "unsupported",
260
+ reason: "ProxyCommand nc must name a proxy with -x host:port"
261
+ };
262
+ if (xMode === "connect" || xMode === "http") return {
263
+ kind: "proxy",
264
+ proxy: {
265
+ kind: "http",
266
+ ...address
267
+ }
268
+ };
269
+ if (xMode === void 0 || xMode === "5" || xMode === "socks5") return {
270
+ kind: "proxy",
271
+ proxy: {
272
+ kind: "socks5",
273
+ ...address
274
+ }
275
+ };
276
+ return {
277
+ kind: "unsupported",
278
+ reason: `ProxyCommand nc -X ${xMode} is not supported`
279
+ };
280
+ }
281
+ if (program === "ncat") {
282
+ const at = words.indexOf("--proxy");
283
+ const address = at < 0 ? void 0 : parseProxyAddress(words[at + 1] ?? "");
284
+ if (address === void 0) return {
285
+ kind: "unsupported",
286
+ reason: "ProxyCommand ncat must name --proxy host:port"
287
+ };
288
+ const typeAt = words.indexOf("--proxy-type");
289
+ const type = typeAt < 0 ? "http" : words[typeAt + 1] ?? "http";
290
+ if (type === "http") return {
291
+ kind: "proxy",
292
+ proxy: {
293
+ kind: "http",
294
+ ...address
295
+ }
296
+ };
297
+ if (type === "socks5") return {
298
+ kind: "proxy",
299
+ proxy: {
300
+ kind: "socks5",
301
+ ...address
302
+ }
303
+ };
304
+ return {
305
+ kind: "unsupported",
306
+ reason: `ProxyCommand ncat --proxy-type ${type} is not supported`
307
+ };
308
+ }
309
+ return {
310
+ kind: "unsupported",
311
+ reason: `ProxyCommand program ${program === "" ? "(none)" : program} is not supported (only ssh -W, nc -X connect -x and ncat --proxy)`
312
+ };
313
+ }
314
+ /** Buffered reads over one socket, keeping every byte it saw. */
315
+ var Reader = class {
316
+ socket;
317
+ buffer = Buffer.alloc(0);
318
+ waiter;
319
+ ended = false;
320
+ failure;
321
+ /** Bound handlers, kept so `detach` can remove exactly what was added. */
322
+ onData = (chunk) => {
323
+ this.buffer = Buffer.concat([this.buffer, chunk]);
324
+ this.wake();
325
+ };
326
+ onError = (error) => {
327
+ this.failure = error;
328
+ this.wake();
329
+ };
330
+ onClose = () => {
331
+ this.ended = true;
332
+ this.wake();
333
+ };
334
+ constructor(socket) {
335
+ this.socket = socket;
336
+ socket.on("data", this.onData);
337
+ socket.once("error", this.onError);
338
+ socket.once("close", this.onClose);
339
+ }
340
+ wake() {
341
+ const waiter = this.waiter;
342
+ this.waiter = void 0;
343
+ waiter?.();
344
+ }
345
+ /** Wait for more bytes; false when the socket closed or failed. */
346
+ async more() {
347
+ if (this.failure !== void 0) throw this.failure;
348
+ if (this.ended) return;
349
+ await new Promise((resolve) => {
350
+ this.waiter = resolve;
351
+ });
352
+ }
353
+ /** Read until `marker` inclusive (used for the HTTP header block). */
354
+ async until(marker) {
355
+ for (;;) {
356
+ const at = this.buffer.indexOf(marker);
357
+ if (at >= 0) {
358
+ const end = at + marker.length;
359
+ const head = this.buffer.subarray(0, end);
360
+ this.buffer = this.buffer.subarray(end);
361
+ return head;
362
+ }
363
+ await this.more();
364
+ if (this.failure !== void 0) throw this.failure;
365
+ if (this.ended) throw new ProxyError("protocol", "the proxy closed the tunnel before answering");
366
+ }
367
+ }
368
+ /** Read exactly `count` bytes (SOCKS replies). */
369
+ async exact(count) {
370
+ for (;;) {
371
+ if (this.buffer.length >= count) {
372
+ const head = this.buffer.subarray(0, count);
373
+ this.buffer = this.buffer.subarray(count);
374
+ return head;
375
+ }
376
+ await this.more();
377
+ if (this.failure !== void 0) throw this.failure;
378
+ if (this.ended) throw new ProxyError("protocol", "the proxy closed the tunnel before answering");
379
+ }
380
+ }
381
+ /** Push back tunnel bytes that arrived with the handshake reply. */
382
+ release() {
383
+ if (this.buffer.length > 0) {
384
+ const leftover = this.buffer;
385
+ this.buffer = Buffer.alloc(0);
386
+ this.socket.unshift(leftover);
387
+ }
388
+ }
389
+ /**
390
+ * Stop observing the socket after a successful handshake.
391
+ *
392
+ * Without this the `data` listener keeps appending every tunnelled byte to
393
+ * `buffer` for the whole life of the connection — an unbounded leak on an SSH
394
+ * session that moves a few files. The socket belongs to the caller from here on
395
+ * (ssh2 becomes its only reader).
396
+ *
397
+ * Called BEFORE `release()`: an attached `data` listener would immediately
398
+ * consume the pushed-back bytes into `buffer` again, and the handover would lose
399
+ * the SSH banner it just rescued.
400
+ */
401
+ detach() {
402
+ this.socket.off("data", this.onData);
403
+ this.socket.off("error", this.onError);
404
+ this.socket.off("close", this.onClose);
405
+ }
406
+ };
407
+ /** The four octets of a dotted-quad IPv4 literal, or `undefined`. */
408
+ function ipv4Octets(value) {
409
+ const parts = value.split(".");
410
+ if (parts.length !== 4) return void 0;
411
+ const octets = [];
412
+ for (const part of parts) {
413
+ if (!/^\d{1,3}$/.test(part)) return void 0;
414
+ const octet = Number.parseInt(part, 10);
415
+ if (octet > 255) return void 0;
416
+ octets.push(octet);
417
+ }
418
+ return octets;
419
+ }
420
+ /**
421
+ * Expand one IPv6 literal into its eight 16-bit groups, or `undefined`.
422
+ *
423
+ * A SOCKS5 CONNECT carries the target as BYTES, so the literal has to be
424
+ * expanded before it is encoded — and `::` is what makes that non-obvious. The
425
+ * first cut appended a single `'0'` group wherever the text was short, so every
426
+ * compressed form encoded a DIFFERENT address than it names (`2001:db8::1` became
427
+ * `2001:db8:0:0:1:0:0:0`, `::1` became `0:0:0:1:0:0:0:0`): the tunnel opened,
428
+ * nothing errored, and the dial reached a host nobody asked for. Handing back
429
+ * `undefined` for an unexpandable literal is the point — the caller refuses the
430
+ * dial instead of encoding something.
431
+ *
432
+ * Accepted: exactly one `::` anywhere (leading / middle / trailing), eight
433
+ * explicit groups when there is no `::`, and a dotted IPv4 in the LAST group
434
+ * (RFC 4291 §2.2.3, e.g. `::ffff:1.2.3.4`). Two `::`, too many or too few
435
+ * groups, bad hex and a bad quad are all `undefined`, never a guess.
436
+ */
437
+ function expandIPv6(value) {
438
+ const halves = value.split("::");
439
+ if (halves.length > 2) return void 0;
440
+ const compressed = halves.length === 2;
441
+ const readGroups = (part) => {
442
+ if (part === void 0 || part === "") return [];
443
+ const groups = part.split(":");
444
+ const out = [];
445
+ for (let index = 0; index < groups.length; index += 1) {
446
+ const group = groups[index];
447
+ if (group.includes(".")) {
448
+ if (index !== groups.length - 1) return void 0;
449
+ const octets = ipv4Octets(group);
450
+ if (octets === void 0) return void 0;
451
+ const [a = 0, b = 0, c = 0, d = 0] = octets;
452
+ out.push(a << 8 | b, c << 8 | d);
453
+ continue;
454
+ }
455
+ if (!/^[0-9A-Fa-f]{1,4}$/.test(group)) return void 0;
456
+ out.push(Number.parseInt(group, 16));
457
+ }
458
+ return out;
459
+ };
460
+ const head = readGroups(halves[0]);
461
+ const tail = compressed ? readGroups(halves[1]) : [];
462
+ if (head === void 0 || tail === void 0) return void 0;
463
+ const explicit = head.length + tail.length;
464
+ if (!compressed) return explicit === 8 ? head : void 0;
465
+ if (explicit > 7) return void 0;
466
+ return [
467
+ ...head,
468
+ ...Array.from({ length: 8 - explicit }, () => 0),
469
+ ...tail
470
+ ];
471
+ }
472
+ /** Encode one SOCKS5 target address (domain / IPv4 / IPv6). */
473
+ function socksAddress(host, port) {
474
+ const bare = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
475
+ const portBytes = Buffer.alloc(2);
476
+ portBytes.writeUInt16BE(port, 0);
477
+ const octets = ipv4Octets(bare);
478
+ if (octets !== void 0) return Buffer.concat([
479
+ Buffer.from([1]),
480
+ Buffer.from(octets),
481
+ portBytes
482
+ ]);
483
+ if (bare.includes(":")) {
484
+ const groups = expandIPv6(bare);
485
+ if (groups === void 0) throw new ProxyError("target", bare.includes("%") ? `destination ${JSON.stringify(host)} is scoped (link-local); SOCKS5 cannot carry a zone id` : `destination ${JSON.stringify(host)} is not a valid IPv6 address`, "socks5");
486
+ const bytes = groups.flatMap((group) => [group >> 8 & 255, group & 255]);
487
+ return Buffer.concat([
488
+ Buffer.from([4]),
489
+ Buffer.from(bytes),
490
+ portBytes
491
+ ]);
492
+ }
493
+ const name = Buffer.from(bare, "utf8");
494
+ return Buffer.concat([
495
+ Buffer.from([3, name.length]),
496
+ name,
497
+ portBytes
498
+ ]);
499
+ }
500
+ /** One SOCKS5 reply code as an actionable failure. */
501
+ function socksReplyError(code) {
502
+ switch (code) {
503
+ case 2: return new ProxyError("refused", "the proxy does not allow this connection (SOCKS5 rule denied)", "socks5");
504
+ case 3: return new ProxyError("refused", "the proxy cannot reach the network (SOCKS5: network unreachable)", "socks5");
505
+ case 4: return new ProxyError("refused", "the proxy cannot reach the host (SOCKS5: host unreachable)", "socks5");
506
+ case 5: return new ProxyError("refused", "the connection was refused by the target host (via SOCKS5)", "socks5");
507
+ case 6: return new ProxyError("refused", "the connection timed out at the proxy (SOCKS5: TTL expired)", "socks5");
508
+ case 7: return new ProxyError("refused", "the proxy does not support CONNECT (SOCKS5: command not supported)", "socks5");
509
+ case 8: return new ProxyError("protocol", "the proxy does not accept this address type (SOCKS5)", "socks5");
510
+ default: return new ProxyError("refused", `the proxy refused the tunnel (SOCKS5 reply ${code})`, "socks5");
511
+ }
512
+ }
513
+ /**
514
+ * Dial `host:port` through `proxy` and hand back the tunnelled socket.
515
+ *
516
+ * The caller owns the socket (ssh2 takes it as its transport). Everything read
517
+ * past the handshake is pushed back, so the SSH banner is not swallowed.
518
+ *
519
+ * @throws {ProxyError} when the proxy layer — not SSH — is what failed.
520
+ */
521
+ async function openProxySocket(proxy, host, port, options = {}) {
522
+ if (host === "" || !HOST_RE.test(host) || !Number.isInteger(port) || port < 1 || port > 65535) throw new ProxyError("target", `destination must be host:port, got ${JSON.stringify(`${host}:${port}`)}`);
523
+ const budget = options.timeoutMs ?? 8e3;
524
+ const socket = (options.connect ?? ((target, targetPort) => createConnection({
525
+ host: target,
526
+ port: targetPort
527
+ })))(proxy.host, proxy.port);
528
+ const reader = new Reader(socket);
529
+ const timer = setTimeout(() => {
530
+ socket.destroy(new ProxyError("timeout", `the proxy ${proxy.host}:${proxy.port} did not answer within ${budget / 1e3}s`, proxy.kind));
531
+ }, budget);
532
+ timer.unref?.();
533
+ try {
534
+ await new Promise((resolve, reject) => {
535
+ socket.once("connect", () => resolve());
536
+ socket.once("error", (error) => {
537
+ const code = error.code;
538
+ reject(code === "ECONNREFUSED" || code === "EHOSTUNREACH" || code === "ENETUNREACH" || code === "EACCES" || code === "ENOTFOUND" || code === "EAI_AGAIN" || code === "ETIMEDOUT" ? new ProxyError("unreachable", `cannot reach the proxy ${proxy.host}:${proxy.port} (${code ?? error.message})`, proxy.kind) : error);
539
+ });
540
+ });
541
+ if (proxy.kind === "http") await httpTunnel(socket, reader, proxy, host, port);
542
+ else await socks5Tunnel(socket, reader, proxy, host, port);
543
+ reader.detach();
544
+ reader.release();
545
+ return socket;
546
+ } catch (error) {
547
+ try {
548
+ socket.destroy();
549
+ } catch {}
550
+ throw error instanceof ProxyError ? error : new ProxyError("protocol", error instanceof Error ? error.message : String(error), proxy.kind);
551
+ } finally {
552
+ clearTimeout(timer);
553
+ }
554
+ }
555
+ /** HTTP CONNECT: one request line, optional Basic auth, then a 2xx. */
556
+ async function httpTunnel(socket, reader, proxy, host, port) {
557
+ const authority = host.includes(":") && !host.startsWith("[") ? `[${host}]:${port}` : `${host}:${port}`;
558
+ const lines = [`CONNECT ${authority} HTTP/1.1`, `Host: ${authority}`];
559
+ if (proxy.username !== void 0) {
560
+ const token = Buffer.from(`${proxy.username}:${proxy.password ?? ""}`, "utf8").toString("base64");
561
+ lines.push(`Proxy-Authorization: Basic ${token}`);
562
+ }
563
+ socket.write(`${lines.join("\r\n")}\r\n\r\n`);
564
+ const statusLine = (await reader.until("\r\n\r\n")).toString("latin1").split("\r\n")[0] ?? "";
565
+ const match = /^HTTP\/1\.[01] (\d{3})/.exec(statusLine);
566
+ if (match === null) throw new ProxyError("protocol", `the proxy did not answer with HTTP (got ${JSON.stringify(statusLine.slice(0, 60))})`, "http");
567
+ const status = Number.parseInt(match[1] ?? "", 10);
568
+ if (status === 200 || status === 201) return;
569
+ if (status === 407) throw new ProxyError("auth", proxy.username === void 0 ? "the proxy requires a username and password (HTTP 407)" : "the proxy rejected the username and password (HTTP 407)", "http");
570
+ if (status === 403) throw new ProxyError("refused", "the proxy refused this destination (HTTP 403)", "http");
571
+ if (status === 405) throw new ProxyError("refused", "the proxy does not allow CONNECT (HTTP 405)", "http");
572
+ if (status === 502 || status === 503 || status === 504) throw new ProxyError("refused", `the proxy could not reach ${authority} (HTTP ${status})`, "http");
573
+ throw new ProxyError("refused", `the proxy refused the tunnel (HTTP ${status})`, "http");
574
+ }
575
+ /** SOCKS5: greeting, optional user/password, CONNECT, reply. */
576
+ async function socks5Tunnel(socket, reader, proxy, host, port) {
577
+ const wantsAuth = proxy.username !== void 0;
578
+ socket.write(Buffer.from(wantsAuth ? [
579
+ 5,
580
+ 2,
581
+ 0,
582
+ 2
583
+ ] : [
584
+ 5,
585
+ 1,
586
+ 0
587
+ ]));
588
+ const greeting = await reader.exact(2);
589
+ if (greeting[0] !== 5) throw new ProxyError("protocol", "the proxy did not answer SOCKS5 (version byte mismatch)", "socks5");
590
+ const method = greeting[1];
591
+ if (method === 255) throw new ProxyError("auth", wantsAuth ? "the proxy rejected the offered SOCKS5 auth methods" : "the proxy requires SOCKS5 username/password", "socks5");
592
+ if (method === 2) {
593
+ if (proxy.username === void 0) throw new ProxyError("auth", "the proxy requires a SOCKS5 username and password", "socks5");
594
+ const user = Buffer.from(proxy.username, "utf8").subarray(0, 255);
595
+ const pass = Buffer.from(proxy.password ?? "", "utf8").subarray(0, 255);
596
+ socket.write(Buffer.concat([
597
+ Buffer.from([1, user.length]),
598
+ user,
599
+ Buffer.from([pass.length]),
600
+ pass
601
+ ]));
602
+ const reply = await reader.exact(2);
603
+ if (reply[0] !== 1 || reply[1] !== 0) throw new ProxyError("auth", "the proxy rejected the SOCKS5 username and password", "socks5");
604
+ } else if (method !== 0) throw new ProxyError("protocol", `the proxy chose an unknown SOCKS5 auth method (${method})`, "socks5");
605
+ socket.write(Buffer.concat([Buffer.from([
606
+ 5,
607
+ 1,
608
+ 0
609
+ ]), socksAddress(host, port)]));
610
+ const head = await reader.exact(4);
611
+ if (head[0] !== 5) throw new ProxyError("protocol", "the proxy answered SOCKS5 CONNECT with a bad version", "socks5");
612
+ const code = head[1] ?? 0;
613
+ const atyp = head[3];
614
+ const addressBytes = atyp === 1 ? 4 : atyp === 4 ? 16 : atyp === 3 ? (await reader.exact(1))[0] ?? 0 : -1;
615
+ if (addressBytes < 0) throw new ProxyError("protocol", "the proxy answered SOCKS5 with an unknown address type", "socks5");
616
+ await reader.exact(addressBytes + 2);
617
+ if (code !== 0) throw socksReplyError(code);
618
+ }
619
+ //#endregion
14
620
  //#region src/store.ts
15
621
  /**
16
622
  * Durable store for dsh-remote-vs: hosts + workspace bindings in
@@ -25,6 +631,41 @@ function emptyDoc() {
25
631
  tombstones: []
26
632
  };
27
633
  }
634
+ /** The proxy modes a stored host decision may name. */
635
+ const PROXY_MODES = [
636
+ "inherit",
637
+ "direct",
638
+ "proxy",
639
+ "jump"
640
+ ];
641
+ /** Narrow an untrusted value to a declared mode (garbage falls back to `inherit`). */
642
+ function proxyModeOf(mode) {
643
+ return PROXY_MODES.includes(mode) ? mode : "inherit";
644
+ }
645
+ /** Message of an error without assuming it is an `Error`. */
646
+ function messageOf$4(error) {
647
+ return error instanceof Error ? error.message : String(error);
648
+ }
649
+ /**
650
+ * Read a stored default-proxy block, tolerating hand-edited garbage.
651
+ *
652
+ * A malformed value is DROPPED (→ direct) rather than throwing: a store file an
653
+ * older version or a text editor touched must still load, and "direct" is the
654
+ * behaviour an upgrade would have had anyway.
655
+ */
656
+ function sanitizeDefaultProxy(value) {
657
+ if (typeof value !== "object" || value === null) return void 0;
658
+ const raw = value;
659
+ if (raw.proxy === void 0) return { mode: raw.mode === "proxy" ? "proxy" : "direct" };
660
+ try {
661
+ return {
662
+ mode: raw.mode === "proxy" ? "proxy" : "direct",
663
+ proxy: normalizeProxy(raw.proxy)
664
+ };
665
+ } catch {
666
+ return { mode: "direct" };
667
+ }
668
+ }
28
669
  /** Same file identity (both absent counts as same). */
29
670
  function sameStamp$1(left, right) {
30
671
  if (left === null || right === null) return left === right;
@@ -125,7 +766,11 @@ var RemoteStore = class {
125
766
  version: 1,
126
767
  hosts: doc.hosts,
127
768
  workspaces: doc.workspaces,
128
- tombstones: Array.isArray(doc.tombstones) ? doc.tombstones.filter((t) => typeof t === "string") : []
769
+ tombstones: Array.isArray(doc.tombstones) ? doc.tombstones.filter((t) => typeof t === "string") : [],
770
+ ...(() => {
771
+ const defaultProxy = sanitizeDefaultProxy(doc.defaultProxy);
772
+ return defaultProxy === void 0 ? {} : { defaultProxy };
773
+ })()
129
774
  };
130
775
  }
131
776
  save() {
@@ -232,10 +877,15 @@ var RemoteStore = class {
232
877
  port: patch.port ?? current.port,
233
878
  user: patch.user ?? current.user,
234
879
  auth,
880
+ proxy: patch.proxy ?? current.proxy,
235
881
  description: patch.description ?? current.description,
236
882
  tags: patch.tags ?? current.tags
237
883
  };
238
884
  const next = this.normalize(merged, current);
885
+ if (proxyModeOf(next.proxy?.mode) === "jump" && proxyModeOf(current.proxy?.mode) !== "jump") {
886
+ const dependent = this.doc.hosts.find((host) => host.alias !== alias && proxyModeOf(host.proxy?.mode) === "jump" && host.proxy?.jump?.viaAlias === alias);
887
+ if (dependent !== void 0) throw new Error(`host "${dependent.alias}" jumps through this host; change it first`);
888
+ }
239
889
  this.doc.hosts[index] = next;
240
890
  return next;
241
891
  });
@@ -274,6 +924,7 @@ var RemoteStore = class {
274
924
  } else if (typeof auth.password !== "string" || auth.password === "") throw new Error("auth.password must be a non-empty string for password auth");
275
925
  if (payload.description !== void 0 && typeof payload.description !== "string") throw new Error("description must be a string when provided");
276
926
  if (payload.tags !== void 0 && (!Array.isArray(payload.tags) || payload.tags.some((t) => typeof t !== "string"))) throw new Error("tags must be string[] when provided");
927
+ const proxy = payload.proxy === void 0 ? void 0 : this.validateHostProxy(payload.proxy, payload.alias, current);
277
928
  const now = Date.now();
278
929
  return {
279
930
  alias: payload.alias,
@@ -286,6 +937,7 @@ var RemoteStore = class {
286
937
  ...auth.passphrase !== void 0 ? { passphrase: auth.passphrase } : {},
287
938
  ...auth.password !== void 0 ? { password: auth.password } : {}
288
939
  },
940
+ ...proxy === void 0 ? {} : { proxy },
289
941
  ...payload.description !== void 0 ? { description: payload.description } : {},
290
942
  tags: payload.tags ?? [],
291
943
  ...current?.deploy !== void 0 ? { deploy: current.deploy } : {},
@@ -293,6 +945,91 @@ var RemoteStore = class {
293
945
  updatedAt: now
294
946
  };
295
947
  }
948
+ /**
949
+ * Validate one host's stored proxy decision.
950
+ *
951
+ * The rules are the ones the two-level model needs to stay explainable:
952
+ * - the mode is one of the four declared values;
953
+ * - `proxy` needs an endpoint, `jump` needs another EXISTING alias (a host
954
+ * cannot jump through itself, and a chain is impossible to resolve with one
955
+ * pooled hop);
956
+ * - fields that the chosen mode does not use are DROPPED rather than stored, so
957
+ * switching modes cannot leave a stale endpoint behind that a later reader
958
+ * would take for the active one.
959
+ *
960
+ * @returns the normalized setting, or undefined for `inherit` (stored as the
961
+ * field's absence, which is what older files have).
962
+ */
963
+ validateHostProxy(input, alias, current) {
964
+ if (typeof input !== "object" || input === null) throw new Error("proxy must be an object");
965
+ const mode = input.mode;
966
+ if (!PROXY_MODES.includes(mode)) throw new Error("proxy.mode must be inherit, direct, proxy or jump");
967
+ if (mode === "inherit") return void 0;
968
+ if (mode === "direct") return { mode };
969
+ if (mode === "proxy") {
970
+ if (input.proxy === void 0) throw new Error("proxy.mode \"proxy\" requires a proxy endpoint");
971
+ return {
972
+ mode,
973
+ proxy: this.mergeProxyTarget(input.proxy, current?.proxy?.proxy)
974
+ };
975
+ }
976
+ const viaAlias = input.jump?.viaAlias;
977
+ if (typeof viaAlias !== "string" || viaAlias === "") throw new Error("proxy.mode \"jump\" requires proxy.jump.viaAlias");
978
+ if (viaAlias === alias) throw new Error("proxy.jump.viaAlias must name another host, not this one");
979
+ if (!this.doc.hosts.some((host) => host.alias === viaAlias)) throw new Error(`proxy.jump.viaAlias: unknown host alias ${viaAlias}`);
980
+ return {
981
+ mode,
982
+ jump: { viaAlias }
983
+ };
984
+ }
985
+ /**
986
+ * Why a host's proxy decision cannot be used, when it cannot.
987
+ *
988
+ * Reads NEVER throw for this: a host that points at a deleted jump host must
989
+ * still be listed (with the reason on its row) instead of making the whole host
990
+ * list fail. The dial path asks {@link resolveProxy}, which does fail closed.
991
+ */
992
+ proxyProblem(entry, mode) {
993
+ const setting = entry.proxy;
994
+ if (mode === "proxy") {
995
+ if (setting?.proxy === void 0) return "proxy mode is selected but no proxy endpoint is configured";
996
+ try {
997
+ normalizeProxy(setting.proxy);
998
+ return;
999
+ } catch (error) {
1000
+ return messageOf$4(error);
1001
+ }
1002
+ }
1003
+ if (mode !== "jump") return void 0;
1004
+ const viaAlias = setting?.jump?.viaAlias;
1005
+ if (viaAlias === void 0 || viaAlias === "") return "jump mode is selected but no jump host is configured";
1006
+ if (viaAlias === entry.alias) return "a host cannot jump through itself";
1007
+ const via = this.doc.hosts.find((host) => host.alias === viaAlias);
1008
+ if (via === void 0) return `jump host "${viaAlias}" is not configured`;
1009
+ if (proxyModeOf(via.proxy?.mode) === "jump") return `jump host "${viaAlias}" itself uses a jump host (one hop only)`;
1010
+ }
1011
+ /** Secret-free view of one stored proxy endpoint. */
1012
+ targetView(setting) {
1013
+ return {
1014
+ kind: setting.kind,
1015
+ host: setting.host,
1016
+ port: setting.port,
1017
+ ...setting.username === void 0 || setting.username === "" ? {} : { username: setting.username },
1018
+ hasPassword: typeof setting.password === "string" && setting.password !== ""
1019
+ };
1020
+ }
1021
+ /** Secret-free view of one host's proxy decision (always present). */
1022
+ proxyView(entry) {
1023
+ const mode = proxyModeOf(entry.proxy?.mode);
1024
+ const view = { mode };
1025
+ if (entry.proxy?.proxy !== void 0) try {
1026
+ view.target = this.targetView(normalizeProxy(entry.proxy.proxy));
1027
+ } catch {}
1028
+ if (entry.proxy?.jump?.viaAlias !== void 0) view.jumpVia = entry.proxy.jump.viaAlias;
1029
+ const problem = this.proxyProblem(entry, mode);
1030
+ if (problem !== void 0) view.problem = problem;
1031
+ return view;
1032
+ }
296
1033
  /** Secret-free projection for browser/agent surfaces. */
297
1034
  summarize(entry) {
298
1035
  let keyReady = false;
@@ -311,11 +1048,117 @@ var RemoteStore = class {
311
1048
  managedKey: entry.auth.kind === "key" && entry.auth.keyPath !== void 0 && entry.auth.keyPath.startsWith(keysDir() + (process.platform === "win32" ? "\\" : "/")),
312
1049
  ...entry.description !== void 0 ? { description: entry.description } : {},
313
1050
  tags: [...entry.tags],
1051
+ proxy: this.proxyView(entry),
314
1052
  ...entry.deploy !== void 0 ? { deploy: entry.deploy } : {},
315
1053
  createdAt: entry.createdAt,
316
1054
  updatedAt: entry.updatedAt
317
1055
  };
318
1056
  }
1057
+ /** Secret-free view of the profile-wide proxy default (read-only). */
1058
+ getDefaultProxy() {
1059
+ this.reload();
1060
+ return this.defaultProxyView();
1061
+ }
1062
+ /** View of the in-memory document (no reload: callers already reloaded). */
1063
+ defaultProxyView() {
1064
+ const stored = this.doc.defaultProxy;
1065
+ const view = { defaultMode: stored?.mode === "proxy" ? "proxy" : "direct" };
1066
+ if (stored?.proxy !== void 0) try {
1067
+ view.target = this.targetView(normalizeProxy(stored.proxy));
1068
+ } catch {
1069
+ view.defaultMode = "direct";
1070
+ }
1071
+ else if (view.defaultMode === "proxy") view.defaultMode = "direct";
1072
+ return view;
1073
+ }
1074
+ /**
1075
+ * Patch the profile-wide proxy default.
1076
+ *
1077
+ * `target` semantics follow the host form: omitted keeps the stored endpoint,
1078
+ * `null` clears it, an object replaces it — and an EMPTY PASSWORD keeps the
1079
+ * stored one, because the browser never receives secrets back.
1080
+ */
1081
+ patchDefaultProxy(patch) {
1082
+ if (typeof patch !== "object" || patch === null) throw new Error("proxy settings patch must be an object");
1083
+ return this.mutate(() => {
1084
+ const current = this.doc.defaultProxy ?? { mode: "direct" };
1085
+ let proxy = current.proxy;
1086
+ if (patch.target === null) proxy = void 0;
1087
+ else if (patch.target !== void 0) proxy = this.mergeProxyTarget(patch.target, current.proxy);
1088
+ const mode = patch.defaultMode ?? current.mode;
1089
+ if (mode !== "direct" && mode !== "proxy") throw new Error("defaultMode must be 'direct' or 'proxy'");
1090
+ if (mode === "proxy" && proxy === void 0) throw new Error("defaultMode \"proxy\" requires a proxy target");
1091
+ this.doc.defaultProxy = {
1092
+ mode,
1093
+ ...proxy === void 0 ? {} : { proxy }
1094
+ };
1095
+ return this.defaultProxyView();
1096
+ });
1097
+ }
1098
+ /**
1099
+ * Normalize a patched endpoint, keeping the stored password on an empty one.
1100
+ *
1101
+ * "Empty means keep" is only sound for the SAME endpoint: the browser never
1102
+ * receives the secret back, so every PATCH of a proxied host arrives without
1103
+ * one — but when kind/host/port/username changed, the stored password is a
1104
+ * credential for a DIFFERENT server, and carrying it over would send the old
1105
+ * secret to a new address (a 407 at best, a leaked credential at worst). A
1106
+ * changed endpoint therefore drops it and the user re-enters it.
1107
+ */
1108
+ mergeProxyTarget(target, current) {
1109
+ const next = normalizeProxy(target);
1110
+ if ((typeof target.password === "string" ? target.password : "") === "") if (current !== void 0 && current.kind === next.kind && current.host === next.host && current.port === next.port && (current.username ?? "") === (next.username ?? "") && current.password !== void 0) next.password = current.password;
1111
+ else delete next.password;
1112
+ return next;
1113
+ }
1114
+ /**
1115
+ * Resolve one host's EFFECTIVE route, in the precedence the UI describes:
1116
+ * the host's own decision, else the profile default, else direct.
1117
+ *
1118
+ * Unlike {@link summarize}, this FAILS CLOSED for an unusable jump: dialing
1119
+ * through a deleted host (or a second jump) cannot work, and the caller must say
1120
+ * why instead of silently connecting some other way.
1121
+ */
1122
+ resolveProxy(alias) {
1123
+ const entry = this.require(alias);
1124
+ const mode = proxyModeOf(entry.proxy?.mode);
1125
+ if (mode === "direct") return { kind: "direct" };
1126
+ if (mode === "proxy") {
1127
+ const stored = entry.proxy?.proxy;
1128
+ if (stored === void 0) throw new Error(`host ${alias}: proxy mode is selected but no proxy endpoint is configured`);
1129
+ return {
1130
+ kind: "proxy",
1131
+ proxy: this.requireStoredProxy(stored, alias),
1132
+ source: "host"
1133
+ };
1134
+ }
1135
+ if (mode === "jump") {
1136
+ const viaAlias = entry.proxy?.jump?.viaAlias;
1137
+ if (viaAlias === void 0 || viaAlias === "") throw new Error(`host ${alias}: jump mode is selected but no jump host is configured`);
1138
+ if (viaAlias === alias) throw new Error(`host ${alias}: a host cannot jump through itself`);
1139
+ const via = this.get(viaAlias);
1140
+ if (via === void 0) throw new Error(`host ${alias}: jump host "${viaAlias}" is not configured`);
1141
+ if (proxyModeOf(via.proxy?.mode) === "jump") throw new Error(`host ${alias}: jump host "${viaAlias}" itself uses a jump host (one hop only)`);
1142
+ return {
1143
+ kind: "jump",
1144
+ viaAlias
1145
+ };
1146
+ }
1147
+ const storedDefault = this.doc.defaultProxy;
1148
+ if (storedDefault?.mode === "proxy" && storedDefault.proxy !== void 0) return {
1149
+ kind: "proxy",
1150
+ proxy: this.requireStoredProxy(storedDefault.proxy, alias),
1151
+ source: "default"
1152
+ };
1153
+ return { kind: "direct" };
1154
+ }
1155
+ requireStoredProxy(stored, alias) {
1156
+ try {
1157
+ return normalizeProxy(stored);
1158
+ } catch (error) {
1159
+ throw new Error(`host ${alias}: invalid proxy configuration (${messageOf$4(error)})`);
1160
+ }
1161
+ }
319
1162
  setDeploy(alias, state) {
320
1163
  this.mutate(() => {
321
1164
  const entry = this.doc.hosts.find((h) => h.alias === alias);
@@ -408,6 +1251,8 @@ const REMOTE_API = {
408
1251
  routing: "/api/dsh-remote/routing",
409
1252
  /** Client view preferences (auto-open the remote page + its width share). */
410
1253
  viewSettings: "/api/dsh-remote/view-settings",
1254
+ /** Profile-wide proxy default (per-host overrides live on the host rows). */
1255
+ proxySettings: "/api/dsh-remote/proxy-settings",
411
1256
  /** Current working directory of one live session (click resolution helper). */
412
1257
  sessionCwd: "/api/dsh-remote/session-cwd",
413
1258
  /** What one live session changed on its remote host (the review panel). */
@@ -591,6 +1436,33 @@ var import_lib = require_lib();
591
1436
  /** Idle time after which a pooled connection is closed. */
592
1437
  const IDLE_MS = 1800 * 1e3;
593
1438
  /**
1439
+ * How long a port forward waits for its DEDICATED connection before falling back.
1440
+ *
1441
+ * The dedicated connection is an optimization, so it must never become the reason
1442
+ * a local socket waits: a server that silently DROPS the extra connection (a very
1443
+ * common `MaxStartups` symptom) would otherwise cost the whole connect watchdog
1444
+ * (45s) per forward channel, with the user staring at a hanging page. Three
1445
+ * seconds is plenty for a second handshake to a host that is already reachable
1446
+ * (the shared connection is up by definition); past that, use the shared one and
1447
+ * let the abandoned dial finish in the background.
1448
+ *
1449
+ * Override with DSH_REMOTE_VS_FORWARD_BUDGET_MS (milliseconds, >= 10) so the gate
1450
+ * does not spend three seconds per case.
1451
+ */
1452
+ const FORWARD_DEDICATED_BUDGET_MS = (() => {
1453
+ const raw = Number(process.env.DSH_REMOTE_VS_FORWARD_BUDGET_MS);
1454
+ return Number.isFinite(raw) && raw >= 10 ? raw : 3e3;
1455
+ })();
1456
+ /**
1457
+ * How long a refused/timed-out dedicated forward connection is skipped per alias.
1458
+ *
1459
+ * A browser opens several forward channels per page; retrying the same refused
1460
+ * handshake for every one of them is exactly the waiting we just removed. One
1461
+ * minute covers the burst; `drop(alias)` (host edited/deleted) and a successful
1462
+ * dedicated connection clear it immediately.
1463
+ */
1464
+ const FORWARD_DEDICATED_BLOCK_MS = 6e4;
1465
+ /**
594
1466
  * Connection establishment timeout, including authentication.
595
1467
  *
596
1468
  * This was 15s, which is not a handshake budget so much as a CPU budget: on a
@@ -721,6 +1593,29 @@ var RemotePool = class {
721
1593
  * that refuses extra connections still gets a working terminal.
722
1594
  */
723
1595
  shellConns = /* @__PURE__ */ new Map();
1596
+ /**
1597
+ * Dedicated connections for `ssh -L` port forwards (one per alias).
1598
+ *
1599
+ * The other half of the same argument: a forwarded channel carries arbitrary
1600
+ * TCP (a database, an SSH tunnel, a whole browser page), so it is long-lived
1601
+ * and can move a lot of data. Multiplexed onto the shared connection it would
1602
+ * queue ahead of exec/SFTP channels (SSH has no per-channel priority), and a
1603
+ * remote service that stalls would hold the window `git status` needs. A
1604
+ * terminal already gets its own connection (`shellConns`); forward traffic gets
1605
+ * its own for exactly the same reason.
1606
+ *
1607
+ * Cost: one extra handshake per alias that actually receives a forwarded
1608
+ * connection, plus one held TCP connection while any of its forward channels is
1609
+ * open (the 30-minute idle eviction applies once the last one closes).
1610
+ * `forwardOut` falls back to the shared connection when this one cannot be
1611
+ * established (e.g. the server refuses extra connections), so a forward never
1612
+ * stops working because of it — it only loses the isolation.
1613
+ */
1614
+ forwardConns = /* @__PURE__ */ new Map();
1615
+ /** Aliases whose dedicated-forward downgrade was already logged (once per alias). */
1616
+ forwardFallbackNoted = /* @__PURE__ */ new Set();
1617
+ /** alias -> timestamp until which the dedicated forward connection is skipped. */
1618
+ forwardBlocked = /* @__PURE__ */ new Map();
724
1619
  /** TOFU fingerprints observed this process (alias -> sha256). */
725
1620
  hostKeys = /* @__PURE__ */ new Map();
726
1621
  /** Per-alias `setsid --wait` capability, probed once (see supportsSetsid). */
@@ -740,10 +1635,17 @@ var RemotePool = class {
740
1635
  this.setsidProbes.delete(alias);
741
1636
  this.evictFrom(this.conns, alias);
742
1637
  this.evictFrom(this.shellConns, alias);
1638
+ this.evictFrom(this.forwardConns, alias);
1639
+ this.forwardBlocked.delete(alias);
1640
+ this.forwardFallbackNoted.delete(alias);
743
1641
  }
744
1642
  /** Close every pooled connection. */
745
1643
  dispose() {
746
- for (const alias of /* @__PURE__ */ new Set([...this.conns.keys(), ...this.shellConns.keys()])) this.drop(alias);
1644
+ for (const alias of /* @__PURE__ */ new Set([
1645
+ ...this.conns.keys(),
1646
+ ...this.shellConns.keys(),
1647
+ ...this.forwardConns.keys()
1648
+ ])) this.drop(alias);
747
1649
  }
748
1650
  /**
749
1651
  * Forget one alias's connection HEALTH (host edited/removed), not just its
@@ -765,22 +1667,67 @@ var RemotePool = class {
765
1667
  */
766
1668
  status() {
767
1669
  const aliases = /* @__PURE__ */ new Set([...this.conns.keys(), ...this.health.keys()]);
1670
+ /** The host rows, read ONCE for the whole answer (see `configuredEgress`). */
1671
+ const hosts = /* @__PURE__ */ new Map();
768
1672
  try {
769
- for (const host of this.store.list()) aliases.add(host.alias);
1673
+ for (const host of this.store.list()) {
1674
+ aliases.add(host.alias);
1675
+ hosts.set(host.alias, host);
1676
+ }
770
1677
  } catch {}
771
1678
  return [...aliases].sort().map((alias) => {
772
1679
  const entry = this.health.get(alias);
773
1680
  const pooled = this.conns.get(alias);
1681
+ const egress = this.liveEgress(alias);
1682
+ const configured = egress === void 0 ? this.configuredEgress(alias, hosts.get(alias)) : void 0;
774
1683
  return {
775
1684
  alias,
776
1685
  state: entry?.state ?? "idle",
777
- open: pooled !== void 0 && pooled.connecting === void 0 || this.shellConns.get(alias)?.connecting === void 0 && this.shellConns.has(alias),
1686
+ open: pooled !== void 0 && pooled.connecting === void 0 || this.shellConns.get(alias)?.connecting === void 0 && this.shellConns.has(alias) || this.forwardConns.get(alias)?.connecting === void 0 && this.forwardConns.has(alias),
778
1687
  ...entry?.okAt === void 0 ? {} : { okAt: entry.okAt },
779
1688
  ...entry?.errorAt === void 0 ? {} : { errorAt: entry.errorAt },
780
- ...entry?.error === void 0 ? {} : { error: entry.error }
1689
+ ...entry?.error === void 0 ? {} : { error: entry.error },
1690
+ ...egress === void 0 ? {} : { egress },
1691
+ ...configured === void 0 ? {} : { configured }
781
1692
  };
782
1693
  });
783
1694
  }
1695
+ /**
1696
+ * The egress of the alias' LIVE connection, whichever class owns it.
1697
+ *
1698
+ * All three classes open through the same resolved route, so the first one
1699
+ * that is up answers for the alias; the shared connection is preferred because
1700
+ * it is the one exec/browse (the surface the chip describes) rides.
1701
+ */
1702
+ liveEgress(alias) {
1703
+ for (const map of [
1704
+ this.conns,
1705
+ this.forwardConns,
1706
+ this.shellConns
1707
+ ]) {
1708
+ const pooled = map.get(alias);
1709
+ if (pooled === void 0 || pooled.connecting !== void 0) continue;
1710
+ if (pooled.egress !== void 0) return pooled.egress;
1711
+ }
1712
+ }
1713
+ /**
1714
+ * The route the stored configuration resolves to, for an alias with NO live
1715
+ * connection. Pure observation, and absorbed: a dangling jump chain or a
1716
+ * half-configured proxy makes `resolveProxy` throw, and a status poll must
1717
+ * answer "the stored route is broken, here is why" instead of failing — the
1718
+ * chip still has to render, and a 500 would hide the reason it exists to show.
1719
+ */
1720
+ configuredEgress(alias, host) {
1721
+ if (host === void 0) return void 0;
1722
+ try {
1723
+ return egressOf(this.store.resolveProxy(alias), host);
1724
+ } catch (error) {
1725
+ return {
1726
+ ...storedEgress(host),
1727
+ problem: messageOf$3(error)
1728
+ };
1729
+ }
1730
+ }
784
1731
  /** Record a successful dial or transport-level operation. */
785
1732
  markOk(alias) {
786
1733
  this.health.set(alias, {
@@ -1184,9 +2131,39 @@ var RemotePool = class {
1184
2131
  * debug their network. Real transport failures still arrive through the
1185
2132
  * pooled connection's own close/error events.
1186
2133
  */
1187
- async forwardOut(alias, dstHost, dstPort, srcPort = 0) {
1188
- const conn = await this.acquire(alias);
1189
- this.hold(alias);
2134
+ async forwardOut(alias, dstHost, dstPort, srcPort = 0, opts = {}) {
2135
+ /**
2136
+ * Prefer the DEDICATED forward connection (see `forwardConns`). A host that
2137
+ * refuses the extra connection still forwards: the fallback is the shared
2138
+ * connection, i.e. exactly the old behaviour. The downgrade is logged once per
2139
+ * alias — a browser opens several forward channels per page, and one warning
2140
+ * per server refusal is information while one per channel is noise.
2141
+ *
2142
+ * Two short-circuits keep that preference from costing time:
2143
+ * - a recent refusal/timeout parks the alias for {@link FORWARD_DEDICATED_BLOCK_MS},
2144
+ * so the next channel goes straight to the shared connection;
2145
+ * - while a dedicated dial is already in flight, a second channel rides the
2146
+ * shared connection instead of waiting for the same handshake (it can only
2147
+ * be used by ONE `acquireIn` caller anyway).
2148
+ */
2149
+ let conn;
2150
+ let dedicated = opts.dedicated !== false;
2151
+ if (dedicated && this.forwardCoolingDown(alias)) dedicated = false;
2152
+ if (dedicated && this.forwardConns.get(alias)?.connecting !== void 0) dedicated = false;
2153
+ if (dedicated) try {
2154
+ conn = await this.acquireForward(alias);
2155
+ this.holdIn(this.forwardConns, alias);
2156
+ this.forwardBlocked.delete(alias);
2157
+ } catch (error) {
2158
+ dedicated = false;
2159
+ this.blockForward(alias, error);
2160
+ conn = await this.acquire(alias);
2161
+ this.hold(alias);
2162
+ }
2163
+ else {
2164
+ conn = await this.acquire(alias);
2165
+ this.hold(alias);
2166
+ }
1190
2167
  /**
1191
2168
  * What the channel-open callback does after the deadline already answered.
1192
2169
  *
@@ -1212,15 +2189,61 @@ var RemotePool = class {
1212
2189
  else resolve(stream);
1213
2190
  });
1214
2191
  }), CONTROL_TIMEOUT_MS, `forwarding channel to ${dstHost}:${dstPort} did not open within ${CONTROL_TIMEOUT_MS / 1e3}s`);
1215
- channel.once("close", () => this.release(alias));
1216
- this.markOk(alias);
1217
- return channel;
2192
+ channel.once("close", () => {
2193
+ if (dedicated) this.releaseIn(this.forwardConns, alias);
2194
+ else this.release(alias);
2195
+ });
2196
+ if (!dedicated) this.markOk(alias);
2197
+ return {
2198
+ channel,
2199
+ dedicated
2200
+ };
1218
2201
  } catch (error) {
1219
2202
  settled = true;
1220
- this.release(alias);
2203
+ if (dedicated) this.releaseIn(this.forwardConns, alias);
2204
+ else this.release(alias);
2205
+ /**
2206
+ * NO `markError` here — deliberately.
2207
+ *
2208
+ * ssh2 reports EVERY direct-tcpip failure as
2209
+ * `(SSH) Channel open failure: <reason>`, and the pool's
2210
+ * `CONNECTION_ERROR_RE` matches `channel open fail`. A closed remote port or
2211
+ * `AllowTcpForwarding no` therefore LOOKS like a transport failure and used
2212
+ * to paint the connection chip red (sending the user to debug a healthy
2213
+ * network, and putting the editor into read-only). The function's contract
2214
+ * is the opposite: a channel-open refusal is the RULE's failure
2215
+ * (`forward.lastError`), while real transport failures surface through the
2216
+ * pooled connection's own close/error events.
2217
+ */
1221
2218
  throw error;
1222
2219
  }
1223
2220
  }
2221
+ /**
2222
+ * Is this alias's dedicated forward connection in its short cooldown?
2223
+ *
2224
+ * Expired entries are dropped eagerly so the map cannot grow per alias forever.
2225
+ */
2226
+ forwardCoolingDown(alias) {
2227
+ const until = this.forwardBlocked.get(alias);
2228
+ if (until === void 0) return false;
2229
+ if (Date.now() >= until) {
2230
+ this.forwardBlocked.delete(alias);
2231
+ return false;
2232
+ }
2233
+ return true;
2234
+ }
2235
+ /** Park the dedicated connection for one alias and log the downgrade, once. */
2236
+ blockForward(alias, error) {
2237
+ this.forwardBlocked.set(alias, Date.now() + FORWARD_DEDICATED_BLOCK_MS);
2238
+ this.noteForwardFallback(alias, error);
2239
+ }
2240
+ /** Log one alias's forward downgrade to the shared connection, once. */
2241
+ noteForwardFallback(alias, error) {
2242
+ if (this.forwardFallbackNoted.has(alias)) return;
2243
+ this.forwardFallbackNoted.add(alias);
2244
+ const detail = error instanceof Error ? error.message : String(error ?? "");
2245
+ console.warn(`[dsh-remote-vs] dedicated forward connection to ${alias} failed; using the shared one:`, detail);
2246
+ }
1224
2247
  /** Run one callback with a fresh SFTP session (closed afterwards). */
1225
2248
  async withSftp(alias, fn, opts = {}) {
1226
2249
  await this.acquireSlot(alias);
@@ -1714,7 +2737,32 @@ var RemotePool = class {
1714
2737
  async acquireShell(alias) {
1715
2738
  return this.acquireIn(this.shellConns, alias);
1716
2739
  }
1717
- async acquireIn(map, alias) {
2740
+ /**
2741
+ * `acquire` for the dedicated port-forward connection map.
2742
+ *
2743
+ * `quiet`: a dedicated forward connection is an OPTIMIZATION. If the server
2744
+ * refuses it (MaxStartups, `MaxSessions`, a per-source limit) the forward still
2745
+ * works over the shared connection, so the shared link is healthy — painting
2746
+ * the connection chip red here would send the user to debug a network that is
2747
+ * fine (and `forwardOut` reports the rule's own error separately).
2748
+ *
2749
+ * The dial also gets its OWN short budget ({@link FORWARD_DEDICATED_BUDGET_MS}):
2750
+ * a server that silently drops the extra connection would otherwise make every
2751
+ * forward channel wait the full connect watchdog before falling back. The
2752
+ * abandoned dial keeps running — if it eventually succeeds the connection is
2753
+ * pooled and the next channel uses it; its failure is already handled inside
2754
+ * `acquireIn`.
2755
+ */
2756
+ async acquireForward(alias) {
2757
+ const dialing = this.acquireIn(this.forwardConns, alias, true);
2758
+ try {
2759
+ return await withDeadline(dialing, FORWARD_DEDICATED_BUDGET_MS, `dedicated forward connection to ${alias} did not settle within ${FORWARD_DEDICATED_BUDGET_MS / 1e3}s`);
2760
+ } catch (error) {
2761
+ dialing.catch(() => void 0);
2762
+ throw error;
2763
+ }
2764
+ }
2765
+ async acquireIn(map, alias, quiet = false) {
1718
2766
  const pooled = map.get(alias);
1719
2767
  if (pooled !== void 0 && pooled.connecting !== void 0) return pooled.connecting;
1720
2768
  if (pooled !== void 0) {
@@ -1740,7 +2788,9 @@ var RemotePool = class {
1740
2788
  * so no idle timer arms, and `dispose()` only walks the map. Without the
1741
2789
  * failure check, a failed OLD dial deletes the NEW entry by alias.
1742
2790
  */
1743
- entry.connecting = this.dial(alias).then((conn) => {
2791
+ entry.connecting = this.dial(alias, (egress) => {
2792
+ if (map.get(alias) === entry) entry.egress = egress;
2793
+ }).then((conn) => {
1744
2794
  if (map.get(alias) !== entry) {
1745
2795
  try {
1746
2796
  conn.end();
@@ -1749,22 +2799,22 @@ var RemotePool = class {
1749
2799
  }
1750
2800
  entry.conn = conn;
1751
2801
  entry.connecting = void 0;
1752
- this.markOk(alias);
2802
+ if (!quiet) this.markOk(alias);
1753
2803
  conn.on("close", () => {
1754
2804
  if (map.get(alias) !== entry) return;
1755
- this.markError(alias, /* @__PURE__ */ new Error("connection closed"));
2805
+ if (!quiet) this.markError(alias, /* @__PURE__ */ new Error("connection closed"));
1756
2806
  this.evictFrom(map, alias);
1757
2807
  });
1758
2808
  conn.on("error", (error) => {
1759
2809
  if (map.get(alias) !== entry) return;
1760
- this.markError(alias, error);
2810
+ if (!quiet) this.markError(alias, error);
1761
2811
  this.evictFrom(map, alias);
1762
2812
  });
1763
2813
  this.releaseIn(map, alias);
1764
2814
  return conn;
1765
2815
  }, (error) => {
1766
2816
  if (map.get(alias) === entry) map.delete(alias);
1767
- this.markError(alias, error);
2817
+ if (!quiet) this.markError(alias, error);
1768
2818
  throw error;
1769
2819
  });
1770
2820
  return entry.connecting;
@@ -1775,6 +2825,7 @@ var RemotePool = class {
1775
2825
  if (pooled === void 0) return;
1776
2826
  map.delete(alias);
1777
2827
  if (pooled.timer !== void 0) clearTimeout(pooled.timer);
2828
+ pooled.egress = void 0;
1778
2829
  try {
1779
2830
  pooled.conn.end();
1780
2831
  } catch {}
@@ -1790,8 +2841,74 @@ var RemotePool = class {
1790
2841
  makeClient() {
1791
2842
  return new import_lib.Client();
1792
2843
  }
1793
- dial(alias) {
2844
+ /**
2845
+ * Open one SSH connection, through whatever route the store resolves.
2846
+ *
2847
+ * Three routes, and only the first is the pre-proxy code path:
2848
+ * - `direct`: unchanged (`host` / `port` in the connect config);
2849
+ * - `proxy`: the proxy module builds the tunnel and ssh2 rides the returned
2850
+ * socket (`sock`), so `host`/`port` are deliberately omitted (ssh2 ignores
2851
+ * them when `sock` is present);
2852
+ * - `jump`: the tunnel is a `direct-tcpip` channel on the JUMP host's pooled
2853
+ * connection, held for as long as the client lives. Its close/error handlers
2854
+ * close that channel and give the hold back — a leak here would pin the jump
2855
+ * host's connection forever.
2856
+ *
2857
+ * Every failure is a DIAL failure, so it keeps the existing `markError`
2858
+ * semantics; only the message is layered, so the user can tell which hop broke:
2859
+ * `proxy auth failed: …`, `proxy refused: …`, `jump host "x" failed: …`.
2860
+ *
2861
+ * `report` receives the route this dial ACTUALLY settled on, once and only on
2862
+ * success — a caller that asked "did this go through the jump host?" must not
2863
+ * be answered from a configuration that may have changed since. It is a
2864
+ * callback rather than a wider return type so the seam keeps returning the
2865
+ * `Client` the existing callers (and gates) hand around.
2866
+ */
2867
+ async dial(alias, report) {
1794
2868
  const host = this.store.require(alias);
2869
+ /** The socket ssh2 will ride, when a proxy/jump built one. */
2870
+ let sock;
2871
+ /** Runs once: tears the tunnel down (close the channel, release the jump). */
2872
+ let releaseTunnel;
2873
+ const route = this.store.resolveProxy(alias);
2874
+ const egress = egressOf(route, host);
2875
+ if (route.kind === "proxy") {
2876
+ try {
2877
+ sock = await openProxySocket(route.proxy, host.host, host.port);
2878
+ } catch (error) {
2879
+ throw proxyDialError(error, route.proxy);
2880
+ }
2881
+ releaseTunnel = () => {
2882
+ try {
2883
+ sock?.destroy();
2884
+ } catch {}
2885
+ };
2886
+ } else if (route.kind === "jump") {
2887
+ const via = route.viaAlias;
2888
+ try {
2889
+ await this.acquire(via);
2890
+ this.hold(via);
2891
+ } catch (error) {
2892
+ throw new Error(`jump host "${via}" failed: ${messageOf$3(error)}`);
2893
+ }
2894
+ let channel;
2895
+ try {
2896
+ channel = (await this.forwardOut(via, host.host, host.port, 0, { dedicated: false })).channel;
2897
+ } catch (error) {
2898
+ this.release(via);
2899
+ throw new Error(`jump host "${via}" failed: ${messageOf$3(error)}`);
2900
+ }
2901
+ let released = false;
2902
+ releaseTunnel = () => {
2903
+ if (released) return;
2904
+ released = true;
2905
+ try {
2906
+ channel.close();
2907
+ } catch {}
2908
+ this.release(via);
2909
+ };
2910
+ sock = channel;
2911
+ }
1795
2912
  return new Promise((resolve, reject) => {
1796
2913
  const conn = this.makeClient();
1797
2914
  let settled = false;
@@ -1803,12 +2920,14 @@ var RemotePool = class {
1803
2920
  try {
1804
2921
  conn.end();
1805
2922
  } catch {}
2923
+ releaseTunnel?.();
1806
2924
  reject(explainAuthError(host, error));
1807
2925
  };
1808
2926
  conn.on("ready", () => {
1809
2927
  if (settled) return;
1810
2928
  settled = true;
1811
2929
  if (guard !== void 0) clearTimeout(guard);
2930
+ report?.(egress);
1812
2931
  resolve(conn);
1813
2932
  });
1814
2933
  conn.on("error", (error) => fail(error));
@@ -1820,6 +2939,10 @@ var RemotePool = class {
1820
2939
  * leave this promise pending forever while the caller held a channel slot.
1821
2940
  */
1822
2941
  conn.on("close", () => fail(/* @__PURE__ */ new Error("connection closed during SSH handshake")));
2942
+ if (releaseTunnel !== void 0) {
2943
+ conn.once("close", () => releaseTunnel?.());
2944
+ conn.once("error", () => releaseTunnel?.());
2945
+ }
1823
2946
  guard = setTimeout(() => {
1824
2947
  fail(/* @__PURE__ */ new Error(`SSH handshake did not settle within ${(READY_TIMEOUT_MS + DIAL_GUARD_MARGIN_MS) / 1e3}s`));
1825
2948
  }, READY_TIMEOUT_MS + DIAL_GUARD_MARGIN_MS);
@@ -1845,11 +2968,14 @@ var RemotePool = class {
1845
2968
  return true;
1846
2969
  };
1847
2970
  try {
2971
+ const transport = sock === void 0 ? {
2972
+ host: host.host,
2973
+ port: host.port
2974
+ } : { sock };
1848
2975
  if (host.auth.kind === "key") {
1849
2976
  const keyPath = host.auth.keyPath;
1850
2977
  conn.connect({
1851
- host: host.host,
1852
- port: host.port,
2978
+ ...transport,
1853
2979
  username: host.user,
1854
2980
  privateKey: readFileSync(keyPath),
1855
2981
  passphrase: host.auth.passphrase,
@@ -1859,8 +2985,7 @@ var RemotePool = class {
1859
2985
  hostVerifier
1860
2986
  });
1861
2987
  } else conn.connect({
1862
- host: host.host,
1863
- port: host.port,
2988
+ ...transport,
1864
2989
  username: host.user,
1865
2990
  password: host.auth.password,
1866
2991
  tryKeyboard: true,
@@ -1876,6 +3001,83 @@ var RemotePool = class {
1876
3001
  }
1877
3002
  };
1878
3003
  /**
3004
+ * The route one resolved proxy decision describes, in the shape the chip prints.
3005
+ *
3006
+ * `detail` is the HOP, never a sentence: the target `host:port` for a direct
3007
+ * connection, the proxy `host:port` for a tunnel, the jump host's alias for a
3008
+ * chain. The wording belongs to the localized client — a second English sentence
3009
+ * baked in here would leak into the Chinese tooltip.
3010
+ */
3011
+ function egressOf(route, host) {
3012
+ if (route.kind === "proxy") return {
3013
+ kind: "proxy",
3014
+ detail: `${route.proxy.host}:${route.proxy.port}`,
3015
+ source: route.source,
3016
+ proxyKind: route.proxy.kind
3017
+ };
3018
+ if (route.kind === "jump") return {
3019
+ kind: "jump",
3020
+ detail: route.viaAlias,
3021
+ viaAlias: route.viaAlias
3022
+ };
3023
+ return {
3024
+ kind: "direct",
3025
+ detail: `${host.host}:${host.port}`
3026
+ };
3027
+ }
3028
+ /**
3029
+ * Best-effort route from the STORED fields, for the one case `resolveProxy`
3030
+ * refuses to answer (a dangling jump chain, a self-jump, a proxy setting that
3031
+ * does not validate). The caller adds `problem` with the reason; the shape here
3032
+ * only says WHICH kind of route is broken, so the chip can name it.
3033
+ */
3034
+ function storedEgress(host) {
3035
+ const jump = host.proxy?.jump?.viaAlias;
3036
+ if (host.proxy?.mode === "jump") return {
3037
+ kind: "jump",
3038
+ detail: jump ?? "",
3039
+ ...jump === void 0 ? {} : { viaAlias: jump }
3040
+ };
3041
+ const proxy = host.proxy?.proxy;
3042
+ if (proxy !== void 0) return {
3043
+ kind: "proxy",
3044
+ detail: `${proxy.host}:${proxy.port}`,
3045
+ proxyKind: proxy.kind
3046
+ };
3047
+ return {
3048
+ kind: "direct",
3049
+ detail: `${host.host}:${host.port}`
3050
+ };
3051
+ }
3052
+ /** Message of an unknown thrown value, without assuming it is an `Error`. */
3053
+ function messageOf$3(error) {
3054
+ return error instanceof Error ? error.message : String(error ?? "");
3055
+ }
3056
+ /**
3057
+ * Fixed prefix per proxy failure reason.
3058
+ *
3059
+ * The dial fails either way; the prefix is what tells the user WHICH layer broke —
3060
+ * their password, the proxy host, the tunnel policy, or the destination. The raw
3061
+ * detail is kept after it, so nothing is lost.
3062
+ */
3063
+ const PROXY_FAILURE_PREFIX = {
3064
+ unreachable: "proxy unreachable",
3065
+ timeout: "proxy timed out",
3066
+ auth: "proxy auth failed",
3067
+ refused: "proxy refused",
3068
+ protocol: "proxy protocol error",
3069
+ target: "proxy target invalid"
3070
+ };
3071
+ /** One proxy dial failure, with the layer in front of the original message. */
3072
+ function proxyDialError(error, proxy) {
3073
+ if (error instanceof ProxyError) {
3074
+ const prefix = PROXY_FAILURE_PREFIX[error.reason];
3075
+ const where = error.reason === "target" ? "" : ` ${proxy.kind} proxy ${proxy.host}:${proxy.port}`;
3076
+ return /* @__PURE__ */ new Error(`${prefix}${where}: ${error.message}`);
3077
+ }
3078
+ return /* @__PURE__ */ new Error(`proxy failed: ${proxy.kind} proxy ${proxy.host}:${proxy.port}: ${messageOf$3(error)}`);
3079
+ }
3080
+ /**
1879
3081
  * Translate ssh2's generic auth failure into something actionable. Never
1880
3082
  * includes secrets — only the entry shape and the likely server-side causes.
1881
3083
  */
@@ -2182,6 +3384,7 @@ var ForwardManager = class {
2182
3384
  bytesIn: 0,
2183
3385
  bytesOut: 0,
2184
3386
  lastError: void 0,
3387
+ transport: void 0,
2185
3388
  startedAt: Date.now()
2186
3389
  };
2187
3390
  server.on("connection", (socket) => {
@@ -2246,7 +3449,16 @@ var ForwardManager = class {
2246
3449
  async connect(forward, socket) {
2247
3450
  let channel;
2248
3451
  try {
2249
- channel = await this.deps.pool.forwardOut(forward.alias, forward.remoteHost, forward.remotePort);
3452
+ /**
3453
+ * Ask for the host's DEDICATED forward connection: forwarding traffic is
3454
+ * long-lived and heavy, and multiplexed onto the shared connection it would
3455
+ * queue ahead of exec/SFTP channels. The pool falls back on its own when the
3456
+ * server refuses the extra connection, and tells us which one was used so
3457
+ * the row can say so.
3458
+ */
3459
+ const opened = await this.deps.pool.forwardOut(forward.alias, forward.remoteHost, forward.remotePort, 0, { dedicated: true });
3460
+ channel = opened.channel;
3461
+ forward.transport = opened.dedicated ? "dedicated" : "shared";
2250
3462
  } catch (error) {
2251
3463
  forward.lastError = messageOf$2(error);
2252
3464
  this.log("warn", `forward ${forward.id} -> ${forward.remoteHost}:${forward.remotePort} failed: ${forward.lastError}`);
@@ -2313,6 +3525,7 @@ var ForwardManager = class {
2313
3525
  bytesIn: forward.bytesIn,
2314
3526
  bytesOut: forward.bytesOut,
2315
3527
  ...forward.lastError === void 0 ? {} : { lastError: forward.lastError },
3528
+ ...forward.transport === void 0 ? {} : { transport: forward.transport },
2316
3529
  startedAt: forward.startedAt
2317
3530
  };
2318
3531
  }
@@ -2666,7 +3879,7 @@ async function bootstrap(pool, store, alias) {
2666
3879
  kind: "key",
2667
3880
  keyPath: privatePath
2668
3881
  } });
2669
- pool.drop(alias);
3882
+ pool.forget(alias);
2670
3883
  const check = await pool.test(alias);
2671
3884
  if (!check.ok) throw new Error(`key installed but key login failed: ${check.error} (password entry was already flipped; fix the key or re-enter the password)`);
2672
3885
  return {
@@ -2681,8 +3894,12 @@ async function bootstrap(pool, store, alias) {
2681
3894
  /**
2682
3895
  * One-shot importers: ~/.ssh/config and the existing dsh-ssh.json. Both only
2683
3896
  * READ the source and produce payloads for our own store — no runtime coupling.
2684
- * P0 supports direct key/password hosts only; jump/proxy/agent entries are
2685
- * reported as skipped with reasons.
3897
+ * Hosts are direct key hosts; the egress half of a `Host` block (`ProxyJump` /
3898
+ * `ProxyCommand`) is mapped onto the store's `proxy` field when it names
3899
+ * something this import actually produces, and refused BY NAME when it names a
3900
+ * form this plugin cannot dial (multi-hop, a shell command, a jump host that is
3901
+ * not part of the config). A silent skip used to be the answer to all of them;
3902
+ * "one hop, from this same config" is the honest boundary.
2686
3903
  */
2687
3904
  /** Expand a leading ~ to the user home. */
2688
3905
  function expandHome(path) {
@@ -2702,9 +3919,89 @@ function validPort(value) {
2702
3919
  if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
2703
3920
  return port;
2704
3921
  }
3922
+ /** `ProxyJump none` / `ProxyCommand none` is OpenSSH for "explicitly no proxy". */
3923
+ function isNone(value) {
3924
+ return value.trim().toLowerCase() === "none";
3925
+ }
3926
+ /**
3927
+ * Index every name an imported host answers to: its alias and its `HostName`.
3928
+ *
3929
+ * `ProxyJump bastion` may name the `Host bastion` alias or the literal hostname
3930
+ * it resolves to, so both are accepted; a name with no host behind it in THIS
3931
+ * config cannot become a `viaAlias` (the stored setting would dangle).
3932
+ */
3933
+ function nameIndex(candidates) {
3934
+ const index = /* @__PURE__ */ new Map();
3935
+ for (const candidate of candidates) {
3936
+ index.set(candidate.alias, candidate.alias);
3937
+ index.set(candidate.alias.toLowerCase(), candidate.alias);
3938
+ index.set(candidate.hostname, candidate.alias);
3939
+ index.set(candidate.hostname.toLowerCase(), candidate.alias);
3940
+ }
3941
+ return index;
3942
+ }
3943
+ /** Resolve one jump host name against the hosts this import creates. */
3944
+ function resolveJump(self, name, index) {
3945
+ const viaAlias = index.get(name) ?? index.get(name.toLowerCase());
3946
+ if (viaAlias === void 0) return {
3947
+ ok: false,
3948
+ reason: `jump host '${name}' is not imported by this config — a jump host must be one of its Host entries`
3949
+ };
3950
+ if (viaAlias === self) return {
3951
+ ok: false,
3952
+ reason: `jump host '${name}' is this host itself`
3953
+ };
3954
+ return {
3955
+ ok: true,
3956
+ proxy: {
3957
+ mode: "jump",
3958
+ jump: { viaAlias }
3959
+ }
3960
+ };
3961
+ }
3962
+ /**
3963
+ * Turn one block's egress directive into the store's proxy decision.
3964
+ *
3965
+ * Precedence matches OpenSSH (a set `ProxyJump` wins over `ProxyCommand`), and
3966
+ * everything unusable keeps the PARSER's own reason so the report says what to
3967
+ * fix ("only one hop", "not supported program") instead of a generic skip.
3968
+ */
3969
+ function resolveProxy(self, fields, index) {
3970
+ const jump = fields.get("proxyjump");
3971
+ if (jump !== void 0) {
3972
+ if (isNone(jump)) return { ok: true };
3973
+ const parsed = parseProxyJump(jump);
3974
+ if (!parsed.ok) return {
3975
+ ok: false,
3976
+ reason: parsed.reason
3977
+ };
3978
+ return resolveJump(self, parsed.target.host, index);
3979
+ }
3980
+ const command = fields.get("proxycommand");
3981
+ if (command !== void 0) {
3982
+ if (isNone(command)) return { ok: true };
3983
+ const plan = parseProxyCommand(command);
3984
+ if (plan.kind === "proxy") return {
3985
+ ok: true,
3986
+ proxy: {
3987
+ mode: "proxy",
3988
+ proxy: {
3989
+ kind: plan.proxy.kind,
3990
+ host: plan.proxy.host,
3991
+ port: plan.proxy.port
3992
+ }
3993
+ }
3994
+ };
3995
+ if (plan.kind === "jump") return resolveJump(self, plan.target.host, index);
3996
+ return {
3997
+ ok: false,
3998
+ reason: plan.reason
3999
+ };
4000
+ }
4001
+ return { ok: true };
4002
+ }
2705
4003
  /** Parse OpenSSH client config text into host payloads. */
2706
4004
  function parseSshConfig(text) {
2707
- const payloads = [];
2708
4005
  const skipped = [];
2709
4006
  const blocks = [];
2710
4007
  let current;
@@ -2735,6 +4032,7 @@ function parseSshConfig(text) {
2735
4032
  });
2736
4033
  else if (current !== void 0 && !current.fields.has(key)) current.fields.set(key, value);
2737
4034
  }
4035
+ const candidates = [];
2738
4036
  for (const block of blocks) {
2739
4037
  const concrete = block.patterns.filter((pattern) => pattern !== "" && !/[*?!]/.test(pattern));
2740
4038
  const special = block.patterns.filter((pattern) => pattern !== "" && /[*?!]/.test(pattern));
@@ -2749,13 +4047,6 @@ function parseSshConfig(text) {
2749
4047
  });
2750
4048
  continue;
2751
4049
  }
2752
- if (block.fields.has("proxyjump") || block.fields.has("proxycommand")) {
2753
- for (const alias of concrete) skipped.push({
2754
- alias,
2755
- reason: "proxyJump/proxyCommand needs P1 (direct hosts only in P0)"
2756
- });
2757
- continue;
2758
- }
2759
4050
  const rawPort = block.fields.get("port");
2760
4051
  const port = rawPort === void 0 ? 22 : validPort(rawPort);
2761
4052
  const identityFile = block.fields.get("identityfile")?.split(/\s+/)[0];
@@ -2782,18 +4073,39 @@ function parseSshConfig(text) {
2782
4073
  });
2783
4074
  continue;
2784
4075
  }
2785
- payloads.push({
4076
+ candidates.push({
2786
4077
  alias,
2787
- host: block.fields.get("hostname") ?? alias,
4078
+ hostname: block.fields.get("hostname") ?? alias,
2788
4079
  port,
2789
4080
  user,
2790
- auth: {
2791
- kind: "key",
2792
- keyPath: expandHome(identityFile)
2793
- },
2794
- tags: ["imported:ssh-config"]
4081
+ identityFile,
4082
+ fields: block.fields
4083
+ });
4084
+ }
4085
+ }
4086
+ const index = nameIndex(candidates);
4087
+ const payloads = [];
4088
+ for (const candidate of candidates) {
4089
+ const resolution = resolveProxy(candidate.alias, candidate.fields, index);
4090
+ if (!resolution.ok) {
4091
+ skipped.push({
4092
+ alias: candidate.alias,
4093
+ reason: resolution.reason
2795
4094
  });
4095
+ continue;
2796
4096
  }
4097
+ payloads.push({
4098
+ alias: candidate.alias,
4099
+ host: candidate.hostname,
4100
+ port: candidate.port,
4101
+ user: candidate.user,
4102
+ auth: {
4103
+ kind: "key",
4104
+ keyPath: expandHome(candidate.identityFile)
4105
+ },
4106
+ tags: ["imported:ssh-config"],
4107
+ ...resolution.proxy === void 0 ? {} : { proxy: resolution.proxy }
4108
+ });
2797
4109
  }
2798
4110
  return {
2799
4111
  payloads,
@@ -2831,7 +4143,7 @@ function migrateDshSsh(home = dshHome()) {
2831
4143
  if (hasProxy) {
2832
4144
  skipped.push({
2833
4145
  alias,
2834
- reason: "proxyJump/proxyCommand needs P1 (direct hosts only in P0)"
4146
+ reason: "proxyJump/proxyCommand in dsh-ssh.json is not mapped — import from ~/.ssh/config instead"
2835
4147
  });
2836
4148
  continue;
2837
4149
  }
@@ -4321,17 +5633,30 @@ function makeRoutes(deps) {
4321
5633
  });
4322
5634
  res.on("close", () => stop());
4323
5635
  };
4324
- /** Apply parsed import payloads; per-entry errors become skips. */
5636
+ /**
5637
+ * Apply parsed import payloads; per-entry errors become skips.
5638
+ *
5639
+ * Two rounds, jump rows LAST, because a `jump` decision names ANOTHER host and
5640
+ * `store.create` refuses a `viaAlias` that is not stored yet. Payload order is
5641
+ * the order of the source file, which is not a dependency order: a config that
5642
+ * writes `Host target` (`ProxyJump bastion`) before `Host bastion` used to
5643
+ * import the bastion and silently drop the host that needs it, reported only as
5644
+ * `proxy.jump.viaAlias: unknown host alias bastion`. One hop is the supported
5645
+ * shape (a jump host is never itself a jump host), so two rounds always
5646
+ * suffice; whatever is still unknown in round two is a host this import did
5647
+ * not create (it was skipped for its own reason, which the report already
5648
+ * carries), and stays a skip with the store's own wording.
5649
+ */
4325
5650
  const applyImport = (parsed) => {
4326
5651
  const imported = [];
4327
5652
  const skipped = [...parsed.skipped];
4328
- for (const payload of parsed.payloads) {
5653
+ const create = (payload) => {
4329
5654
  if (store.get(payload.alias) !== void 0) {
4330
5655
  skipped.push({
4331
5656
  alias: payload.alias,
4332
5657
  reason: "alias already exists"
4333
5658
  });
4334
- continue;
5659
+ return;
4335
5660
  }
4336
5661
  try {
4337
5662
  store.create(payload);
@@ -4342,7 +5667,9 @@ function makeRoutes(deps) {
4342
5667
  reason: error instanceof Error ? error.message : String(error)
4343
5668
  });
4344
5669
  }
4345
- }
5670
+ };
5671
+ for (const payload of parsed.payloads.filter((entry) => entry.proxy?.mode !== "jump")) create(payload);
5672
+ for (const payload of parsed.payloads.filter((entry) => entry.proxy?.mode === "jump")) create(payload);
4346
5673
  return {
4347
5674
  imported,
4348
5675
  skipped
@@ -4414,11 +5741,11 @@ function makeRoutes(deps) {
4414
5741
  return;
4415
5742
  }
4416
5743
  try {
5744
+ const entry = store.update(alias, body);
4417
5745
  pool.forget(alias);
4418
5746
  monitor.forget(alias);
4419
5747
  forgetProcesses(alias);
4420
5748
  worlds.dropHost(alias).catch(() => void 0);
4421
- const entry = store.update(alias, body);
4422
5749
  writeJson(res, 200, { host: store.summarize(entry) });
4423
5750
  } catch (error) {
4424
5751
  writeJson(res, (error instanceof Error ? error.message : "").startsWith("unknown host alias") ? 404 : 400, { error: error instanceof Error ? error.message : String(error) });
@@ -5151,6 +6478,40 @@ function makeRoutes(deps) {
5151
6478
  }
5152
6479
  }
5153
6480
  },
6481
+ {
6482
+ kind: "exact",
6483
+ path: REMOTE_API.proxySettings,
6484
+ handler: async (req, res) => {
6485
+ if (!isLoopbackRequest(req)) {
6486
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
6487
+ return;
6488
+ }
6489
+ const method = req.method ?? "GET";
6490
+ if (method === "GET") {
6491
+ try {
6492
+ writeJson(res, 200, { settings: store.getDefaultProxy() });
6493
+ } catch (error) {
6494
+ writeStoreError(res, error);
6495
+ }
6496
+ return;
6497
+ }
6498
+ if (method !== "POST" && method !== "PATCH") {
6499
+ writeJson(res, 405, { error: `method not allowed: ${method}` });
6500
+ return;
6501
+ }
6502
+ const read = await readBodyOrError(req, res, { objectOnly: true });
6503
+ if (!read.ok) return;
6504
+ try {
6505
+ writeJson(res, 200, { settings: store.patchDefaultProxy(read.body ?? {}) });
6506
+ } catch (error) {
6507
+ if (isStoreError(error)) {
6508
+ writeStoreError(res, error);
6509
+ return;
6510
+ }
6511
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
6512
+ }
6513
+ }
6514
+ },
5154
6515
  {
5155
6516
  kind: "exact",
5156
6517
  path: REMOTE_API.deploy,
@@ -7835,11 +9196,23 @@ function toAgentHostRow(host) {
7835
9196
  managedKey: host.managedKey,
7836
9197
  ...host.description !== void 0 ? { description: host.description } : {},
7837
9198
  tags: [...host.tags],
9199
+ proxy: host.proxy,
7838
9200
  createdAt: host.createdAt,
7839
9201
  updatedAt: host.updatedAt
7840
9202
  };
7841
9203
  }
7842
9204
  /**
9205
+ * One-line description of a host's effective route, for the agent table.
9206
+ *
9207
+ * `problem` is part of the value (not a separate column): a host whose jump target
9208
+ * was deleted is still listed, and the caller must see why it would fail.
9209
+ */
9210
+ function proxyLabel(proxy) {
9211
+ const target = proxy.target === void 0 ? "" : ` ${proxy.target.host}:${proxy.target.port}`;
9212
+ const route = proxy.mode === "proxy" ? `proxy${target}` : proxy.mode === "jump" ? `jump ${proxy.jumpVia ?? "?"}` : proxy.mode;
9213
+ return proxy.problem === void 0 ? route : `${route} (problem: ${proxy.problem})`;
9214
+ }
9215
+ /**
7843
9216
  * Render the host table.
7844
9217
  *
7845
9218
  * An empty list has TWO very different causes and they used to share one
@@ -7850,8 +9223,8 @@ function toAgentHostRow(host) {
7850
9223
  function renderHosts(hosts, query) {
7851
9224
  if (hosts.length === 0) return query === void 0 || query.trim() === "" ? "no remote hosts configured (add one in the Remote sidebar tab first)" : `no remote host matches "${query}" — hosts are configured, the query just filtered them all out`;
7852
9225
  return [
7853
- "alias | host | port | user | auth | key | tags | description",
7854
- "--- | --- | --- | --- | --- | --- | --- | ---",
9226
+ "alias | host | port | user | auth | key | proxy | tags | description",
9227
+ "--- | --- | --- | --- | --- | --- | --- | --- | ---",
7855
9228
  ...hosts.map((h) => [
7856
9229
  h.alias,
7857
9230
  h.host,
@@ -7859,6 +9232,7 @@ function renderHosts(hosts, query) {
7859
9232
  h.user,
7860
9233
  h.auth,
7861
9234
  h.auth === "key" ? h.keyReady ? "key-ok" : "key-missing" : "password",
9235
+ proxyLabel(h.proxy),
7862
9236
  h.tags.length > 0 ? h.tags.join(",") : "-",
7863
9237
  h.description ?? ""
7864
9238
  ].join(" | "))
@@ -7941,6 +9315,49 @@ function remoteHostsTool(deps) {
7941
9315
  items: { type: "string" },
7942
9316
  required: true
7943
9317
  },
9318
+ proxy: {
9319
+ type: "object",
9320
+ additionalProperties: false,
9321
+ required: true,
9322
+ properties: {
9323
+ mode: {
9324
+ type: "string",
9325
+ enum: [
9326
+ "inherit",
9327
+ "direct",
9328
+ "proxy",
9329
+ "jump"
9330
+ ],
9331
+ required: true
9332
+ },
9333
+ target: {
9334
+ type: "object",
9335
+ additionalProperties: false,
9336
+ properties: {
9337
+ kind: {
9338
+ type: "string",
9339
+ enum: ["http", "socks5"],
9340
+ required: true
9341
+ },
9342
+ host: {
9343
+ type: "string",
9344
+ required: true
9345
+ },
9346
+ port: {
9347
+ type: "integer",
9348
+ required: true
9349
+ },
9350
+ username: { type: "string" },
9351
+ hasPassword: {
9352
+ type: "boolean",
9353
+ required: true
9354
+ }
9355
+ }
9356
+ },
9357
+ jumpVia: { type: "string" },
9358
+ problem: { type: "string" }
9359
+ }
9360
+ },
7944
9361
  createdAt: {
7945
9362
  type: "integer",
7946
9363
  required: true