dsh-remote-vs 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +7 -3
- package/README.md +7 -3
- package/lib/client.js +914 -8
- package/lib/index.js +692 -5
- package/lib/types/client/PortsView.d.ts +30 -0
- package/lib/types/client/api.d.ts +29 -1
- package/lib/types/client/store.d.ts +1 -1
- package/lib/types/forward.d.ts +114 -0
- package/lib/types/listen-ports.d.ts +56 -0
- package/lib/types/pool.d.ts +18 -0
- package/lib/types/protocol.d.ts +72 -0
- package/lib/types/routes.d.ts +7 -0
- package/package.json +1 -1
- package/src/client/PortsView.tsx +850 -0
- package/src/client/RemoteRoot.tsx +7 -1
- package/src/client/api.ts +38 -0
- package/src/client/i18n.ts +54 -0
- package/src/client/store.tsx +2 -2
- package/src/client/vsc/vsc.css +183 -0
- package/src/forward.ts +445 -0
- package/src/index.ts +40 -1
- package/src/listen-ports.ts +241 -0
- package/src/pool.ts +63 -0
- package/src/protocol.ts +76 -0
- package/src/routes.ts +125 -0
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remote listening-TCP-socket enumeration for the port panel.
|
|
3
|
+
*
|
|
4
|
+
* One bounded POSIX one-liner does the work: `ss` (iproute2, every modern
|
|
5
|
+
* Linux) first, `netstat` as the fallback (older Linux, and macOS with a
|
|
6
|
+
* different address spelling), and an explicit `none` when neither exists. The
|
|
7
|
+
* answer is a POOL of three facts the panel must keep apart:
|
|
8
|
+
*
|
|
9
|
+
* - `none` / `unknown` are "cannot enumerate", never "no ports are open";
|
|
10
|
+
* - a tool that ran but produced nothing recognizable is a parse failure, not
|
|
11
|
+
* an empty machine;
|
|
12
|
+
* - process names are only visible for the invoking user's own processes
|
|
13
|
+
* (`ss -p` is allowed for everyone, but the kernel hides other users'
|
|
14
|
+
* sockets), so a missing name is UNKNOWN, not "not a service".
|
|
15
|
+
*
|
|
16
|
+
* Pure functions only (command builder + parser) so the gate can feed real
|
|
17
|
+
* sample outputs; the route owns the exec round trip and its deadline.
|
|
18
|
+
*/
|
|
19
|
+
import type { RemoteListenPort, RemoteListenPortsResult } from './protocol.ts'
|
|
20
|
+
|
|
21
|
+
/** Prefix of every control line the probe prints (also the "did it answer" proof). */
|
|
22
|
+
export const LISTEN_PORTS_MARK = '@@RVS-PORTS'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Budget for the whole probe. A handful of local commands over one channel; if
|
|
26
|
+
* `ss` hangs (a stuck kernel table), the route answers with the exec deadline
|
|
27
|
+
* instead of holding the panel's refresh forever.
|
|
28
|
+
*/
|
|
29
|
+
export const LISTEN_PORTS_TIMEOUT_MS = 15_000
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Most listeners one probe reports. A container host or a dev box running a
|
|
33
|
+
* port scanner can have thousands; the panel is a picker, not an inventory.
|
|
34
|
+
*/
|
|
35
|
+
export const LISTEN_PORTS_MAX = 500
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The remote probe line.
|
|
39
|
+
*
|
|
40
|
+
* `if/elif/fi` rather than `a && b || c` chains: the shell's operator
|
|
41
|
+
* precedence would make a failing `ss` fall through into `netstat`'s branch in
|
|
42
|
+
* ways that depend on the last command's status, and one missing tool would be
|
|
43
|
+
* indistinguishable from a tool that ran and failed.
|
|
44
|
+
*
|
|
45
|
+
* `-p` is requested first and silently degrades to `-n`: it only ADDS process
|
|
46
|
+
* names, and it is allowed for a non-root user (the kernel just omits other
|
|
47
|
+
* users' sockets). `netstat -an` is the last resort for macOS, whose `-l` is
|
|
48
|
+
* not the Linux spelling; the parser understands both the colon and the dotted
|
|
49
|
+
* `addr.port` form.
|
|
50
|
+
*/
|
|
51
|
+
export function listenPortsCommand(): string {
|
|
52
|
+
return [
|
|
53
|
+
// EXPORTED, not a bare assignment: a plain `LC_ALL=C` line sets the shell's
|
|
54
|
+
// own variable but does not reach the `ss`/`netstat` child processes, so a
|
|
55
|
+
// localized remote would still print translated headers and break parsing.
|
|
56
|
+
'export LC_ALL=C',
|
|
57
|
+
'if command -v ss >/dev/null 2>&1; then',
|
|
58
|
+
` echo "${LISTEN_PORTS_MARK} ss"`,
|
|
59
|
+
' ss -ltnp 2>/dev/null || ss -ltn 2>/dev/null',
|
|
60
|
+
'elif command -v netstat >/dev/null 2>&1; then',
|
|
61
|
+
` echo "${LISTEN_PORTS_MARK} netstat"`,
|
|
62
|
+
' netstat -ltnp 2>/dev/null || netstat -ltn 2>/dev/null || netstat -an 2>/dev/null',
|
|
63
|
+
'else',
|
|
64
|
+
` echo "${LISTEN_PORTS_MARK} none"`,
|
|
65
|
+
'fi',
|
|
66
|
+
`echo "${LISTEN_PORTS_MARK} end"`,
|
|
67
|
+
].join('\n')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** `0.0.0.0:22` / `[::]:22` / `*:22` / macOS `127.0.0.1.631` → addr + port. */
|
|
71
|
+
interface SplitAddress {
|
|
72
|
+
addr: string
|
|
73
|
+
port: number
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function splitAddressPort(value: string): SplitAddress | undefined {
|
|
77
|
+
let addr: string
|
|
78
|
+
let portText: string
|
|
79
|
+
// The dotted form is tried FIRST: macOS's `netstat -an` prints `127.0.0.1.631`
|
|
80
|
+
// and also `::1.9000`, where a colon split would land inside the address.
|
|
81
|
+
const dotted = /^(.*)\.(\d+)$/.exec(value)
|
|
82
|
+
if (dotted !== null) {
|
|
83
|
+
addr = dotted[1]
|
|
84
|
+
portText = dotted[2]
|
|
85
|
+
} else if (value.includes(':')) {
|
|
86
|
+
const at = value.lastIndexOf(':')
|
|
87
|
+
addr = value.slice(0, at)
|
|
88
|
+
portText = value.slice(at + 1)
|
|
89
|
+
// `[::]:22` keeps the brackets in the address column; strip them so the
|
|
90
|
+
// panel shows `::` (the conventional spelling) and the row can be copied.
|
|
91
|
+
if (addr.startsWith('[') && addr.endsWith(']')) addr = addr.slice(1, -1)
|
|
92
|
+
} else {
|
|
93
|
+
return undefined
|
|
94
|
+
}
|
|
95
|
+
if (addr === '' || !/^[0-9]+$/.test(portText)) return undefined
|
|
96
|
+
const port = Number(portText)
|
|
97
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) return undefined
|
|
98
|
+
return { addr, port }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** `[::]:22` → `[::]` for display; the bracket strip above already handles it. */
|
|
102
|
+
function normalizeAddr(addr: string): string {
|
|
103
|
+
if (addr === '' || addr === '*') return '*'
|
|
104
|
+
return addr
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Process name out of `users:(("sshd",pid=1,fd=3))`, if the tool printed one. */
|
|
108
|
+
function processOf(text: string): string | undefined {
|
|
109
|
+
const match = /users:\(\("([^"]+)"/.exec(text)
|
|
110
|
+
if (match !== null) return match[1]
|
|
111
|
+
// Linux `netstat -p` appends `1234/sshd`.
|
|
112
|
+
const short = /(?:^|\s)[0-9]+\/([^\s/]+)/.exec(text)
|
|
113
|
+
return short === null ? undefined : short[1]
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** One `ss -ltn[p]` row, or undefined for headers/foreign lines. */
|
|
117
|
+
function parseSsLine(line: string): RemoteListenPort | undefined {
|
|
118
|
+
// `ss -l` prints ONLY listening sockets, so the state column is always
|
|
119
|
+
// `LISTEN`; a header line ("State Recv-Q …") starts differently.
|
|
120
|
+
if (!line.startsWith('LISTEN ')) return undefined
|
|
121
|
+
const fields = line.split(/\s+/)
|
|
122
|
+
// 0:LISTEN 1:Recv-Q 2:Send-Q 3:Local 4:Peer [5..:Process]
|
|
123
|
+
const local = fields[3]
|
|
124
|
+
if (local === undefined) return undefined
|
|
125
|
+
const split = splitAddressPort(local)
|
|
126
|
+
if (split === undefined) return undefined
|
|
127
|
+
const process = fields.length > 5 ? processOf(fields.slice(5).join(' ')) : undefined
|
|
128
|
+
return {
|
|
129
|
+
addr: normalizeAddr(split.addr),
|
|
130
|
+
port: split.port,
|
|
131
|
+
...(process === undefined ? {} : { process }),
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** One `netstat -ltn[p]` / `netstat -an` row, or undefined for headers. */
|
|
136
|
+
function parseNetstatLine(line: string): RemoteListenPort | undefined {
|
|
137
|
+
if (!/^tcp[0-9]*\s/.test(line)) return undefined
|
|
138
|
+
const fields = line.split(/\s+/)
|
|
139
|
+
const stateAt = fields.indexOf('LISTEN')
|
|
140
|
+
if (stateAt < 0) return undefined
|
|
141
|
+
const local = fields[3]
|
|
142
|
+
if (local === undefined) return undefined
|
|
143
|
+
const split = splitAddressPort(local)
|
|
144
|
+
if (split === undefined) return undefined
|
|
145
|
+
const tail = fields.slice(stateAt + 1).join(' ')
|
|
146
|
+
const process = tail === '' ? undefined : processOf(tail)
|
|
147
|
+
return {
|
|
148
|
+
addr: normalizeAddr(split.addr),
|
|
149
|
+
port: split.port,
|
|
150
|
+
...(process === undefined ? {} : { process }),
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Parse one probe's stdout into the panel's result.
|
|
156
|
+
*
|
|
157
|
+
* @param stdout - the probe's standard output (both tools plus markers).
|
|
158
|
+
* @param exitCode - the exec exit code; a non-zero run with no `end` marker is
|
|
159
|
+
* reported as `unknown`, because an interrupted probe proves nothing about
|
|
160
|
+
* the ports it never reached.
|
|
161
|
+
*/
|
|
162
|
+
export function parseListenPorts(stdout: string, exitCode: number | null): RemoteListenPortsResult {
|
|
163
|
+
let tool: 'ss' | 'netstat' | 'none' | 'unknown' = 'unknown'
|
|
164
|
+
let sawEnd = false
|
|
165
|
+
/** Lines that looked like a candidate row, for the "parsed nothing" verdict. */
|
|
166
|
+
let sawCandidate = false
|
|
167
|
+
const seen = new Map<string, RemoteListenPort>()
|
|
168
|
+
|
|
169
|
+
for (const raw of stdout.split('\n')) {
|
|
170
|
+
const line = raw.trim()
|
|
171
|
+
if (line === '') continue
|
|
172
|
+
if (line.startsWith(LISTEN_PORTS_MARK)) {
|
|
173
|
+
const arg = line.slice(LISTEN_PORTS_MARK.length).trim()
|
|
174
|
+
if (arg === 'end') sawEnd = true
|
|
175
|
+
else if (arg === 'ss' || arg === 'netstat' || arg === 'none') tool = arg
|
|
176
|
+
continue
|
|
177
|
+
}
|
|
178
|
+
const parsed = tool === 'ss'
|
|
179
|
+
? parseSsLine(line)
|
|
180
|
+
: tool === 'netstat'
|
|
181
|
+
? parseNetstatLine(line)
|
|
182
|
+
: undefined
|
|
183
|
+
if (parsed !== undefined) {
|
|
184
|
+
const key = `${parsed.addr}|${parsed.port}`
|
|
185
|
+
if (!seen.has(key)) seen.set(key, parsed)
|
|
186
|
+
sawCandidate = true
|
|
187
|
+
continue
|
|
188
|
+
}
|
|
189
|
+
if (tool === 'ss' && line.startsWith('LISTEN ')) sawCandidate = true
|
|
190
|
+
if (tool === 'netstat' && /^tcp[0-9]*\s/.test(line) && line.includes('LISTEN')) sawCandidate = true
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (tool === 'none') {
|
|
194
|
+
return { tool, ports: [], error: 'neither ss nor netstat is installed on the remote host' }
|
|
195
|
+
}
|
|
196
|
+
if (tool === 'unknown') {
|
|
197
|
+
return {
|
|
198
|
+
tool,
|
|
199
|
+
ports: [],
|
|
200
|
+
error: 'the remote probe did not answer (no marker line in its output)',
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (!sawEnd && exitCode !== null && exitCode !== 0) {
|
|
204
|
+
return {
|
|
205
|
+
tool,
|
|
206
|
+
ports: [],
|
|
207
|
+
error: `the remote probe exited with code ${exitCode} before it finished`,
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
// A null exit code means the channel closed without telling us how the
|
|
211
|
+
// command ended: the stdout is a PREFIX, so nothing here may be presented as
|
|
212
|
+
// the complete list. The route also guards this; the parser must too, because
|
|
213
|
+
// a future caller should not have to know the route's convention.
|
|
214
|
+
if (exitCode === null) {
|
|
215
|
+
return {
|
|
216
|
+
tool: 'unknown',
|
|
217
|
+
ports: [],
|
|
218
|
+
error: 'the remote probe ended without an exit status (the SSH channel closed)',
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const ports = [...seen.values()]
|
|
222
|
+
// Code-unit ordering, not `localeCompare`: the panel's order must be
|
|
223
|
+
// deterministic (and the gate's expected list readable), and ICU collation
|
|
224
|
+
// sorts `::` before `0.0.0.0` — arbitrary for a machine-facing list.
|
|
225
|
+
.sort((left, right) => left.port - right.port || (left.addr < right.addr ? -1 : left.addr > right.addr ? 1 : 0))
|
|
226
|
+
if (ports.length === 0 && sawCandidate) {
|
|
227
|
+
return {
|
|
228
|
+
tool,
|
|
229
|
+
ports: [],
|
|
230
|
+
error: `${tool} printed listening sockets but the output could not be parsed`,
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (ports.length > LISTEN_PORTS_MAX) {
|
|
234
|
+
return {
|
|
235
|
+
tool,
|
|
236
|
+
ports: ports.slice(0, LISTEN_PORTS_MAX),
|
|
237
|
+
error: `only the first ${LISTEN_PORTS_MAX} listening sockets are listed`,
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return { tool, ports }
|
|
241
|
+
}
|
package/src/pool.ts
CHANGED
|
@@ -686,6 +686,69 @@ export class RemotePool {
|
|
|
686
686
|
}
|
|
687
687
|
}
|
|
688
688
|
|
|
689
|
+
/**
|
|
690
|
+
* Open one direct-tcpip channel to a TCP target reachable FROM the remote
|
|
691
|
+
* host (`ssh -L` semantics). The caller owns the channel lifecycle.
|
|
692
|
+
*
|
|
693
|
+
* Deliberately NOT routed through `acquireSlot`: that table bounds the pool's
|
|
694
|
+
* own request channels (exec / SFTP) and its ceiling leaves room for the
|
|
695
|
+
* long-lived channels the pool does not count (PTY terminals, the subprocess
|
|
696
|
+
* runtime, the helper). A local forward is the same kind of long-lived
|
|
697
|
+
* channel, so the port panel keeps its own per-alias budget instead.
|
|
698
|
+
*
|
|
699
|
+
* A channel-open failure is NOT a connection failure: sshd answers
|
|
700
|
+
* "administratively prohibited" when forwarding is forbidden and "connect
|
|
701
|
+
* failed" when the remote port is closed — both on a perfectly healthy link,
|
|
702
|
+
* and painting the connection chip red for either would send the user to
|
|
703
|
+
* debug their network. Real transport failures still arrive through the
|
|
704
|
+
* pooled connection's own close/error events.
|
|
705
|
+
*/
|
|
706
|
+
async forwardOut(alias: string, dstHost: string, dstPort: number, srcPort = 0): Promise<ClientChannel> {
|
|
707
|
+
const conn = await this.acquire(alias)
|
|
708
|
+
this.hold(alias)
|
|
709
|
+
/**
|
|
710
|
+
* What the channel-open callback does after the deadline already answered.
|
|
711
|
+
*
|
|
712
|
+
* ssh2 has no channel-open timeout (see `openSession`'s note), so the
|
|
713
|
+
* deadline above can fire while the callback is still in flight. Without
|
|
714
|
+
* this flag a late success would hand back a channel nobody owns — a
|
|
715
|
+
* direct-tcpip that outlives every reference to it. The late channel is
|
|
716
|
+
* closed here instead, and no `close`→`release` handler is attached to it
|
|
717
|
+
* (the hold was already released by the timeout path).
|
|
718
|
+
*/
|
|
719
|
+
let settled = false
|
|
720
|
+
try {
|
|
721
|
+
const channel = await withDeadline(
|
|
722
|
+
new Promise<ClientChannel>((resolve, reject) => {
|
|
723
|
+
conn.forwardOut('127.0.0.1', srcPort, dstHost, dstPort, (error, stream) => {
|
|
724
|
+
if (settled) {
|
|
725
|
+
if (error === undefined || error === null) {
|
|
726
|
+
try {
|
|
727
|
+
stream.close()
|
|
728
|
+
} catch {
|
|
729
|
+
// Already gone.
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
return
|
|
733
|
+
}
|
|
734
|
+
settled = true
|
|
735
|
+
if (error !== undefined && error !== null) reject(error)
|
|
736
|
+
else resolve(stream)
|
|
737
|
+
})
|
|
738
|
+
}),
|
|
739
|
+
CONTROL_TIMEOUT_MS,
|
|
740
|
+
`forwarding channel to ${dstHost}:${dstPort} did not open within ${CONTROL_TIMEOUT_MS / 1000}s`,
|
|
741
|
+
)
|
|
742
|
+
channel.once('close', () => this.release(alias))
|
|
743
|
+
this.markOk(alias)
|
|
744
|
+
return channel
|
|
745
|
+
} catch (error) {
|
|
746
|
+
settled = true
|
|
747
|
+
this.release(alias)
|
|
748
|
+
throw error
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
689
752
|
/** Run one callback with a fresh SFTP session (closed afterwards). */
|
|
690
753
|
async withSftp<T>(alias: string, fn: (sftp: SFTPWrapper) => Promise<T>, opts: SftpOptions = {}): Promise<T> {
|
|
691
754
|
// An SFTP session IS a channel, so it takes a slot too: the burst that put
|
package/src/protocol.ts
CHANGED
|
@@ -34,6 +34,10 @@ export const REMOTE_API = {
|
|
|
34
34
|
sessionCwd: '/api/dsh-remote/session-cwd',
|
|
35
35
|
/** What one live session changed on its remote host (the review panel). */
|
|
36
36
|
changes: '/api/dsh-remote/changes',
|
|
37
|
+
/** Local TCP forwards (`ssh -L` semantics) for the port panel. */
|
|
38
|
+
forwards: '/api/dsh-remote/forwards',
|
|
39
|
+
/** Remote listening TCP sockets for the port panel (one bounded probe). */
|
|
40
|
+
listenPorts: '/api/dsh-remote/listen-ports',
|
|
37
41
|
} as const
|
|
38
42
|
|
|
39
43
|
/**
|
|
@@ -556,3 +560,75 @@ export interface GitShow {
|
|
|
556
560
|
body: string
|
|
557
561
|
stat: string
|
|
558
562
|
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* One request to forward a local TCP port to a target reachable from the
|
|
566
|
+
* remote host — the port panel's manual rule and its one-click "forward this
|
|
567
|
+
* discovered port" button both send exactly this shape.
|
|
568
|
+
*
|
|
569
|
+
* The local listener is ALWAYS bound to 127.0.0.1 (never 0.0.0.0): a forward is
|
|
570
|
+
* `ssh -L`, so anything the user's machine can reach through it is what ssh -L
|
|
571
|
+
* grants — exposing it on the LAN is not part of this feature.
|
|
572
|
+
*/
|
|
573
|
+
export interface RemoteForwardRequest {
|
|
574
|
+
/** Host alias the tunnel runs through. */
|
|
575
|
+
alias: string
|
|
576
|
+
/** Target address AS THE REMOTE HOST RESOLVES IT (`127.0.0.1` by default). */
|
|
577
|
+
remoteHost: string
|
|
578
|
+
/** Target port on that address. */
|
|
579
|
+
remotePort: number
|
|
580
|
+
/**
|
|
581
|
+
* Requested local port, or 0/omitted to let the OS assign one.
|
|
582
|
+
*
|
|
583
|
+
* The panel asks for 0 by default: picking a fixed port invites EADDRINUSE
|
|
584
|
+
* from whatever else the developer runs locally.
|
|
585
|
+
*/
|
|
586
|
+
localPort?: number
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/** One live local forward, as the port panel renders it. */
|
|
590
|
+
export interface RemoteForwardState {
|
|
591
|
+
/** Stable rule id (`alias|remoteHost|remotePort|localPort-as-requested`). */
|
|
592
|
+
id: string
|
|
593
|
+
alias: string
|
|
594
|
+
remoteHost: string
|
|
595
|
+
remotePort: number
|
|
596
|
+
/** The port actually bound (resolved when the request asked for 0). */
|
|
597
|
+
localPort: number
|
|
598
|
+
/** URL to copy / open; loopback HTTP is the overwhelmingly common case. */
|
|
599
|
+
localUrl: string
|
|
600
|
+
/** `error` means the last connection attempt failed; the listener is alive. */
|
|
601
|
+
state: 'listening' | 'error'
|
|
602
|
+
/** Currently open TCP connections through this rule. */
|
|
603
|
+
connections: number
|
|
604
|
+
/** Cumulative bytes in each direction (diagnostic, not a quota). */
|
|
605
|
+
bytesIn: number
|
|
606
|
+
bytesOut: number
|
|
607
|
+
/** Last connect/bind failure, human-readable. */
|
|
608
|
+
lastError?: string
|
|
609
|
+
startedAt: number
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** One listening TCP socket on the remote host. */
|
|
613
|
+
export interface RemoteListenPort {
|
|
614
|
+
/** Bind address exactly as the remote tool printed it (`0.0.0.0`, `::`, `*`, `127.0.0.1`). */
|
|
615
|
+
addr: string
|
|
616
|
+
port: number
|
|
617
|
+
/** Process name when the remote tool revealed it (usually only own processes). */
|
|
618
|
+
process?: string
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* The remote listening-port probe's answer.
|
|
623
|
+
*
|
|
624
|
+
* `tool` says what actually ran: `none` means the host has neither `ss` nor
|
|
625
|
+
* `netstat` (an honest "cannot enumerate", not "no ports"), and `unknown`
|
|
626
|
+
* means the probe did not answer at all. The panel must render those as an
|
|
627
|
+
* explanation, never as an empty list.
|
|
628
|
+
*/
|
|
629
|
+
export interface RemoteListenPortsResult {
|
|
630
|
+
tool: 'ss' | 'netstat' | 'none' | 'unknown'
|
|
631
|
+
ports: RemoteListenPort[]
|
|
632
|
+
/** Why the probe could not be used, when it could not. */
|
|
633
|
+
error?: string
|
|
634
|
+
}
|
package/src/routes.ts
CHANGED
|
@@ -22,6 +22,8 @@ import { bootstrap } from './keygen.ts'
|
|
|
22
22
|
import { helperAvailability, probe, pushPipeline } from './deploy.ts'
|
|
23
23
|
import { migrateDshSsh, parseSshConfig, readDefaultSshConfig, type ParsedImport } from './importers.ts'
|
|
24
24
|
import { TERMINAL_MAX_FRAME_BYTES, TerminalSessionRegistry } from './terminal.ts'
|
|
25
|
+
import { ForwardManager, validateForwardRequest } from './forward.ts'
|
|
26
|
+
import { LISTEN_PORTS_TIMEOUT_MS, listenPortsCommand, parseListenPorts } from './listen-ports.ts'
|
|
25
27
|
import type { SessionChanges } from './changes/recorder.ts'
|
|
26
28
|
import { DEFAULT_TIMEOUTS, clampExecTimeout } from './timeouts.ts'
|
|
27
29
|
|
|
@@ -184,6 +186,12 @@ export interface RemoteRoutesDeps {
|
|
|
184
186
|
timeouts?: () => RemoteTimeouts
|
|
185
187
|
/** Session change ledger, when the host half mounted one. */
|
|
186
188
|
changes?: SessionChanges
|
|
189
|
+
/**
|
|
190
|
+
* Live local port forwards. Absent only in route-only probes (the gates build
|
|
191
|
+
* `makeRoutes` with the minimum they need): the port routes then answer 503
|
|
192
|
+
* instead of pretending the feature exists.
|
|
193
|
+
*/
|
|
194
|
+
forwards?: ForwardManager
|
|
187
195
|
}
|
|
188
196
|
|
|
189
197
|
/** Package name our loader row is mounted from (ns discovery key). */
|
|
@@ -247,6 +255,7 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
|
|
|
247
255
|
const timeouts = (): RemoteTimeouts => deps.timeouts?.() ?? DEFAULT_TIMEOUTS
|
|
248
256
|
const files = new RemoteFiles(pool)
|
|
249
257
|
const terminalSessions = new TerminalSessionRegistry(pool)
|
|
258
|
+
const forwards = deps.forwards
|
|
250
259
|
|
|
251
260
|
/**
|
|
252
261
|
* Stream one remote `tar -czf -` command into a `.tar.gz` download response.
|
|
@@ -395,6 +404,10 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
|
|
|
395
404
|
return
|
|
396
405
|
}
|
|
397
406
|
if (method === 'DELETE') {
|
|
407
|
+
// A deleted host has no panel row left to stop its forwards from, so
|
|
408
|
+
// their listeners would keep the local ports bound until the Host
|
|
409
|
+
// restarts. Close them BEFORE the connection they ride on goes away.
|
|
410
|
+
forwards?.stopAlias(alias)
|
|
398
411
|
pool.forget(alias)
|
|
399
412
|
void worlds.dropHost(alias).catch(() => undefined)
|
|
400
413
|
if (!store.remove(alias)) {
|
|
@@ -1311,6 +1324,118 @@ export function makeRoutes(deps: RemoteRoutesDeps): { routes: WebRoute[]; upgrad
|
|
|
1311
1324
|
writeJson(res, 200, { ok: terminalSessions.close(body.id) })
|
|
1312
1325
|
},
|
|
1313
1326
|
},
|
|
1327
|
+
// ---------------------------------------------- port forwards
|
|
1328
|
+
// Local TCP forwards (`ssh -L`): the listener lives in the ForwardManager
|
|
1329
|
+
// (its own fiber-scoped lifecycle), so this route family is a thin CRUD
|
|
1330
|
+
// face plus the remote listening-port probe. Local ports are loopback-only;
|
|
1331
|
+
// see `src/forward.ts` for why.
|
|
1332
|
+
{
|
|
1333
|
+
kind: 'exact',
|
|
1334
|
+
path: REMOTE_API.forwards,
|
|
1335
|
+
handler: async (req, res) => {
|
|
1336
|
+
if (!isLoopbackRequest(req)) {
|
|
1337
|
+
writeJson(res, 403, { error: 'forbidden: loopback-only' })
|
|
1338
|
+
return
|
|
1339
|
+
}
|
|
1340
|
+
if (forwards === undefined) {
|
|
1341
|
+
writeJson(res, 503, { error: 'port forwarding is not available in this composition' })
|
|
1342
|
+
return
|
|
1343
|
+
}
|
|
1344
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
1345
|
+
if (req.method === 'GET') {
|
|
1346
|
+
const alias = queryParam(url, 'alias')
|
|
1347
|
+
writeJson(res, 200, { forwards: forwards.list(alias === undefined || alias === '' ? undefined : alias) })
|
|
1348
|
+
return
|
|
1349
|
+
}
|
|
1350
|
+
if (req.method === 'DELETE') {
|
|
1351
|
+
const id = queryParam(url, 'id')
|
|
1352
|
+
if (id === undefined || id === '') {
|
|
1353
|
+
writeJson(res, 400, { error: 'id query parameter is required' })
|
|
1354
|
+
return
|
|
1355
|
+
}
|
|
1356
|
+
writeJson(res, 200, { ok: forwards.stop(id) })
|
|
1357
|
+
return
|
|
1358
|
+
}
|
|
1359
|
+
if (req.method !== 'POST') {
|
|
1360
|
+
writeJson(res, 405, { error: `method not allowed: ${req.method}` })
|
|
1361
|
+
return
|
|
1362
|
+
}
|
|
1363
|
+
const read = await readBodyOrError<unknown>(req, res, { objectOnly: true })
|
|
1364
|
+
if (!read.ok) return
|
|
1365
|
+
const validated = validateForwardRequest(read.body)
|
|
1366
|
+
if (!validated.ok) {
|
|
1367
|
+
writeJson(res, 400, { error: validated.error })
|
|
1368
|
+
return
|
|
1369
|
+
}
|
|
1370
|
+
try {
|
|
1371
|
+
writeJson(res, 200, { forward: await forwards.start(validated.value) })
|
|
1372
|
+
} catch (error) {
|
|
1373
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
1374
|
+
// Caller-actionable refusals get 409: a taken local port, a privileged
|
|
1375
|
+
// port this process may not bind, and the per-alias rule ceiling
|
|
1376
|
+
// ("already has 16 local forwards; stop one first") — all three are
|
|
1377
|
+
// fixed by stopping/changing something locally. Everything else here
|
|
1378
|
+
// is the ssh side refusing or failing to connect: 502.
|
|
1379
|
+
const local = /EADDRINUSE|EACCES|already in use|already has \d+ local forwards|permission denied|not permitted/i.test(message)
|
|
1380
|
+
writeJson(res, local ? 409 : 502, { error: message })
|
|
1381
|
+
}
|
|
1382
|
+
},
|
|
1383
|
+
},
|
|
1384
|
+
// ------------------------------------------------ remote listen ports
|
|
1385
|
+
{
|
|
1386
|
+
kind: 'exact',
|
|
1387
|
+
path: REMOTE_API.listenPorts,
|
|
1388
|
+
handler: async (req, res) => {
|
|
1389
|
+
if (!isLoopbackRequest(req)) {
|
|
1390
|
+
writeJson(res, 403, { error: 'forbidden: loopback-only' })
|
|
1391
|
+
return
|
|
1392
|
+
}
|
|
1393
|
+
if (req.method !== 'GET') {
|
|
1394
|
+
writeJson(res, 405, { error: `method not allowed: ${req.method}` })
|
|
1395
|
+
return
|
|
1396
|
+
}
|
|
1397
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
1398
|
+
const alias = queryParam(url, 'alias')
|
|
1399
|
+
if (alias === undefined || alias === '') {
|
|
1400
|
+
writeJson(res, 400, { error: 'alias query parameter is required' })
|
|
1401
|
+
return
|
|
1402
|
+
}
|
|
1403
|
+
try {
|
|
1404
|
+
const result = await pool.exec(alias, listenPortsCommand(), { timeoutMs: LISTEN_PORTS_TIMEOUT_MS })
|
|
1405
|
+
// `exec` answers transport failures as a RESULT; only a real command
|
|
1406
|
+
// run can be parsed. A missing tool is the command's own answer
|
|
1407
|
+
// (`@@RVS-PORTS none`), not an error.
|
|
1408
|
+
if (result.error !== undefined) {
|
|
1409
|
+
writeJson(res, 502, { error: result.error })
|
|
1410
|
+
return
|
|
1411
|
+
}
|
|
1412
|
+
// A capped/dead run must not be parsed as a complete one: `timedOut`
|
|
1413
|
+
// means the exec deadline cut the command (a partial `ss` table would
|
|
1414
|
+
// read as "these are all the ports"), and a null exit code means the
|
|
1415
|
+
// channel closed without telling us how the command ended. Both are
|
|
1416
|
+
// "cannot enumerate", which the panel renders as an explanation.
|
|
1417
|
+
if (result.timedOut) {
|
|
1418
|
+
writeJson(res, 200, {
|
|
1419
|
+
tool: 'unknown',
|
|
1420
|
+
ports: [],
|
|
1421
|
+
error: `the remote probe did not finish within ${LISTEN_PORTS_TIMEOUT_MS / 1000}s`,
|
|
1422
|
+
})
|
|
1423
|
+
return
|
|
1424
|
+
}
|
|
1425
|
+
if (result.exitCode === null) {
|
|
1426
|
+
writeJson(res, 200, {
|
|
1427
|
+
tool: 'unknown',
|
|
1428
|
+
ports: [],
|
|
1429
|
+
error: 'the remote probe ended without an exit status (the SSH channel closed)',
|
|
1430
|
+
})
|
|
1431
|
+
return
|
|
1432
|
+
}
|
|
1433
|
+
writeJson(res, 200, parseListenPorts(result.stdout, result.exitCode))
|
|
1434
|
+
} catch (error) {
|
|
1435
|
+
writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) })
|
|
1436
|
+
}
|
|
1437
|
+
},
|
|
1438
|
+
},
|
|
1314
1439
|
]
|
|
1315
1440
|
|
|
1316
1441
|
// ---------------------------------------------- terminal (upgrade)
|