@fish-under-sea/dsh-ssh-fish 0.0.0-stage → 1.0.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 (82) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +23 -0
  3. package/README.en.md +29 -0
  4. package/README.i18n.yaml +6 -0
  5. package/README.md +28 -2
  6. package/README.zh.md +29 -0
  7. package/cordis.patch.yml +12 -0
  8. package/icon.svg +3 -0
  9. package/lib/client.js +16487 -0
  10. package/lib/client.js.map +1 -0
  11. package/lib/index.js +3511 -0
  12. package/lib/types/client/api.d.ts +141 -0
  13. package/lib/types/client/index.d.ts +37 -0
  14. package/lib/types/client/locales.d.ts +164 -0
  15. package/lib/types/client/native-panel.d.ts +70 -0
  16. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  17. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  18. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  19. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  20. package/lib/types/client/panel/TerminalTab.d.ts +22 -0
  21. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  22. package/lib/types/client/panel/TunnelsTab.d.ts +19 -0
  23. package/lib/types/client/panel/controller.d.ts +89 -0
  24. package/lib/types/client/panel/helpers.d.ts +45 -0
  25. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  26. package/lib/types/client/settings-binding.d.ts +61 -0
  27. package/lib/types/dsh-home.d.ts +16 -0
  28. package/lib/types/engine/cluster.d.ts +19 -0
  29. package/lib/types/engine/connection-pool.d.ts +112 -0
  30. package/lib/types/engine/proxy-command.d.ts +36 -0
  31. package/lib/types/engine/pty.d.ts +32 -0
  32. package/lib/types/engine/sftp.d.ts +20 -0
  33. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  34. package/lib/types/engine/tunnel.d.ts +36 -0
  35. package/lib/types/engine.d.ts +89 -0
  36. package/lib/types/http.d.ts +59 -0
  37. package/lib/types/index.d.ts +83 -0
  38. package/lib/types/loopback.d.ts +24 -0
  39. package/lib/types/mount-once.d.ts +55 -0
  40. package/lib/types/protocol.d.ts +239 -0
  41. package/lib/types/routes.d.ts +33 -0
  42. package/lib/types/ssh-config.d.ts +34 -0
  43. package/lib/types/store.d.ts +71 -0
  44. package/lib/types/tool-surface.d.ts +71 -0
  45. package/lib/types/tools.d.ts +42 -0
  46. package/package.json +109 -4
  47. package/src/client/api.ts +562 -0
  48. package/src/client/css-modules.d.ts +5 -0
  49. package/src/client/index.ts +137 -0
  50. package/src/client/locales.ts +338 -0
  51. package/src/client/native-panel.tsx +141 -0
  52. package/src/client/panel/ClusterTab.tsx +123 -0
  53. package/src/client/panel/HostFormDialog.tsx +258 -0
  54. package/src/client/panel/HostsTab.tsx +325 -0
  55. package/src/client/panel/SshPanel.tsx +90 -0
  56. package/src/client/panel/TerminalTab.tsx +330 -0
  57. package/src/client/panel/TransferTab.tsx +232 -0
  58. package/src/client/panel/TunnelsTab.tsx +244 -0
  59. package/src/client/panel/controller.ts +167 -0
  60. package/src/client/panel/helpers.ts +84 -0
  61. package/src/client/panel/panel.module.css +876 -0
  62. package/src/client/panel/xterm.css.ts +2 -0
  63. package/src/client/settings-binding.ts +165 -0
  64. package/src/dsh-home.ts +42 -0
  65. package/src/engine/cluster.ts +60 -0
  66. package/src/engine/connection-pool.ts +543 -0
  67. package/src/engine/proxy-command.ts +248 -0
  68. package/src/engine/pty.ts +78 -0
  69. package/src/engine/sftp.ts +226 -0
  70. package/src/engine/terminal-sessions.ts +280 -0
  71. package/src/engine/tunnel.ts +194 -0
  72. package/src/engine.ts +176 -0
  73. package/src/http.ts +127 -0
  74. package/src/index.ts +234 -0
  75. package/src/loopback.ts +63 -0
  76. package/src/mount-once.ts +142 -0
  77. package/src/protocol.ts +230 -0
  78. package/src/routes.ts +494 -0
  79. package/src/ssh-config.ts +153 -0
  80. package/src/store.ts +419 -0
  81. package/src/tool-surface.ts +95 -0
  82. package/src/tools.ts +404 -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,194 @@
1
+ /**
2
+ * Local port-forward tunnels: one loopback-only listener per tunnel, pinned
3
+ * to a pooled connection so an idle sweep never closes it, with per-tunnel
4
+ * socket tracking and stop (single / alias-scoped / all).
5
+ */
6
+
7
+ import { createServer, type Server as NetServer, type Socket } from 'node:net'
8
+ import type { TunnelInfo } from '../protocol.ts'
9
+ import { acquire, disposeRecord, endRecordChain, type PoolEngine, type PoolRecord } from './connection-pool.ts'
10
+
11
+ /** One active tunnel record (server + pinned connection + live sockets). */
12
+ export interface TunnelRecord {
13
+ info: TunnelInfo
14
+ server: NetServer
15
+ alias: string
16
+ /** The pooled connection this tunnel pins; siblings on one alias may share it. */
17
+ record: PoolRecord
18
+ sockets: Set<Socket>
19
+ /** Detach the link-death hook startTunnel installs on the pooled client. */
20
+ detachLink?: () => void
21
+ }
22
+
23
+ /** The engine slice the tunnel module needs (adds the tunnel registry). */
24
+ export interface TunnelEngine extends PoolEngine {
25
+ readonly tunnels: Map<string, TunnelRecord>
26
+ nextTunnelId: number
27
+ }
28
+
29
+ /** Destroy one socket or channel stream, tolerating an already-dead peer. */
30
+ function destroyQuietly(target: { destroy(): void }): void {
31
+ try { target.destroy() } catch { /* already closed */ }
32
+ }
33
+
34
+ /**
35
+ * Tear down one tunnel because the SSH link behind it is gone. Idempotent: the
36
+ * tunnel registry is the guard, so a socket callback or a link-death hook that
37
+ * arrives after a manual stop does nothing instead of tearing down twice, and
38
+ * no teardown error can escape into the net connection handler — an exception
39
+ * there terminates the whole host process.
40
+ */
41
+ function abortTunnel(engine: TunnelEngine, id: string): void {
42
+ try { stopTunnel(engine, id) } catch { /* teardown already in progress */ }
43
+ }
44
+
45
+ /** Start a local port-forward tunnel (listens on 127.0.0.1 only). */
46
+ export async function startTunnel(
47
+ engine: TunnelEngine,
48
+ alias: string,
49
+ options: { remotePort: number; remoteHost?: string; localPort?: number },
50
+ ): Promise<TunnelInfo> {
51
+ if (!Number.isInteger(options.remotePort) || options.remotePort < 1 || options.remotePort > 65535) {
52
+ throw new Error('remotePort must be an integer in 1..65535')
53
+ }
54
+ if (options.localPort !== undefined && (!Number.isInteger(options.localPort) || options.localPort < 1 || options.localPort > 65535)) {
55
+ throw new Error('localPort must be an integer in 1..65535')
56
+ }
57
+ const entry = engine.store.find(alias)
58
+ if (entry === undefined) throw new Error('alias \'' + alias + '\' not found — add it first')
59
+ const remoteHost = options.remoteHost ?? '127.0.0.1'
60
+ const id = 'tun-' + engine.nextTunnelId
61
+ engine.nextTunnelId += 1
62
+ const info: TunnelInfo = {
63
+ id,
64
+ alias,
65
+ localPort: 0,
66
+ remoteHost,
67
+ remotePort: options.remotePort,
68
+ state: 'connecting',
69
+ startedAt: Date.now(),
70
+ }
71
+ // Reuse the live pooled connection when one exists so sibling tunnels on
72
+ // one alias multiplex over it (and no orphaned connection leaks); recycle
73
+ // a broken one first.
74
+ const existing = engine.pool.get(alias)
75
+ if (existing !== undefined && existing.broken) disposeRecord(engine, alias, existing)
76
+ const record = engine.pool.get(alias) ?? (await acquire(engine, alias))
77
+ const client = record.client
78
+ const sockets = new Set<Socket>()
79
+ // A tunnel whose SSH link died can only refuse what it is handed, so every
80
+ // path that learns the link is gone tears the tunnel down as well instead
81
+ // of leaving a listener alive on a connection that forwards nothing.
82
+ const onLinkClosed = (): void => { abortTunnel(engine, id) }
83
+ const detachLink = (): void => { client.off('close', onLinkClosed) }
84
+ const server = createServer((socket) => {
85
+ sockets.add(socket)
86
+ socket.on('close', () => { sockets.delete(socket) })
87
+ // The link can die between taking the record above and this connection.
88
+ if (record.broken) {
89
+ destroyQuietly(socket)
90
+ abortTunnel(engine, id)
91
+ return
92
+ }
93
+ try {
94
+ client.forwardOut('127.0.0.1', 0, remoteHost, options.remotePort, (error, stream) => {
95
+ if (error !== undefined) {
96
+ // A refused remote channel is the remote service's answer, not a
97
+ // dead SSH link: the tunnel itself stays up for the next attempt.
98
+ destroyQuietly(socket)
99
+ return
100
+ }
101
+ // Both ends of the pipe can die independently; destroy the pair so an
102
+ // unhandled 'error' event can never crash the host process.
103
+ const destroy = (): void => {
104
+ destroyQuietly(socket)
105
+ try { stream.close() } catch { /* gone */ }
106
+ }
107
+ stream.on('error', destroy)
108
+ socket.on('error', destroy)
109
+ stream.on('close', destroy)
110
+ socket.on('close', destroy)
111
+ stream.pipe(socket).pipe(stream)
112
+ })
113
+ } catch {
114
+ // ssh2 reports 'Not connected' by throwing out of forwardOut rather than
115
+ // through the callback; an exception escaping this connection handler
116
+ // is an uncaught exception that takes the host process down with it.
117
+ destroyQuietly(socket)
118
+ abortTunnel(engine, id)
119
+ }
120
+ })
121
+ try {
122
+ await new Promise<void>((resolve, reject) => {
123
+ server.once('error', reject)
124
+ server.listen(options.localPort ?? 0, '127.0.0.1', () => {
125
+ server.removeListener('error', reject)
126
+ resolve()
127
+ })
128
+ })
129
+ } catch (error) {
130
+ // Roll back: never leave an unpinned orphan connection behind.
131
+ if (!record.pinned && record.inFlight === 0) disposeRecord(engine, alias, record)
132
+ throw error
133
+ }
134
+ record.pinned = true
135
+ const address = server.address()
136
+ info.localPort = typeof address === 'object' && address !== null ? address.port : 0
137
+ info.state = 'forwarding'
138
+ engine.tunnels.set(id, { info, server, alias, record, sockets, detachLink })
139
+ // A dead link must not keep a listener alive: without this hook the tunnel
140
+ // outlives its connection and every later local connection hits the dead
141
+ // forwardOut path above.
142
+ client.once('close', onLinkClosed)
143
+ if (record.broken) {
144
+ // A link that died while the listener was binding already emitted 'close',
145
+ // so the pool's broken flag is the only signal left for that window. The
146
+ // tunnel retires right away, and the start reports that instead of
147
+ // handing the caller a forwarding tunnel that no longer exists.
148
+ info.state = 'failed'
149
+ info.error = 'ssh link closed while the tunnel was starting'
150
+ abortTunnel(engine, id)
151
+ }
152
+ return info
153
+ }
154
+
155
+ /** All active tunnels. */
156
+ export function listTunnels(engine: TunnelEngine): TunnelInfo[] {
157
+ return [...engine.tunnels.values()].map(tunnel => ({ ...tunnel.info }))
158
+ }
159
+
160
+ /** Stop one tunnel (closes the listener, live sockets, and the pinned connection). */
161
+ export function stopTunnel(engine: TunnelEngine, id: string): boolean {
162
+ const tunnel = engine.tunnels.get(id)
163
+ if (tunnel === undefined) return false
164
+ engine.tunnels.delete(id)
165
+ // Drop the link-death hook first: a stop is never the link's death, and a
166
+ // long-lived pooled client outlives many tunnels.
167
+ try { tunnel.detachLink?.() } catch { /* already detached */ }
168
+ try { tunnel.server.close() } catch { /* already closed */ }
169
+ for (const socket of tunnel.sockets) {
170
+ destroyQuietly(socket)
171
+ }
172
+ tunnel.sockets.clear()
173
+ // Sibling tunnels on the same alias share the pinned connection: release it
174
+ // only once the last tunnel using it is gone. A record the pool has since
175
+ // replaced (e.g. after a broken-connection recycle) is ended directly.
176
+ const shared = [...engine.tunnels.values()].some(candidate => candidate.record === tunnel.record)
177
+ if (!shared) {
178
+ if (engine.pool.get(tunnel.alias) === tunnel.record) disposeRecord(engine, tunnel.alias, tunnel.record)
179
+ else endRecordChain(tunnel.record)
180
+ }
181
+ return true
182
+ }
183
+
184
+ /** Stop all tunnels (optionally for one alias). */
185
+ export function stopAllTunnels(engine: TunnelEngine, alias?: string): number {
186
+ let count = 0
187
+ for (const [id, tunnel] of [...engine.tunnels]) {
188
+ if (alias === undefined || tunnel.alias === alias) {
189
+ stopTunnel(engine, id)
190
+ count += 1
191
+ }
192
+ }
193
+ return count
194
+ }
package/src/engine.ts ADDED
@@ -0,0 +1,176 @@
1
+ /**
2
+ * The SSH engine facade: a per-alias persistent connection pool (ssh2) with
3
+ * multi-hop jump support, command execution, PTY shells, SFTP transfers,
4
+ * local port-forward tunnels and cluster execution. The heavy lifting lives
5
+ * in the engine/ modules (connection-pool, pty, sftp, tunnel, cluster); this
6
+ * class composes them behind one new SshEngine instance per plugin apply.
7
+ */
8
+
9
+ import type { ClusterResult, ExecResult, SshHostSummary, TestResult, TransferProgress, TunnelInfo } from './protocol.ts'
10
+ import type { HostStore } from './store.ts'
11
+ import {
12
+ DEFAULTS,
13
+ execCommand,
14
+ disposeRecord,
15
+ sweepPool,
16
+ type EngineOptions,
17
+ type KeyboardInteractiveHandler,
18
+ type PoolRecord,
19
+ } from './engine/connection-pool.ts'
20
+ import { openShell, type ShellSession } from './engine/pty.ts'
21
+ import { download, ls, upload } from './engine/sftp.ts'
22
+ import { listTunnels, startTunnel, stopAllTunnels, stopTunnel, type TunnelRecord } from './engine/tunnel.ts'
23
+ import { cluster } from './engine/cluster.ts'
24
+
25
+ export type { EngineOptions, KeyboardInteractiveHandler } from './engine/connection-pool.ts'
26
+ export type { ShellSession } from './engine/pty.ts'
27
+ export type { PoolRecord } from './engine/connection-pool.ts'
28
+ export type { TunnelRecord } from './engine/tunnel.ts'
29
+
30
+ /**
31
+ * The engine. Owns the pool, tunnels, and all operations. One instance per
32
+ * plugin apply; dispose() closes every connection.
33
+ */
34
+ export class SshEngine {
35
+ readonly store: HostStore
36
+ readonly opts: Required<EngineOptions>
37
+ readonly pool = new Map<string, PoolRecord>()
38
+ readonly acquireQueue = new Map<string, Promise<PoolRecord>>()
39
+ readonly tunnels = new Map<string, TunnelRecord>()
40
+ nextTunnelId = 1
41
+ private sweepTimer: NodeJS.Timeout | undefined
42
+
43
+ /**
44
+ * @param store - the host config store.
45
+ * @param options - engine knobs (defaults applied).
46
+ */
47
+ constructor(store: HostStore, options?: EngineOptions) {
48
+ this.store = store
49
+ this.opts = { ...DEFAULTS, ...options }
50
+ this.sweepTimer = setInterval(() => sweepPool(this), Math.max(10_000, this.opts.idleTimeoutMs / 4))
51
+ this.sweepTimer.unref?.()
52
+ }
53
+
54
+ // ---------------------------------------------------------------- config
55
+
56
+ /** Secret-free host list (filtered by the optional query). */
57
+ list(query?: string): SshHostSummary[] {
58
+ const needle = query?.trim().toLowerCase()
59
+ return this.store.list()
60
+ .filter(entry => needle === undefined || needle === ''
61
+ || entry.alias.toLowerCase().includes(needle)
62
+ || (entry.description ?? '').toLowerCase().includes(needle)
63
+ || entry.host.toLowerCase().includes(needle)
64
+ || entry.tags.some(tag => tag.toLowerCase().includes(needle)))
65
+ .map(entry => this.store.summarize(entry))
66
+ }
67
+
68
+ /** One host summary by alias. */
69
+ find(alias: string): SshHostSummary | undefined {
70
+ const entry = this.store.find(alias)
71
+ return entry === undefined ? undefined : this.store.summarize(entry)
72
+ }
73
+
74
+ // ------------------------------------------------------------ exec
75
+
76
+ /** Run one command on `alias` (reusing the pooled connection). */
77
+ async exec(alias: string, command: string, timeoutMs?: number, signal?: AbortSignal): Promise<ExecResult> {
78
+ return execCommand(this, alias, command, timeoutMs, signal)
79
+ }
80
+
81
+ /** Run one command against many hosts concurrently. */
82
+ async cluster(options: {
83
+ command: string
84
+ aliases?: string[]
85
+ environment?: string
86
+ tags?: string[]
87
+ timeoutMs?: number
88
+ maxWorkers?: number
89
+ signal?: AbortSignal
90
+ }): Promise<ClusterResult[]> {
91
+ return cluster(this, options)
92
+ }
93
+
94
+ // -------------------------------------------------------------- shell
95
+
96
+ /** Open a PTY shell session for the web terminal (standalone connection). */
97
+ async openShell(
98
+ alias: string,
99
+ size: { cols: number; rows: number },
100
+ onKeyboardInteractive?: KeyboardInteractiveHandler,
101
+ ): Promise<ShellSession> {
102
+ return openShell(this, alias, size, onKeyboardInteractive)
103
+ }
104
+
105
+ // -------------------------------------------------------------- sftp
106
+
107
+ /** Upload one local file (or directory tree) to a remote path. */
108
+ async upload(alias: string, localPath: string, remotePath: string, recursive: boolean, onProgress?: (progress: TransferProgress) => void): Promise<{ bytes: number; files: number }> {
109
+ return upload(this, alias, localPath, remotePath, recursive, onProgress)
110
+ }
111
+
112
+ /** Download one remote file to a local path. */
113
+ async download(alias: string, remotePath: string, localPath: string, onProgress?: (progress: TransferProgress) => void): Promise<{ bytes: number }> {
114
+ return download(this, alias, remotePath, localPath, onProgress)
115
+ }
116
+
117
+ /** List a remote directory (file browser). */
118
+ async ls(alias: string, path: string): Promise<import('./protocol.ts').RemoteDirEntry[]> {
119
+ return ls(this, alias, path)
120
+ }
121
+
122
+ // ------------------------------------------------------------- tunnel
123
+
124
+ /** Start a local port-forward tunnel (listens on 127.0.0.1 only). */
125
+ async startTunnel(alias: string, options: { remotePort: number; remoteHost?: string; localPort?: number }): Promise<TunnelInfo> {
126
+ return startTunnel(this, alias, options)
127
+ }
128
+
129
+ /** All active tunnels. */
130
+ listTunnels(): TunnelInfo[] {
131
+ return listTunnels(this)
132
+ }
133
+
134
+ /** Stop one tunnel (closes the listener, live sockets, and the pinned connection). */
135
+ stopTunnel(id: string): boolean {
136
+ return stopTunnel(this, id)
137
+ }
138
+
139
+ /** Stop all tunnels (optionally for one alias). */
140
+ stopAllTunnels(alias?: string): number {
141
+ return stopAllTunnels(this, alias)
142
+ }
143
+
144
+ /**
145
+ * Drop every live artifact bound to one alias: stop its tunnels and close
146
+ * the pooled connection. Host entries that are deleted or whose connection
147
+ * fields change must never keep serving a stale, previously authenticated
148
+ * connection — the next operation re-connects from the current config.
149
+ */
150
+ dropAlias(alias: string): void {
151
+ stopAllTunnels(this, alias)
152
+ disposeRecord(this, alias)
153
+ }
154
+
155
+ // ------------------------------------------------------------- misc
156
+
157
+ /** Probe connectivity with a cross-platform shell command. */
158
+ async test(alias: string): Promise<TestResult> {
159
+ const started = Date.now()
160
+ try {
161
+ const result = await this.exec(alias, 'echo ok', 10_000)
162
+ return result.success
163
+ ? { ok: true, latencyMs: result.durationMs }
164
+ : { ok: false, latencyMs: result.durationMs, error: 'remote exit code ' + result.exitCode }
165
+ } catch (error) {
166
+ return { ok: false, latencyMs: Date.now() - started, error: error instanceof Error ? error.message : String(error) }
167
+ }
168
+ }
169
+
170
+ /** Close every pooled connection and tunnel. */
171
+ dispose(): void {
172
+ if (this.sweepTimer !== undefined) clearInterval(this.sweepTimer)
173
+ for (const id of [...this.tunnels.keys()]) stopTunnel(this, id)
174
+ for (const alias of [...this.pool.keys()]) disposeRecord(this, alias)
175
+ }
176
+ }