dsh-remote-vs 0.16.0 → 0.18.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
@@ -6,6 +6,7 @@ import { dirname, join, posix } from "node:path";
6
6
  import { homedir } from "node:os";
7
7
  import { StringDecoder } from "node:string_decoder";
8
8
  import { fileURLToPath } from "node:url";
9
+ import { createServer } from "node:net";
9
10
  import { WebSocketServer } from "ws";
10
11
  import { execFile } from "node:child_process";
11
12
  import { promisify } from "node:util";
@@ -30,9 +31,9 @@ function sameStamp(left, right) {
30
31
  return left.mtimeMs === right.mtimeMs && left.size === right.size;
31
32
  }
32
33
  /** Alias grammar: 1-64 chars of letters/digits/._- */
33
- const ALIAS_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
34
+ const ALIAS_RE$1 = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
34
35
  function assertAlias(alias) {
35
- if (typeof alias !== "string" || !ALIAS_RE.test(alias)) throw new Error("alias must match [A-Za-z0-9._-]{1,64} and start with an alphanumeric");
36
+ if (typeof alias !== "string" || !ALIAS_RE$1.test(alias)) throw new Error("alias must match [A-Za-z0-9._-]{1,64} and start with an alphanumeric");
36
37
  }
37
38
  /**
38
39
  * Replays one read-modify-write before giving up. Two processes sharing
@@ -921,6 +922,60 @@ var RemotePool = class {
921
922
  throw error;
922
923
  }
923
924
  }
925
+ /**
926
+ * Open one direct-tcpip channel to a TCP target reachable FROM the remote
927
+ * host (`ssh -L` semantics). The caller owns the channel lifecycle.
928
+ *
929
+ * Deliberately NOT routed through `acquireSlot`: that table bounds the pool's
930
+ * own request channels (exec / SFTP) and its ceiling leaves room for the
931
+ * long-lived channels the pool does not count (PTY terminals, the subprocess
932
+ * runtime, the helper). A local forward is the same kind of long-lived
933
+ * channel, so the port panel keeps its own per-alias budget instead.
934
+ *
935
+ * A channel-open failure is NOT a connection failure: sshd answers
936
+ * "administratively prohibited" when forwarding is forbidden and "connect
937
+ * failed" when the remote port is closed — both on a perfectly healthy link,
938
+ * and painting the connection chip red for either would send the user to
939
+ * debug their network. Real transport failures still arrive through the
940
+ * pooled connection's own close/error events.
941
+ */
942
+ async forwardOut(alias, dstHost, dstPort, srcPort = 0) {
943
+ const conn = await this.acquire(alias);
944
+ this.hold(alias);
945
+ /**
946
+ * What the channel-open callback does after the deadline already answered.
947
+ *
948
+ * ssh2 has no channel-open timeout (see `openSession`'s note), so the
949
+ * deadline above can fire while the callback is still in flight. Without
950
+ * this flag a late success would hand back a channel nobody owns — a
951
+ * direct-tcpip that outlives every reference to it. The late channel is
952
+ * closed here instead, and no `close`→`release` handler is attached to it
953
+ * (the hold was already released by the timeout path).
954
+ */
955
+ let settled = false;
956
+ try {
957
+ const channel = await withDeadline(new Promise((resolve, reject) => {
958
+ conn.forwardOut("127.0.0.1", srcPort, dstHost, dstPort, (error, stream) => {
959
+ if (settled) {
960
+ if (error === void 0 || error === null) try {
961
+ stream.close();
962
+ } catch {}
963
+ return;
964
+ }
965
+ settled = true;
966
+ if (error !== void 0 && error !== null) reject(error);
967
+ else resolve(stream);
968
+ });
969
+ }), CONTROL_TIMEOUT_MS, `forwarding channel to ${dstHost}:${dstPort} did not open within ${CONTROL_TIMEOUT_MS / 1e3}s`);
970
+ channel.once("close", () => this.release(alias));
971
+ this.markOk(alias);
972
+ return channel;
973
+ } catch (error) {
974
+ settled = true;
975
+ this.release(alias);
976
+ throw error;
977
+ }
978
+ }
924
979
  /** Run one callback with a fresh SFTP session (closed afterwards). */
925
980
  async withSftp(alias, fn, opts = {}) {
926
981
  await this.acquireSlot(alias);
@@ -1642,6 +1697,335 @@ function withDeadline(promise, ms, message) {
1642
1697
  });
1643
1698
  });
1644
1699
  }
1700
+ /** What every forward binds to (never a LAN address). */
1701
+ const LOOPBACK = "127.0.0.1";
1702
+ /** Alias grammar (same rule the host store enforces). */
1703
+ const ALIAS_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
1704
+ /**
1705
+ * Hostname / IPv4 / IPv6 accepted as the REMOTE target.
1706
+ *
1707
+ * The string never reaches a shell — ssh2 hands it to the server as the
1708
+ * direct-tcpip destination — so this is a sanity fence (no whitespace, no
1709
+ * control characters, bounded length) rather than escaping. A hostname with
1710
+ * underscores and an IPv6 literal with brackets are both legal here.
1711
+ */
1712
+ const REMOTE_HOST_RE = /^[A-Za-z0-9._:[\]%-]{1,255}$/;
1713
+ function messageOf$1(error) {
1714
+ return error instanceof Error ? error.message : String(error ?? "");
1715
+ }
1716
+ /**
1717
+ * Validate one request from the browser.
1718
+ *
1719
+ * `localPort` deliberately accepts 0 = "let the OS pick": the panel defaults to
1720
+ * auto-assignment because a fixed port invites EADDRINUSE from whatever else
1721
+ * the developer runs locally.
1722
+ */
1723
+ function validateForwardRequest(input) {
1724
+ if (typeof input !== "object" || input === null) return {
1725
+ ok: false,
1726
+ error: "a JSON object is required"
1727
+ };
1728
+ const raw = input;
1729
+ if (typeof raw.alias !== "string" || !ALIAS_RE.test(raw.alias)) return {
1730
+ ok: false,
1731
+ error: "alias must be 1-64 chars of letters/digits/._- and start with an alphanumeric"
1732
+ };
1733
+ if (typeof raw.remoteHost !== "string" || !REMOTE_HOST_RE.test(raw.remoteHost)) return {
1734
+ ok: false,
1735
+ error: "remoteHost must be a hostname or IP address"
1736
+ };
1737
+ const remotePort = raw.remotePort;
1738
+ if (typeof remotePort !== "number" || !Number.isInteger(remotePort) || remotePort < 1 || remotePort > 65535) return {
1739
+ ok: false,
1740
+ error: "remotePort must be an integer between 1 and 65535"
1741
+ };
1742
+ const localRaw = raw.localPort;
1743
+ let localPort = 0;
1744
+ if (localRaw !== void 0 && localRaw !== null) {
1745
+ if (typeof localRaw !== "number" || !Number.isInteger(localRaw) || localRaw < 0 || localRaw > 65535) return {
1746
+ ok: false,
1747
+ error: "localPort must be 0 (auto) or an integer between 1 and 65535"
1748
+ };
1749
+ localPort = localRaw;
1750
+ }
1751
+ return {
1752
+ ok: true,
1753
+ value: {
1754
+ alias: raw.alias,
1755
+ remoteHost: raw.remoteHost,
1756
+ remotePort,
1757
+ ...localPort === 0 ? {} : { localPort }
1758
+ }
1759
+ };
1760
+ }
1761
+ /**
1762
+ * Stable rule identity.
1763
+ *
1764
+ * `localPort` is the port the CALLER asked for (0 = auto), not the one the OS
1765
+ * assigned: asking twice for the same automatic rule must return the running
1766
+ * forward instead of opening a second listener on a second random port.
1767
+ */
1768
+ function forwardIdOf(alias, remoteHost, remotePort, localPort) {
1769
+ return `${alias}|${remoteHost}|${remotePort}|${localPort}`;
1770
+ }
1771
+ /** What the panel copies / opens for one forward. */
1772
+ function forwardLocalUrl(localPort) {
1773
+ return `http://127.0.0.1:${localPort}/`;
1774
+ }
1775
+ /** Listens on loopback and proxies every accepted connection over SSH. */
1776
+ var ForwardManager = class {
1777
+ deps;
1778
+ forwards = /* @__PURE__ */ new Map();
1779
+ /**
1780
+ * Rules whose listener is still BINDING.
1781
+ *
1782
+ * Two clicks (or a restore racing the panel's own poll) must share one bind:
1783
+ * without this map the second call binds a SECOND listener on a different
1784
+ * automatic port, overwrites the first entry in `forwards`, and leaves the
1785
+ * first listener orphaned — unreachable from the panel and never closed.
1786
+ */
1787
+ starting = /* @__PURE__ */ new Map();
1788
+ /** Set on unload so a bind that settles afterwards closes itself. */
1789
+ disposed = false;
1790
+ constructor(deps) {
1791
+ this.deps = deps;
1792
+ }
1793
+ /**
1794
+ * Start one rule (idempotent for the same requested tuple).
1795
+ *
1796
+ * Resolves with the state once the local listener is BOUND; a bind failure
1797
+ * (EADDRINUSE, permission) rejects, which the route maps to a caller-visible
1798
+ * status. A remote-side failure cannot be known yet — the first connection
1799
+ * discovers it and records it on the rule.
1800
+ */
1801
+ async start(request) {
1802
+ const requestedLocalPort = request.localPort ?? 0;
1803
+ const id = forwardIdOf(request.alias, request.remoteHost, request.remotePort, requestedLocalPort);
1804
+ const existing = this.forwards.get(id);
1805
+ if (existing !== void 0) return this.stateOf(existing);
1806
+ const inFlight = this.starting.get(id);
1807
+ if (inFlight !== void 0) return inFlight;
1808
+ const pendingOnAlias = [...this.starting.keys()].filter((key) => key.startsWith(`${request.alias}|`)).length;
1809
+ const perAlias = [...this.forwards.values()].filter((forward) => forward.alias === request.alias).length + pendingOnAlias;
1810
+ const maxPerAlias = this.deps.maxPerAlias ?? 16;
1811
+ if (perAlias >= maxPerAlias) throw new Error(`host ${request.alias} already has ${maxPerAlias} local forwards; stop one first`);
1812
+ const pending = this.bindForward(id, request, requestedLocalPort).then((forward) => {
1813
+ if (this.disposed) {
1814
+ this.closeForward(forward);
1815
+ throw new Error("the port-forward manager was unloaded while the rule was binding");
1816
+ }
1817
+ this.forwards.set(id, forward);
1818
+ this.log("info", `forward ${id} listening on 127.0.0.1:${forward.localPort}`);
1819
+ return this.stateOf(forward);
1820
+ }).finally(() => {
1821
+ this.starting.delete(id);
1822
+ });
1823
+ this.starting.set(id, pending);
1824
+ return pending;
1825
+ }
1826
+ /** Stop one rule. Returns false when the id is unknown (already stopped). */
1827
+ stop(id) {
1828
+ const forward = this.forwards.get(id);
1829
+ if (forward === void 0) return false;
1830
+ this.forwards.delete(id);
1831
+ this.closeForward(forward);
1832
+ this.log("info", `forward ${id} stopped`);
1833
+ return true;
1834
+ }
1835
+ /**
1836
+ * Stop every rule for one host alias (the host was deleted).
1837
+ *
1838
+ * A deleted host disappears from the panel — there is no row left to press
1839
+ * "stop" on — so leaving its listeners bound would squat the local ports
1840
+ * until the Host restarts. Returns how many rules were closed.
1841
+ */
1842
+ stopAlias(alias) {
1843
+ let stopped = 0;
1844
+ for (const [id, forward] of [...this.forwards]) {
1845
+ if (forward.alias !== alias) continue;
1846
+ this.forwards.delete(id);
1847
+ this.closeForward(forward);
1848
+ stopped += 1;
1849
+ }
1850
+ if (stopped > 0) this.log("info", `stopped ${stopped} forward(s) for deleted host ${alias}`);
1851
+ return stopped;
1852
+ }
1853
+ /**
1854
+ * Stop every rule but keep the manager alive (plugin disabled).
1855
+ *
1856
+ * `dispose()` is the unload path and flips a flag that makes later binds
1857
+ * throw; a settings toggle needs the listeners gone without burning the
1858
+ * instance, because re-enabling the plugin must be able to start rules again.
1859
+ */
1860
+ stopAll() {
1861
+ let stopped = 0;
1862
+ for (const id of [...this.forwards.keys()]) if (this.stop(id)) stopped += 1;
1863
+ return stopped;
1864
+ }
1865
+ /** Every rule, optionally narrowed to one host alias. */
1866
+ list(alias) {
1867
+ return [...this.forwards.values()].filter((forward) => alias === void 0 || forward.alias === alias).sort((left, right) => left.alias.localeCompare(right.alias) || left.localPort - right.localPort).map((forward) => this.stateOf(forward));
1868
+ }
1869
+ /** Close every listener and every proxied connection (plugin unload). */
1870
+ dispose() {
1871
+ this.disposed = true;
1872
+ for (const id of [...this.forwards.keys()]) this.stop(id);
1873
+ }
1874
+ /** Bind the loopback listener. Split out so the error path is one place. */
1875
+ async bindForward(id, request, requestedLocalPort) {
1876
+ const server = createServer();
1877
+ const forward = {
1878
+ id,
1879
+ alias: request.alias,
1880
+ remoteHost: request.remoteHost,
1881
+ remotePort: request.remotePort,
1882
+ localPort: 0,
1883
+ server,
1884
+ sockets: /* @__PURE__ */ new Set(),
1885
+ channels: /* @__PURE__ */ new Set(),
1886
+ bytesIn: 0,
1887
+ bytesOut: 0,
1888
+ lastError: void 0,
1889
+ startedAt: Date.now()
1890
+ };
1891
+ server.on("connection", (socket) => {
1892
+ this.accept(forward, socket);
1893
+ });
1894
+ await new Promise((resolve, reject) => {
1895
+ const onError = (error) => {
1896
+ server.removeListener("listening", onListening);
1897
+ reject(error);
1898
+ };
1899
+ const onListening = () => {
1900
+ server.removeListener("error", onError);
1901
+ resolve();
1902
+ };
1903
+ server.once("error", onError);
1904
+ server.once("listening", onListening);
1905
+ server.listen(requestedLocalPort, LOOPBACK);
1906
+ });
1907
+ forward.localPort = server.address().port;
1908
+ server.on("error", (error) => {
1909
+ forward.lastError = messageOf$1(error);
1910
+ this.log("warn", `forward ${id} listener error: ${forward.lastError}`);
1911
+ });
1912
+ return forward;
1913
+ }
1914
+ /** One accepted local TCP connection: bound, or refused when the rule is full. */
1915
+ accept(forward, socket) {
1916
+ const maxConnections = this.deps.maxConnections ?? 32;
1917
+ if (forward.sockets.size >= maxConnections) {
1918
+ forward.lastError = `too many simultaneous connections (limit ${maxConnections}); close one and retry`;
1919
+ this.log("warn", `forward ${forward.id}: ${forward.lastError}`);
1920
+ socket.destroy();
1921
+ return;
1922
+ }
1923
+ forward.sockets.add(socket);
1924
+ /**
1925
+ * A reset in the DIAL WINDOW must never crash the Host.
1926
+ *
1927
+ * `finish` — the handler that owns the socket/channel pair and absorbs both
1928
+ * errors — is attached only AFTER a channel exists. A cold dial takes
1929
+ * seconds (up to the 15 s channel-open deadline), and a client that resets
1930
+ * in that window emits `error` on a socket with no listener: Node turns
1931
+ * that into an `uncaughtException`, and the DSH Host exits on those. This
1932
+ * accept-time handler ends the local half; the later `finish` closes the
1933
+ * channel if the dial wins the race.
1934
+ */
1935
+ const dropSocket = () => {
1936
+ forward.sockets.delete(socket);
1937
+ socket.destroy();
1938
+ };
1939
+ socket.once("close", dropSocket);
1940
+ socket.once("error", dropSocket);
1941
+ this.connect(forward, socket);
1942
+ }
1943
+ /**
1944
+ * Open one direct-tcpip channel for a local socket and pipe both ways.
1945
+ *
1946
+ * The channel is opened through the pool, so a dropped SSH connection is
1947
+ * re-dialed per new local connection; an in-flight one fails with the pool's
1948
+ * reason and is recorded on the rule.
1949
+ */
1950
+ async connect(forward, socket) {
1951
+ let channel;
1952
+ try {
1953
+ channel = await this.deps.pool.forwardOut(forward.alias, forward.remoteHost, forward.remotePort);
1954
+ } catch (error) {
1955
+ forward.lastError = messageOf$1(error);
1956
+ this.log("warn", `forward ${forward.id} -> ${forward.remoteHost}:${forward.remotePort} failed: ${forward.lastError}`);
1957
+ forward.sockets.delete(socket);
1958
+ socket.destroy();
1959
+ return;
1960
+ }
1961
+ if (socket.destroyed) {
1962
+ try {
1963
+ channel.close();
1964
+ } catch {}
1965
+ return;
1966
+ }
1967
+ forward.channels.add(channel);
1968
+ forward.lastError = void 0;
1969
+ socket.on("data", (chunk) => {
1970
+ forward.bytesIn += chunk.length;
1971
+ });
1972
+ channel.on("data", (chunk) => {
1973
+ forward.bytesOut += chunk.length;
1974
+ });
1975
+ let finished = false;
1976
+ const finish = () => {
1977
+ if (finished) return;
1978
+ finished = true;
1979
+ forward.sockets.delete(socket);
1980
+ forward.channels.delete(channel);
1981
+ socket.destroy();
1982
+ try {
1983
+ channel.close();
1984
+ } catch {}
1985
+ };
1986
+ socket.once("close", finish);
1987
+ socket.once("error", finish);
1988
+ channel.once("close", finish);
1989
+ channel.once("error", finish);
1990
+ socket.pipe(channel);
1991
+ channel.pipe(socket);
1992
+ }
1993
+ /** Tear one rule down: listener, then every proxied connection. */
1994
+ closeForward(forward) {
1995
+ try {
1996
+ forward.server.close();
1997
+ } catch {}
1998
+ for (const socket of [...forward.sockets]) try {
1999
+ socket.destroy();
2000
+ } catch {}
2001
+ forward.sockets.clear();
2002
+ for (const channel of [...forward.channels]) try {
2003
+ channel.close();
2004
+ } catch {}
2005
+ forward.channels.clear();
2006
+ }
2007
+ stateOf(forward) {
2008
+ return {
2009
+ id: forward.id,
2010
+ alias: forward.alias,
2011
+ remoteHost: forward.remoteHost,
2012
+ remotePort: forward.remotePort,
2013
+ localPort: forward.localPort,
2014
+ localUrl: forwardLocalUrl(forward.localPort),
2015
+ state: forward.lastError === void 0 ? "listening" : "error",
2016
+ connections: forward.sockets.size,
2017
+ bytesIn: forward.bytesIn,
2018
+ bytesOut: forward.bytesOut,
2019
+ ...forward.lastError === void 0 ? {} : { lastError: forward.lastError },
2020
+ startedAt: forward.startedAt
2021
+ };
2022
+ }
2023
+ log(level, message) {
2024
+ try {
2025
+ this.deps.log?.(level, message);
2026
+ } catch {}
2027
+ }
2028
+ };
1645
2029
  //#endregion
1646
2030
  //#region src/http.ts
1647
2031
  const JSON_HEADERS = {
@@ -1804,7 +2188,11 @@ const REMOTE_API = {
1804
2188
  /** Current working directory of one live session (click resolution helper). */
1805
2189
  sessionCwd: "/api/dsh-remote/session-cwd",
1806
2190
  /** What one live session changed on its remote host (the review panel). */
1807
- changes: "/api/dsh-remote/changes"
2191
+ changes: "/api/dsh-remote/changes",
2192
+ /** Local TCP forwards (`ssh -L` semantics) for the port panel. */
2193
+ forwards: "/api/dsh-remote/forwards",
2194
+ /** Remote listening TCP sockets for the port panel (one bounded probe). */
2195
+ listenPorts: "/api/dsh-remote/listen-ports"
1808
2196
  };
1809
2197
  /** Suggested/attachment file name for one multi-selection archive. */
1810
2198
  function selectionDownloadName(count) {
@@ -2465,6 +2853,180 @@ var TerminalSessionRegistry = class {
2465
2853
  }
2466
2854
  };
2467
2855
  //#endregion
2856
+ //#region src/listen-ports.ts
2857
+ /** Prefix of every control line the probe prints (also the "did it answer" proof). */
2858
+ const LISTEN_PORTS_MARK = "@@RVS-PORTS";
2859
+ /**
2860
+ * Budget for the whole probe. A handful of local commands over one channel; if
2861
+ * `ss` hangs (a stuck kernel table), the route answers with the exec deadline
2862
+ * instead of holding the panel's refresh forever.
2863
+ */
2864
+ const LISTEN_PORTS_TIMEOUT_MS = 15e3;
2865
+ /**
2866
+ * The remote probe line.
2867
+ *
2868
+ * `if/elif/fi` rather than `a && b || c` chains: the shell's operator
2869
+ * precedence would make a failing `ss` fall through into `netstat`'s branch in
2870
+ * ways that depend on the last command's status, and one missing tool would be
2871
+ * indistinguishable from a tool that ran and failed.
2872
+ *
2873
+ * `-p` is requested first and silently degrades to `-n`: it only ADDS process
2874
+ * names, and it is allowed for a non-root user (the kernel just omits other
2875
+ * users' sockets). `netstat -an` is the last resort for macOS, whose `-l` is
2876
+ * not the Linux spelling; the parser understands both the colon and the dotted
2877
+ * `addr.port` form.
2878
+ */
2879
+ function listenPortsCommand() {
2880
+ return [
2881
+ "export LC_ALL=C",
2882
+ "if command -v ss >/dev/null 2>&1; then",
2883
+ ` echo "${LISTEN_PORTS_MARK} ss"`,
2884
+ " ss -ltnp 2>/dev/null || ss -ltn 2>/dev/null",
2885
+ "elif command -v netstat >/dev/null 2>&1; then",
2886
+ ` echo "${LISTEN_PORTS_MARK} netstat"`,
2887
+ " netstat -ltnp 2>/dev/null || netstat -ltn 2>/dev/null || netstat -an 2>/dev/null",
2888
+ "else",
2889
+ ` echo "${LISTEN_PORTS_MARK} none"`,
2890
+ "fi",
2891
+ `echo "${LISTEN_PORTS_MARK} end"`
2892
+ ].join("\n");
2893
+ }
2894
+ function splitAddressPort(value) {
2895
+ let addr;
2896
+ let portText;
2897
+ const dotted = /^(.*)\.(\d+)$/.exec(value);
2898
+ if (dotted !== null) {
2899
+ addr = dotted[1];
2900
+ portText = dotted[2];
2901
+ } else if (value.includes(":")) {
2902
+ const at = value.lastIndexOf(":");
2903
+ addr = value.slice(0, at);
2904
+ portText = value.slice(at + 1);
2905
+ if (addr.startsWith("[") && addr.endsWith("]")) addr = addr.slice(1, -1);
2906
+ } else return;
2907
+ if (addr === "" || !/^[0-9]+$/.test(portText)) return void 0;
2908
+ const port = Number(portText);
2909
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return void 0;
2910
+ return {
2911
+ addr,
2912
+ port
2913
+ };
2914
+ }
2915
+ /** `[::]:22` → `[::]` for display; the bracket strip above already handles it. */
2916
+ function normalizeAddr(addr) {
2917
+ if (addr === "" || addr === "*") return "*";
2918
+ return addr;
2919
+ }
2920
+ /** Process name out of `users:(("sshd",pid=1,fd=3))`, if the tool printed one. */
2921
+ function processOf(text) {
2922
+ const match = /users:\(\("([^"]+)"/.exec(text);
2923
+ if (match !== null) return match[1];
2924
+ const short = /(?:^|\s)[0-9]+\/([^\s/]+)/.exec(text);
2925
+ return short === null ? void 0 : short[1];
2926
+ }
2927
+ /** One `ss -ltn[p]` row, or undefined for headers/foreign lines. */
2928
+ function parseSsLine(line) {
2929
+ if (!line.startsWith("LISTEN ")) return void 0;
2930
+ const fields = line.split(/\s+/);
2931
+ const local = fields[3];
2932
+ if (local === void 0) return void 0;
2933
+ const split = splitAddressPort(local);
2934
+ if (split === void 0) return void 0;
2935
+ const process = fields.length > 5 ? processOf(fields.slice(5).join(" ")) : void 0;
2936
+ return {
2937
+ addr: normalizeAddr(split.addr),
2938
+ port: split.port,
2939
+ ...process === void 0 ? {} : { process }
2940
+ };
2941
+ }
2942
+ /** One `netstat -ltn[p]` / `netstat -an` row, or undefined for headers. */
2943
+ function parseNetstatLine(line) {
2944
+ if (!/^tcp[0-9]*\s/.test(line)) return void 0;
2945
+ const fields = line.split(/\s+/);
2946
+ const stateAt = fields.indexOf("LISTEN");
2947
+ if (stateAt < 0) return void 0;
2948
+ const local = fields[3];
2949
+ if (local === void 0) return void 0;
2950
+ const split = splitAddressPort(local);
2951
+ if (split === void 0) return void 0;
2952
+ const tail = fields.slice(stateAt + 1).join(" ");
2953
+ const process = tail === "" ? void 0 : processOf(tail);
2954
+ return {
2955
+ addr: normalizeAddr(split.addr),
2956
+ port: split.port,
2957
+ ...process === void 0 ? {} : { process }
2958
+ };
2959
+ }
2960
+ /**
2961
+ * Parse one probe's stdout into the panel's result.
2962
+ *
2963
+ * @param stdout - the probe's standard output (both tools plus markers).
2964
+ * @param exitCode - the exec exit code; a non-zero run with no `end` marker is
2965
+ * reported as `unknown`, because an interrupted probe proves nothing about
2966
+ * the ports it never reached.
2967
+ */
2968
+ function parseListenPorts(stdout, exitCode) {
2969
+ let tool = "unknown";
2970
+ let sawEnd = false;
2971
+ /** Lines that looked like a candidate row, for the "parsed nothing" verdict. */
2972
+ let sawCandidate = false;
2973
+ const seen = /* @__PURE__ */ new Map();
2974
+ for (const raw of stdout.split("\n")) {
2975
+ const line = raw.trim();
2976
+ if (line === "") continue;
2977
+ if (line.startsWith("@@RVS-PORTS")) {
2978
+ const arg = line.slice(11).trim();
2979
+ if (arg === "end") sawEnd = true;
2980
+ else if (arg === "ss" || arg === "netstat" || arg === "none") tool = arg;
2981
+ continue;
2982
+ }
2983
+ const parsed = tool === "ss" ? parseSsLine(line) : tool === "netstat" ? parseNetstatLine(line) : void 0;
2984
+ if (parsed !== void 0) {
2985
+ const key = `${parsed.addr}|${parsed.port}`;
2986
+ if (!seen.has(key)) seen.set(key, parsed);
2987
+ sawCandidate = true;
2988
+ continue;
2989
+ }
2990
+ if (tool === "ss" && line.startsWith("LISTEN ")) sawCandidate = true;
2991
+ if (tool === "netstat" && /^tcp[0-9]*\s/.test(line) && line.includes("LISTEN")) sawCandidate = true;
2992
+ }
2993
+ if (tool === "none") return {
2994
+ tool,
2995
+ ports: [],
2996
+ error: "neither ss nor netstat is installed on the remote host"
2997
+ };
2998
+ if (tool === "unknown") return {
2999
+ tool,
3000
+ ports: [],
3001
+ error: "the remote probe did not answer (no marker line in its output)"
3002
+ };
3003
+ if (!sawEnd && exitCode !== null && exitCode !== 0) return {
3004
+ tool,
3005
+ ports: [],
3006
+ error: `the remote probe exited with code ${exitCode} before it finished`
3007
+ };
3008
+ if (exitCode === null) return {
3009
+ tool: "unknown",
3010
+ ports: [],
3011
+ error: "the remote probe ended without an exit status (the SSH channel closed)"
3012
+ };
3013
+ const ports = [...seen.values()].sort((left, right) => left.port - right.port || (left.addr < right.addr ? -1 : left.addr > right.addr ? 1 : 0));
3014
+ if (ports.length === 0 && sawCandidate) return {
3015
+ tool,
3016
+ ports: [],
3017
+ error: `${tool} printed listening sockets but the output could not be parsed`
3018
+ };
3019
+ if (ports.length > 500) return {
3020
+ tool,
3021
+ ports: ports.slice(0, 500),
3022
+ error: `only the first 500 listening sockets are listed`
3023
+ };
3024
+ return {
3025
+ tool,
3026
+ ports
3027
+ };
3028
+ }
3029
+ //#endregion
2468
3030
  //#region src/routes.ts
2469
3031
  /** One noServer WebSocket server for terminal upgrades (RFC 6455). */
2470
3032
  const terminalWss = new WebSocketServer({
@@ -2641,6 +3203,7 @@ function makeRoutes(deps) {
2641
3203
  const timeouts = () => deps.timeouts?.() ?? DEFAULT_TIMEOUTS;
2642
3204
  const files = new RemoteFiles(pool);
2643
3205
  const terminalSessions = new TerminalSessionRegistry(pool);
3206
+ const forwards = deps.forwards;
2644
3207
  /**
2645
3208
  * Stream one remote `tar -czf -` command into a `.tar.gz` download response.
2646
3209
  *
@@ -2782,6 +3345,7 @@ function makeRoutes(deps) {
2782
3345
  return;
2783
3346
  }
2784
3347
  if (method === "DELETE") {
3348
+ forwards?.stopAlias(alias);
2785
3349
  pool.forget(alias);
2786
3350
  worlds.dropHost(alias).catch(() => void 0);
2787
3351
  if (!store.remove(alias)) {
@@ -3583,6 +4147,97 @@ function makeRoutes(deps) {
3583
4147
  }
3584
4148
  writeJson(res, 200, { ok: terminalSessions.close(body.id) });
3585
4149
  }
4150
+ },
4151
+ {
4152
+ kind: "exact",
4153
+ path: REMOTE_API.forwards,
4154
+ handler: async (req, res) => {
4155
+ if (!isLoopbackRequest(req)) {
4156
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
4157
+ return;
4158
+ }
4159
+ if (forwards === void 0) {
4160
+ writeJson(res, 503, { error: "port forwarding is not available in this composition" });
4161
+ return;
4162
+ }
4163
+ const url = new URL(req.url ?? "/", "http://localhost");
4164
+ if (req.method === "GET") {
4165
+ const alias = queryParam(url, "alias");
4166
+ writeJson(res, 200, { forwards: forwards.list(alias === void 0 || alias === "" ? void 0 : alias) });
4167
+ return;
4168
+ }
4169
+ if (req.method === "DELETE") {
4170
+ const id = queryParam(url, "id");
4171
+ if (id === void 0 || id === "") {
4172
+ writeJson(res, 400, { error: "id query parameter is required" });
4173
+ return;
4174
+ }
4175
+ writeJson(res, 200, { ok: forwards.stop(id) });
4176
+ return;
4177
+ }
4178
+ if (req.method !== "POST") {
4179
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` });
4180
+ return;
4181
+ }
4182
+ const read = await readBodyOrError(req, res, { objectOnly: true });
4183
+ if (!read.ok) return;
4184
+ const validated = validateForwardRequest(read.body);
4185
+ if (!validated.ok) {
4186
+ writeJson(res, 400, { error: validated.error });
4187
+ return;
4188
+ }
4189
+ try {
4190
+ writeJson(res, 200, { forward: await forwards.start(validated.value) });
4191
+ } catch (error) {
4192
+ const message = error instanceof Error ? error.message : String(error);
4193
+ writeJson(res, /EADDRINUSE|EACCES|already in use|already has \d+ local forwards|permission denied|not permitted/i.test(message) ? 409 : 502, { error: message });
4194
+ }
4195
+ }
4196
+ },
4197
+ {
4198
+ kind: "exact",
4199
+ path: REMOTE_API.listenPorts,
4200
+ handler: async (req, res) => {
4201
+ if (!isLoopbackRequest(req)) {
4202
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
4203
+ return;
4204
+ }
4205
+ if (req.method !== "GET") {
4206
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` });
4207
+ return;
4208
+ }
4209
+ const alias = queryParam(new URL(req.url ?? "/", "http://localhost"), "alias");
4210
+ if (alias === void 0 || alias === "") {
4211
+ writeJson(res, 400, { error: "alias query parameter is required" });
4212
+ return;
4213
+ }
4214
+ try {
4215
+ const result = await pool.exec(alias, listenPortsCommand(), { timeoutMs: LISTEN_PORTS_TIMEOUT_MS });
4216
+ if (result.error !== void 0) {
4217
+ writeJson(res, 502, { error: result.error });
4218
+ return;
4219
+ }
4220
+ if (result.timedOut) {
4221
+ writeJson(res, 200, {
4222
+ tool: "unknown",
4223
+ ports: [],
4224
+ error: `the remote probe did not finish within ${LISTEN_PORTS_TIMEOUT_MS / 1e3}s`
4225
+ });
4226
+ return;
4227
+ }
4228
+ if (result.exitCode === null) {
4229
+ writeJson(res, 200, {
4230
+ tool: "unknown",
4231
+ ports: [],
4232
+ error: "the remote probe ended without an exit status (the SSH channel closed)"
4233
+ });
4234
+ return;
4235
+ }
4236
+ writeJson(res, 200, parseListenPorts(result.stdout, result.exitCode));
4237
+ } catch (error) {
4238
+ writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
4239
+ }
4240
+ }
3586
4241
  }
3587
4242
  ],
3588
4243
  upgrade: {
@@ -5659,13 +6314,33 @@ function apply(ctx, config) {
5659
6314
  ctx.effect(() => () => {
5660
6315
  changes.dispose();
5661
6316
  }, "dsh-remote-vs: changes ledger");
6317
+ /**
6318
+ * Local port forwards (`ssh -L`) — resident listeners with their own
6319
+ * lifecycle, on purpose.
6320
+ *
6321
+ * A forward's listener must survive `sync()` erasing and re-registering the
6322
+ * route table (a settings edit must not kill a tunnel), so the manager is not
6323
+ * created inside `makeRoutes`; the routes only see its CRUD face. Its effect
6324
+ * is registered BEFORE the routes effect, so unload closes routes first, then
6325
+ * the forwards (their channels still need a live pool), and the pool last.
6326
+ */
6327
+ const forwards = new ForwardManager({
6328
+ pool,
6329
+ log: (level, message) => {
6330
+ try {
6331
+ if (level === "warn") ctx.logger.warn(`[remote-vs] forwards: ${message}`);
6332
+ else ctx.logger.info(`[remote-vs] forwards: ${message}`);
6333
+ } catch {}
6334
+ }
6335
+ });
5662
6336
  const { routes, upgrade, terminalSessions } = makeRoutes({
5663
6337
  store,
5664
6338
  pool,
5665
6339
  worlds,
5666
6340
  ctx,
5667
6341
  timeouts: resolveTimeoutsNow,
5668
- changes
6342
+ changes,
6343
+ forwards
5669
6344
  });
5670
6345
  /**
5671
6346
  * PTY sessions own their own lifetime, separate from route registration.
@@ -5687,6 +6362,15 @@ function apply(ctx, config) {
5687
6362
  ctx.effect(() => () => {
5688
6363
  terminalSessions.dispose();
5689
6364
  }, "dsh-remote-vs: terminal sessions");
6365
+ /**
6366
+ * Forwards close after routes (no new local connection can arrive once the
6367
+ * route table is gone) and BEFORE the pool is disposed (a channel close still
6368
+ * needs a live connection). Registered before `sync()` creates the routes
6369
+ * effect, so the reverse-order cleanup above holds.
6370
+ */
6371
+ ctx.effect(() => () => {
6372
+ forwards.dispose();
6373
+ }, "dsh-remote-vs: port forwards");
5690
6374
  let disposeRoutes;
5691
6375
  const tools = [
5692
6376
  remoteHostsTool({
@@ -5726,7 +6410,10 @@ function apply(ctx, config) {
5726
6410
  disposeTools = void 0;
5727
6411
  }
5728
6412
  const value = resolve();
5729
- if (!value.enabled) return;
6413
+ if (!value.enabled) {
6414
+ forwards.stopAll();
6415
+ return;
6416
+ }
5730
6417
  if (value.announceToAgent) disposeSection = ctx.systemPrompt.section({
5731
6418
  name: "plugin:dsh-remote-vs",
5732
6419
  order: 60,