dsh-ssh-hub 0.0.0-stage → 0.2.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.
Files changed (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +271 -2
  3. package/cordis.patch.yml +16 -0
  4. package/icon.svg +3 -0
  5. package/lib/client.js +13975 -0
  6. package/lib/index.js +6908 -0
  7. package/lib/types/activity/history.d.ts +50 -0
  8. package/lib/types/alerting/notify.d.ts +89 -0
  9. package/lib/types/alerting/prompt-summary.d.ts +28 -0
  10. package/lib/types/alerting/rules.d.ts +135 -0
  11. package/lib/types/alerting/tools.d.ts +30 -0
  12. package/lib/types/audit/audit-log.d.ts +84 -0
  13. package/lib/types/audit/recorder.d.ts +50 -0
  14. package/lib/types/client/api.d.ts +222 -0
  15. package/lib/types/client/index.d.ts +45 -0
  16. package/lib/types/client/locales.d.ts +319 -0
  17. package/lib/types/client/native-panel.d.ts +70 -0
  18. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  19. package/lib/types/client/panel/DeployTab.d.ts +10 -0
  20. package/lib/types/client/panel/FleetTab.d.ts +10 -0
  21. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  22. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  23. package/lib/types/client/panel/LogsTab.d.ts +10 -0
  24. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  25. package/lib/types/client/panel/TerminalTab.d.ts +27 -0
  26. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  27. package/lib/types/client/panel/TunnelEditDialog.d.ts +15 -0
  28. package/lib/types/client/panel/TunnelsTab.d.ts +27 -0
  29. package/lib/types/client/panel/controller.d.ts +253 -0
  30. package/lib/types/client/panel/helpers.d.ts +45 -0
  31. package/lib/types/client/panel/tabs.d.ts +62 -0
  32. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  33. package/lib/types/client/settings-binding.d.ts +71 -0
  34. package/lib/types/deploy/orchestrator.d.ts +158 -0
  35. package/lib/types/deploy/tools.d.ts +14 -0
  36. package/lib/types/dsh-home.d.ts +16 -0
  37. package/lib/types/engine/cluster.d.ts +19 -0
  38. package/lib/types/engine/connection-pool.d.ts +183 -0
  39. package/lib/types/engine/proxy-command.d.ts +36 -0
  40. package/lib/types/engine/pty.d.ts +32 -0
  41. package/lib/types/engine/sftp.d.ts +20 -0
  42. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  43. package/lib/types/engine/tunnel-discovery.d.ts +89 -0
  44. package/lib/types/engine/tunnel-remarks.d.ts +49 -0
  45. package/lib/types/engine/tunnel.d.ts +76 -0
  46. package/lib/types/engine.d.ts +103 -0
  47. package/lib/types/http.d.ts +59 -0
  48. package/lib/types/index.d.ts +128 -0
  49. package/lib/types/inspect/checks.d.ts +118 -0
  50. package/lib/types/inspect/inspection.d.ts +111 -0
  51. package/lib/types/inspect/tools.d.ts +50 -0
  52. package/lib/types/logs/search.d.ts +131 -0
  53. package/lib/types/logs/tools.d.ts +6 -0
  54. package/lib/types/loopback.d.ts +64 -0
  55. package/lib/types/monitor/loop.d.ts +133 -0
  56. package/lib/types/monitor/metrics.d.ts +151 -0
  57. package/lib/types/mount-once.d.ts +55 -0
  58. package/lib/types/protocol.d.ts +524 -0
  59. package/lib/types/routes.d.ts +82 -0
  60. package/lib/types/security/known-hosts.d.ts +153 -0
  61. package/lib/types/security/master-secret.d.ts +157 -0
  62. package/lib/types/security/redact.d.ts +44 -0
  63. package/lib/types/security/secrets.d.ts +70 -0
  64. package/lib/types/ssh-config.d.ts +42 -0
  65. package/lib/types/store.d.ts +183 -0
  66. package/lib/types/tool-surface.d.ts +72 -0
  67. package/lib/types/tools.d.ts +56 -0
  68. package/locale/en.json +6 -0
  69. package/locale/zh.json +6 -0
  70. package/package.json +126 -6
  71. package/src/activity/history.ts +117 -0
  72. package/src/alerting/notify.ts +212 -0
  73. package/src/alerting/prompt-summary.ts +71 -0
  74. package/src/alerting/rules.ts +281 -0
  75. package/src/alerting/tools.ts +263 -0
  76. package/src/audit/audit-log.ts +199 -0
  77. package/src/audit/recorder.ts +73 -0
  78. package/src/client/api.ts +782 -0
  79. package/src/client/css-modules.d.ts +5 -0
  80. package/src/client/index.ts +150 -0
  81. package/src/client/locales.ts +654 -0
  82. package/src/client/native-panel.tsx +141 -0
  83. package/src/client/panel/ClusterTab.tsx +141 -0
  84. package/src/client/panel/DeployTab.tsx +314 -0
  85. package/src/client/panel/FleetTab.tsx +494 -0
  86. package/src/client/panel/HostFormDialog.tsx +289 -0
  87. package/src/client/panel/HostsTab.tsx +395 -0
  88. package/src/client/panel/LogsTab.tsx +208 -0
  89. package/src/client/panel/SshPanel.tsx +105 -0
  90. package/src/client/panel/TerminalTab.tsx +550 -0
  91. package/src/client/panel/TransferTab.tsx +238 -0
  92. package/src/client/panel/TunnelEditDialog.tsx +174 -0
  93. package/src/client/panel/TunnelsTab.tsx +328 -0
  94. package/src/client/panel/controller.ts +507 -0
  95. package/src/client/panel/helpers.ts +84 -0
  96. package/src/client/panel/panel.module.css +1734 -0
  97. package/src/client/panel/tabs.ts +52 -0
  98. package/src/client/panel/xterm.css.ts +2 -0
  99. package/src/client/settings-binding.ts +184 -0
  100. package/src/deploy/orchestrator.ts +326 -0
  101. package/src/deploy/tools.ts +225 -0
  102. package/src/dsh-home.ts +42 -0
  103. package/src/engine/cluster.ts +60 -0
  104. package/src/engine/connection-pool.ts +721 -0
  105. package/src/engine/proxy-command.ts +248 -0
  106. package/src/engine/pty.ts +78 -0
  107. package/src/engine/sftp.ts +229 -0
  108. package/src/engine/terminal-sessions.ts +280 -0
  109. package/src/engine/tunnel-discovery.ts +353 -0
  110. package/src/engine/tunnel-remarks.ts +120 -0
  111. package/src/engine/tunnel.ts +300 -0
  112. package/src/engine.ts +195 -0
  113. package/src/http.ts +127 -0
  114. package/src/index.ts +690 -0
  115. package/src/inspect/checks.ts +251 -0
  116. package/src/inspect/inspection.ts +321 -0
  117. package/src/inspect/tools.ts +366 -0
  118. package/src/logs/search.ts +251 -0
  119. package/src/logs/tools.ts +160 -0
  120. package/src/loopback.ts +119 -0
  121. package/src/monitor/loop.ts +265 -0
  122. package/src/monitor/metrics.ts +333 -0
  123. package/src/mount-once.ts +142 -0
  124. package/src/protocol.ts +534 -0
  125. package/src/routes.ts +998 -0
  126. package/src/security/known-hosts.ts +342 -0
  127. package/src/security/master-secret.ts +334 -0
  128. package/src/security/redact.ts +119 -0
  129. package/src/security/secrets.ts +152 -0
  130. package/src/ssh-config.ts +182 -0
  131. package/src/store.ts +757 -0
  132. package/src/tool-surface.ts +96 -0
  133. package/src/tools.ts +550 -0
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Host-side terminal sessions for the web terminal.
3
+ *
4
+ * The PTY shell is owned here, not by the browser view: a view can detach
5
+ * (panel switch, page unmount, a dropped socket) and reattach by session id
6
+ * without tearing the remote shell down, which is what makes the terminal
7
+ * survival property the old DOM takeover used to provide. A session with no
8
+ * attached socket is reaped after an idle window, and an exited one is kept
9
+ * for a short grace window so a reattaching view still sees the final screen.
10
+ */
11
+ import { randomBytes } from 'node:crypto'
12
+ import { WebSocket } from 'ws'
13
+ import type { KeyboardInteractiveHandler } from './connection-pool.ts'
14
+ import type { ShellSession } from './pty.ts'
15
+ import type { TerminalServerFrame } from '../protocol.ts'
16
+
17
+ /** Pause the shell when an attached socket's send buffer exceeds this… */
18
+ const BACKPRESSURE_HIGH_WATER = 1024 * 1024
19
+
20
+ /** …and resume once every attached socket drains below this. */
21
+ const BACKPRESSURE_LOW_WATER = 512 * 1024
22
+
23
+ /** Scrollback retained for a reattaching view (bytes of UTF-8 output). */
24
+ const DEFAULT_MAX_BUFFER_BYTES = 256 * 1024
25
+
26
+ /** A detached session is reaped after this long. */
27
+ const DEFAULT_IDLE_MS = 10 * 60 * 1000
28
+
29
+ /** An exited session is kept this long for a reattaching view. */
30
+ const DEFAULT_EXIT_GRACE_MS = 60 * 1000
31
+
32
+ /** One live terminal session and the sockets currently watching it. */
33
+ interface HostedTerminal {
34
+ id: string
35
+ alias: string
36
+ shell?: ShellSession
37
+ sockets: Set<WebSocket>
38
+ /** Bounded scrollback replayed to an attaching socket. */
39
+ buffer: string[]
40
+ bufferBytes: number
41
+ exited: boolean
42
+ exit?: { code: number | null; error?: string }
43
+ /** Pending keyboard-interactive challenge, whoever attached when it arrived. */
44
+ pendingAuthFinish?: (responses: string[]) => void
45
+ reapTimer?: ReturnType<typeof setTimeout>
46
+ }
47
+
48
+ /** What the registry needs from the engine (swappable in tests). */
49
+ export interface TerminalSessionDeps {
50
+ /** Open one PTY shell for the alias (engine.openShell). */
51
+ openShell(alias: string, size: { cols: number; rows: number }, onKeyboardInteractive?: KeyboardInteractiveHandler): Promise<ShellSession>
52
+ /** @returns the current time (defaults to Date.now). */
53
+ now?: () => number
54
+ /** Bounded scrollback per session. */
55
+ maxBufferBytes?: number
56
+ /** Idle window before a detached session is reaped. */
57
+ idleMs?: number
58
+ /** Grace window an exited session is kept for reattaching views. */
59
+ exitGraceMs?: number
60
+ }
61
+
62
+ /**
63
+ * The host's terminal session table: open one session per connect, attach any
64
+ * number of sockets, and keep the shell alive across detach.
65
+ */
66
+ export class TerminalSessionRegistry {
67
+ private readonly sessions = new Map<string, HostedTerminal>()
68
+ private readonly deps: TerminalSessionDeps
69
+ private readonly maxBufferBytes: number
70
+ private readonly idleMs: number
71
+ private readonly exitGraceMs: number
72
+
73
+ constructor(deps: TerminalSessionDeps) {
74
+ this.deps = deps
75
+ this.maxBufferBytes = deps.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES
76
+ this.idleMs = deps.idleMs ?? DEFAULT_IDLE_MS
77
+ this.exitGraceMs = deps.exitGraceMs ?? DEFAULT_EXIT_GRACE_MS
78
+ }
79
+
80
+ /** Open a new session for the alias and attach the requesting socket to it. */
81
+ async open(ws: WebSocket, alias: string, size: { cols: number; rows: number }): Promise<void> {
82
+ const session: HostedTerminal = {
83
+ id: randomBytes(9).toString('hex'),
84
+ alias,
85
+ sockets: new Set(),
86
+ buffer: [],
87
+ bufferBytes: 0,
88
+ exited: false,
89
+ }
90
+ this.sessions.set(session.id, session)
91
+ this.bind(ws, session)
92
+ try {
93
+ const shell = await this.deps.openShell(alias, size, this.keyboardInteractive(session))
94
+ if (!this.sessions.has(session.id)) {
95
+ // The session was ended (or the host torn down) while it connected.
96
+ shell.close()
97
+ return
98
+ }
99
+ session.shell = shell
100
+ shell.onData = data => { this.pushOutput(session, data.toString('utf8')) }
101
+ shell.onExit = (code, error) => { this.finish(session, code, error) }
102
+ this.send(session, { type: 'ready', alias, sessionId: session.id })
103
+ } catch (error) {
104
+ this.sessions.delete(session.id)
105
+ this.send(session, { type: 'exit', code: null, error: error instanceof Error ? error.message : String(error) })
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Attach a socket to an existing session, replaying its scrollback first.
111
+ * @returns false when the session is unknown (expired or already reaped).
112
+ */
113
+ attach(ws: WebSocket, sessionId: string, size: { cols: number; rows: number }): boolean {
114
+ const session = this.sessions.get(sessionId)
115
+ if (session === undefined) return false
116
+ this.bind(ws, session)
117
+ this.clearReap(session)
118
+ for (const chunk of session.buffer) this.sendTo(session, ws, { type: 'output', data: chunk })
119
+ this.sendTo(session, ws, { type: 'ready', alias: session.alias, sessionId: session.id })
120
+ if (session.exited) {
121
+ this.sendTo(session, ws, { type: 'exit', code: session.exit?.code ?? null, error: session.exit?.error })
122
+ // Re-arm the grace window: this socket now holds the exited session open.
123
+ this.scheduleReap(session, this.exitGraceMs)
124
+ } else {
125
+ session.shell?.resize(Math.max(2, size.cols), Math.max(1, size.rows))
126
+ session.shell?.resume()
127
+ }
128
+ return true
129
+ }
130
+
131
+ /** End every session (host teardown, plugin dispose). */
132
+ dispose(): void {
133
+ for (const session of [...this.sessions.values()]) this.end(session, false)
134
+ this.sessions.clear()
135
+ }
136
+
137
+ /** Number of live sessions (introspection for tests and diagnostics). */
138
+ size(): number {
139
+ return this.sessions.size
140
+ }
141
+
142
+ /** Wire one socket's frames and lifecycle onto a session. */
143
+ private bind(ws: WebSocket, session: HostedTerminal): void {
144
+ session.sockets.add(ws)
145
+ ws.on('message', (data) => {
146
+ let frame: { type?: string; data?: string; cols?: number; rows?: number; responses?: string[] }
147
+ try {
148
+ frame = JSON.parse(String(data)) as typeof frame
149
+ } catch {
150
+ return
151
+ }
152
+ if (frame.type === 'input') {
153
+ session.shell?.send(frame.data ?? '')
154
+ } else if (frame.type === 'resize') {
155
+ session.shell?.resize(Math.max(2, frame.cols ?? 80), Math.max(1, frame.rows ?? 24))
156
+ } else if (frame.type === 'auth_response') {
157
+ const finish = session.pendingAuthFinish
158
+ session.pendingAuthFinish = undefined
159
+ try { finish?.(frame.responses ?? []) } catch { /* the connect already failed */ }
160
+ } else if (frame.type === 'close') {
161
+ this.end(session, true)
162
+ } else if (frame.type === 'detach') {
163
+ this.detach(ws)
164
+ }
165
+ })
166
+ ws.on('close', () => { this.detach(ws) })
167
+ ws.on('error', () => { this.detach(ws) })
168
+ }
169
+
170
+ /** Remove a socket from its session, keeping the shell alive. */
171
+ private detach(ws: WebSocket): void {
172
+ for (const session of this.sessions.values()) {
173
+ if (!session.sockets.delete(ws)) continue
174
+ if (session.sockets.size === 0) {
175
+ // Nobody is watching: give the view a window to come back before the
176
+ // remote shell is torn down (or, for an exited one, before its final
177
+ // screen is dropped).
178
+ this.scheduleReap(session, session.exited ? this.exitGraceMs : this.idleMs)
179
+ }
180
+ return
181
+ }
182
+ }
183
+
184
+ /** End the session a socket is attached to (explicit close from the view). */
185
+ private end(session: HostedTerminal, notify: boolean): void {
186
+ this.clearReap(session)
187
+ if (this.sessions.delete(session.id) && notify) {
188
+ if (session.pendingAuthFinish !== undefined) {
189
+ const finish = session.pendingAuthFinish
190
+ session.pendingAuthFinish = undefined
191
+ try { finish([]) } catch { /* the connect already failed */ }
192
+ }
193
+ }
194
+ try { session.shell?.close() } catch { /* channel gone */ }
195
+ }
196
+
197
+ /** Mark a session exited and keep it briefly so a reattaching view sees it. */
198
+ private finish(session: HostedTerminal, code: number | null, error?: string): void {
199
+ if (session.exited) return
200
+ session.exited = true
201
+ session.exit = { code, error }
202
+ this.send(session, { type: 'exit', code, error })
203
+ // The view has its exit frame; close the sockets so neither the browser
204
+ // nor the host holds a dead transport open. The session record itself
205
+ // survives the grace window, so a reattach still replays the final screen.
206
+ for (const ws of [...session.sockets]) {
207
+ session.sockets.delete(ws)
208
+ try { ws.close(1000) } catch { /* already closed */ }
209
+ }
210
+ this.scheduleReap(session, this.exitGraceMs)
211
+ }
212
+
213
+ /** Append output to the replay buffer, trimmed to the byte cap. */
214
+ private pushOutput(session: HostedTerminal, data: string): void {
215
+ session.buffer.push(data)
216
+ session.bufferBytes += Buffer.byteLength(data)
217
+ while (session.bufferBytes > this.maxBufferBytes && session.buffer.length > 1) {
218
+ const dropped = session.buffer.shift()
219
+ session.bufferBytes -= Buffer.byteLength(dropped ?? '')
220
+ }
221
+ this.send(session, { type: 'output', data })
222
+ }
223
+
224
+ /** Broadcast one frame to every attached socket, honoring backpressure. */
225
+ private send(session: HostedTerminal, frame: TerminalServerFrame): void {
226
+ for (const ws of session.sockets) this.sendTo(session, ws, frame)
227
+ this.applyBackpressure(session)
228
+ }
229
+
230
+ private sendTo(session: HostedTerminal, ws: WebSocket, frame: TerminalServerFrame): void {
231
+ if (ws.readyState !== WebSocket.OPEN) return
232
+ try { ws.send(JSON.stringify(frame)) } catch { /* socket raced away */ }
233
+ }
234
+
235
+ /** Pause while any attached socket is backed up; resume once all drained. */
236
+ private applyBackpressure(session: HostedTerminal): void {
237
+ const shell = session.shell
238
+ if (shell === undefined) return
239
+ let high = false
240
+ let low = true
241
+ for (const ws of session.sockets) {
242
+ if (ws.bufferedAmount > BACKPRESSURE_HIGH_WATER) high = true
243
+ if (ws.bufferedAmount > BACKPRESSURE_LOW_WATER) low = false
244
+ }
245
+ if (high) shell.pause()
246
+ else if (low) shell.resume()
247
+ }
248
+
249
+ /** Answer a keyboard-interactive challenge through whoever is attached. */
250
+ private keyboardInteractive(session: HostedTerminal): KeyboardInteractiveHandler {
251
+ return (name, instructions, _lang, prompts, finish) => {
252
+ session.pendingAuthFinish = finish
253
+ this.send(session, {
254
+ type: 'auth_prompt',
255
+ name,
256
+ instructions,
257
+ prompts: prompts.map(p => ({ prompt: p.prompt, echo: p.echo })),
258
+ })
259
+ }
260
+ }
261
+
262
+ private scheduleReap(session: HostedTerminal, delayMs: number): void {
263
+ this.clearReap(session)
264
+ const timer = setTimeout(() => {
265
+ session.reapTimer = undefined
266
+ if (session.sockets.size > 0) return
267
+ this.end(session, false)
268
+ }, delayMs)
269
+ // Never hold the host process open for an idle terminal.
270
+ ;(timer as { unref?: () => void }).unref?.()
271
+ session.reapTimer = timer
272
+ }
273
+
274
+ private clearReap(session: HostedTerminal): void {
275
+ if (session.reapTimer !== undefined) {
276
+ clearTimeout(session.reapTimer)
277
+ session.reapTimer = undefined
278
+ }
279
+ }
280
+ }
@@ -0,0 +1,353 @@
1
+ /**
2
+ * Discovery of port forwards that already exist on this machine.
3
+ *
4
+ * The plugin can only list the tunnels it created itself, because they live in
5
+ * process memory. An operator's real fleet usually also has forwards started by
6
+ * hand (`ssh -N -L 8080:localhost:80 host`) or by another tool, and those were
7
+ * invisible in the tunnels tab even while they were serving traffic. This
8
+ * module reads the OS process table, parses the ssh forward options, and probes
9
+ * each local port so the panel can report what is actually listening.
10
+ *
11
+ * Everything here is best-effort: any failure (no process tool, a denied
12
+ * command, an unexpected line shape) yields "no external forwards" instead of
13
+ * an error, because a diagnostic aid must never break the tab it decorates.
14
+ */
15
+
16
+ import { execFile } from 'node:child_process'
17
+ import { existsSync, readFileSync } from 'node:fs'
18
+ import { connect } from 'node:net'
19
+ import { homedir } from 'node:os'
20
+ import { join } from 'node:path'
21
+ import type { TunnelInfo } from '../protocol.ts'
22
+
23
+ /** How long a process scan is reused. The tab polls every 5s; spawning a
24
+ * process enumeration that often is wasteful and briefly spikes CPU. */
25
+ const SCAN_TTL_MS = 6000
26
+
27
+ /** Hard ceiling for the process enumeration command. */
28
+ const SCAN_TIMEOUT_MS = 4000
29
+
30
+ /** How long a TCP probe may take before the port counts as not listening. */
31
+ const PROBE_TIMEOUT_MS = 250
32
+
33
+ /** One forward extracted from an ssh command line. */
34
+ export interface ParsedForward {
35
+ kind: 'local' | 'remote' | 'dynamic'
36
+ /** The port that listens on THIS machine (the local side of -L and -D). */
37
+ localPort: number
38
+ /** Bind address for the local listener, when given. */
39
+ bindHost?: string
40
+ remoteHost?: string
41
+ remotePort?: number
42
+ }
43
+
44
+ /** One ssh process and the forwards its command line declares. */
45
+ export interface ScannedProcess {
46
+ pid: number
47
+ /** Destination alias/host: the last bare argument (OpenSSH's destination). */
48
+ destination: string
49
+ forwards: ParsedForward[]
50
+ }
51
+
52
+ /** Cached scan so the 5s poll does not fork a process every tick. */
53
+ let scanCache: { at: number; value: ScannedProcess[] } | undefined
54
+
55
+ /**
56
+ * Split an ssh command line into arguments, tolerating both quoting styles a
57
+ * Windows process table can contain.
58
+ * @param commandLine - the raw command line.
59
+ * @returns the argument list (options keep their leading dash).
60
+ */
61
+ export function splitCommandLine(commandLine: string): string[] {
62
+ const args: string[] = []
63
+ let current = ''
64
+ let quote: '"' | "'" | undefined
65
+ let started = false
66
+ for (const char of commandLine) {
67
+ if (quote !== undefined) {
68
+ if (char === quote) quote = undefined
69
+ else current += char
70
+ continue
71
+ }
72
+ if (char === '"' || char === "'") {
73
+ quote = char
74
+ started = true
75
+ continue
76
+ }
77
+ if (char === ' ' || char === '\t') {
78
+ if (started || current !== '') {
79
+ args.push(current)
80
+ current = ''
81
+ started = false
82
+ }
83
+ continue
84
+ }
85
+ current += char
86
+ started = true
87
+ }
88
+ if (started || current !== '') args.push(current)
89
+ return args
90
+ }
91
+
92
+ /**
93
+ * Parse one `-L` / `-R` / `-D` specification.
94
+ *
95
+ * `-L` accepts `[bind_address:]port:host:hostport`; the bind part may itself be
96
+ * an IPv6 literal in brackets. `-D` accepts `[bind_address:]port`. `-R` mirrors
97
+ * `-L` but listens on the remote side, so it never owns a local port.
98
+ * @param kind - which option produced the spec.
99
+ * @param spec - the raw value after the option.
100
+ * @returns the parsed forward, or undefined when the spec is not understood.
101
+ */
102
+ export function parseForwardSpec(kind: 'local' | 'remote' | 'dynamic', spec: string): ParsedForward | undefined {
103
+ const text = spec.trim()
104
+ if (text === '') return undefined
105
+ // A bracketed IPv6 bind address keeps its colons: pull it out first.
106
+ let bindHost: string | undefined
107
+ let rest = text
108
+ if (rest.startsWith('[')) {
109
+ const close = rest.indexOf(']')
110
+ if (close > 0) {
111
+ bindHost = rest.slice(1, close)
112
+ rest = rest.slice(close + 1).replace(/^:/, '')
113
+ }
114
+ }
115
+ const parts = rest.split(':')
116
+ const numeric = (value: string | undefined): number | undefined => {
117
+ if (value === undefined || !/^\d+$/.test(value)) return undefined
118
+ const parsed = Number.parseInt(value, 10)
119
+ return parsed >= 1 && parsed <= 65535 ? parsed : undefined
120
+ }
121
+ if (kind === 'dynamic') {
122
+ // [bind:]port
123
+ const localPort = numeric(parts[parts.length - 1])
124
+ if (localPort === undefined) return undefined
125
+ if (bindHost === undefined && parts.length === 2) bindHost = parts[0]
126
+ return { kind, localPort, ...(bindHost !== undefined && bindHost !== '' ? { bindHost } : {}) }
127
+ }
128
+ // [bind:]port:host:hostport — bind is optional, so 3 or 4 segments remain
129
+ // after the bracketed case has been peeled off.
130
+ if (parts.length < 3) return undefined
131
+ const [localPortRaw, hostRaw, remotePortRaw] = parts.length === 4
132
+ ? [parts[1], parts[2], parts[3]]
133
+ : [parts[0], parts[1], parts[2]]
134
+ if (parts.length === 4 && bindHost === undefined) bindHost = parts[0]
135
+ const localPort = numeric(localPortRaw)
136
+ const remotePort = numeric(remotePortRaw)
137
+ if (localPort === undefined || remotePort === undefined || hostRaw === '') return undefined
138
+ return {
139
+ kind,
140
+ localPort,
141
+ remoteHost: hostRaw,
142
+ remotePort,
143
+ ...(bindHost !== undefined && bindHost !== '' ? { bindHost } : {}),
144
+ }
145
+ }
146
+
147
+ /**
148
+ * Extract the forward options and the destination from an ssh argument list.
149
+ * @param args - argv of one ssh invocation (program name included).
150
+ * @returns destination and forwards.
151
+ */
152
+ export function parseSshArguments(args: string[]): { destination: string; forwards: ParsedForward[] } {
153
+ const forwards: ParsedForward[] = []
154
+ let destination = ''
155
+ const takesValue = new Set(['-o', '-i', '-p', '-l', '-F', '-e', '-b', '-c', '-m', '-w', '-E', '-J', '-S', '-W'])
156
+ for (let index = 0; index < args.length; index += 1) {
157
+ const arg = args[index] as string
158
+ const next = args[index + 1]
159
+ // The option may be glued to its value (`-L8080:host:80`) or separate.
160
+ const attached = (flag: string): string | undefined =>
161
+ arg.length > flag.length ? arg.slice(flag.length) : undefined
162
+ if (arg === '-L' || arg === '-R' || arg === '-D') {
163
+ if (next === undefined) continue
164
+ const kind = arg === '-L' ? 'local' : arg === '-R' ? 'remote' : 'dynamic'
165
+ const parsed = parseForwardSpec(kind, next)
166
+ if (parsed !== undefined) forwards.push(parsed)
167
+ index += 1
168
+ continue
169
+ }
170
+ if (arg.startsWith('-L') || arg.startsWith('-R') || arg.startsWith('-D')) {
171
+ const flag = arg.slice(0, 2)
172
+ const value = attached(flag)
173
+ if (value !== undefined && value !== '') {
174
+ const kind = flag === '-L' ? 'local' : flag === '-R' ? 'remote' : 'dynamic'
175
+ const parsed = parseForwardSpec(kind, value)
176
+ if (parsed !== undefined) forwards.push(parsed)
177
+ }
178
+ continue
179
+ }
180
+ if (takesValue.has(arg)) {
181
+ index += 1
182
+ continue
183
+ }
184
+ if (arg.startsWith('-')) continue
185
+ // OpenSSH: the destination is the last non-option argument.
186
+ destination = arg
187
+ }
188
+ return { destination, forwards }
189
+ }
190
+
191
+ /** Run a command and resolve its stdout, or '' when it fails. */
192
+ function run(command: string, args: string[], timeout = SCAN_TIMEOUT_MS): Promise<string> {
193
+ return new Promise(resolve => {
194
+ try {
195
+ execFile(command, args, { timeout, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (error, stdout) => {
196
+ resolve(error === null ? stdout : '')
197
+ })
198
+ } catch {
199
+ resolve('')
200
+ }
201
+ })
202
+ }
203
+
204
+ /** Enumerate ssh processes with a forward on this machine (cached). */
205
+ export async function scanSshProcesses(): Promise<ScannedProcess[]> {
206
+ const now = Date.now()
207
+ if (scanCache !== undefined && now - scanCache.at < SCAN_TTL_MS) return scanCache.value
208
+ let value: ScannedProcess[] = []
209
+ if (process.platform === 'win32') {
210
+ // CommandLine is only populated for processes the caller can see; a denied
211
+ // read yields '' and simply contributes no forwards.
212
+ const stdout = await run('powershell.exe', [
213
+ '-NoProfile',
214
+ '-NonInteractive',
215
+ '-Command',
216
+ "Get-CimInstance Win32_Process -Filter \"Name='ssh.exe'\" | ForEach-Object { [string]$_.ProcessId + ' ' + [string]$_.CommandLine }",
217
+ ])
218
+ for (const line of stdout.split(/\r?\n/)) {
219
+ const trimmed = line.trim()
220
+ const match = /^(\d+)\s+(.*)$/.exec(trimmed)
221
+ if (match === null) continue
222
+ const pid = Number.parseInt(match[1] as string, 10)
223
+ const args = splitCommandLine(match[2] as string)
224
+ const { destination, forwards } = parseSshArguments(args)
225
+ if (forwards.length > 0) value.push({ pid, destination, forwards })
226
+ }
227
+ } else {
228
+ const stdout = await run('ps', ['-eo', 'pid=,args='])
229
+ for (const line of stdout.split(/\r?\n/)) {
230
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line)
231
+ if (match === null) continue
232
+ const args = splitCommandLine(match[2] as string)
233
+ if (!/\bssh\b/.test(args[0] ?? '')) continue
234
+ const { destination, forwards } = parseSshArguments(args)
235
+ if (forwards.length > 0) value.push({ pid: Number.parseInt(match[1] as string, 10), destination, forwards })
236
+ }
237
+ }
238
+ scanCache = { at: now, value }
239
+ return value
240
+ }
241
+
242
+ /** Whether a TCP port accepts a connection right now on loopback. */
243
+ function probePort(port: number): Promise<boolean> {
244
+ return new Promise(resolve => {
245
+ const socket = connect({ host: '127.0.0.1', port })
246
+ const done = (result: boolean): void => {
247
+ socket.removeAllListeners()
248
+ socket.destroy()
249
+ resolve(result)
250
+ }
251
+ socket.setTimeout(PROBE_TIMEOUT_MS)
252
+ socket.once('connect', () => { done(true) })
253
+ socket.once('timeout', () => { done(false) })
254
+ socket.once('error', () => { done(false) })
255
+ })
256
+ }
257
+
258
+ /** Clear the process-scan cache (tests). */
259
+ export function resetTunnelScanCache(): void {
260
+ scanCache = undefined
261
+ }
262
+
263
+ /** One record from ~/.ssh/forwards.conf. */
264
+ export interface ForwardConfEntry {
265
+ name: string
266
+ localPort: number
267
+ remoteTarget: string
268
+ description: string
269
+ }
270
+
271
+ /**
272
+ * Parse ~/.ssh/forwards.conf for project names and descriptions.
273
+ * The user's forwards.conf is the authoritative registry of tunnels on the machine.
274
+ */
275
+ export function readForwardsConf(overridePath?: string): Map<number, ForwardConfEntry> {
276
+ const map = new Map<number, ForwardConfEntry>()
277
+ const home = process.env.USERPROFILE ?? homedir()
278
+ const confPath = overridePath ?? join(home, '.ssh', 'forwards.conf')
279
+ if (!existsSync(confPath)) return map
280
+ try {
281
+ const content = readFileSync(confPath, 'utf8')
282
+ for (const rawLine of content.split(/\r?\n/)) {
283
+ const line = rawLine.trim()
284
+ if (line === '' || line.startsWith('#')) continue
285
+ const parts = line.split(/\s+/)
286
+ if (parts.length >= 2) {
287
+ const name = parts[0]
288
+ const port = Number.parseInt(parts[1], 10)
289
+ if (Number.isInteger(port)) {
290
+ const remoteTarget = parts[2] ?? ''
291
+ const description = parts.slice(3).join(' ')
292
+ map.set(port, { name, localPort: port, remoteTarget, description })
293
+ }
294
+ }
295
+ }
296
+ } catch {
297
+ // best-effort
298
+ }
299
+ return map
300
+ }
301
+
302
+ /**
303
+ * Port forwards that exist on this machine but are not owned by this plugin.
304
+ *
305
+ * A forward whose local port is dead is still reported (`live: false`) — it was
306
+ * declared by a running process, and hiding it would make a half-broken tunnel
307
+ * look absent rather than broken.
308
+ * @param owned - local ports the plugin already reports, to avoid duplicates.
309
+ * @param customRemarks - optional stored user remarks keyed by port or tunnel id.
310
+ * @returns external forwards in process order.
311
+ */
312
+ export async function discoverExternalTunnels(
313
+ owned: TunnelInfo[],
314
+ customRemarks?: Record<string, { name?: string; description?: string }>,
315
+ ): Promise<TunnelInfo[]> {
316
+ let scanned: ScannedProcess[]
317
+ try {
318
+ scanned = await scanSshProcesses()
319
+ } catch {
320
+ return []
321
+ }
322
+ const ownedPorts = new Set(owned.map(tunnel => tunnel.localPort))
323
+ const found: TunnelInfo[] = []
324
+ const forwardsMap = readForwardsConf()
325
+
326
+ for (const process of scanned) {
327
+ for (const [index, forward] of process.forwards.entries()) {
328
+ if (forward.kind === 'remote') continue
329
+ if (ownedPorts.has(forward.localPort)) continue
330
+ const conf = forwardsMap.get(forward.localPort)
331
+ const remark = customRemarks?.[String(forward.localPort)]
332
+ found.push({
333
+ id: `ext-${String(process.pid)}-${String(index)}`,
334
+ alias: process.destination !== '' ? process.destination : `pid ${String(process.pid)}`,
335
+ localPort: forward.localPort,
336
+ remoteHost: forward.remoteHost ?? (forward.kind === 'dynamic' ? 'SOCKS' : ''),
337
+ remotePort: forward.remotePort ?? 0,
338
+ state: 'forwarding',
339
+ startedAt: 0,
340
+ source: 'external',
341
+ pid: process.pid,
342
+ kind: forward.kind,
343
+ name: remark?.name ?? conf?.name,
344
+ description: remark?.description ?? conf?.description,
345
+ customRemark: remark !== undefined,
346
+ })
347
+ }
348
+ }
349
+ await Promise.all(found.map(async tunnel => {
350
+ tunnel.live = await probePort(tunnel.localPort)
351
+ }))
352
+ return found
353
+ }