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.
- package/LICENSE +202 -0
- package/README.md +271 -2
- package/cordis.patch.yml +16 -0
- package/icon.svg +3 -0
- package/lib/client.js +13975 -0
- package/lib/index.js +6908 -0
- package/lib/types/activity/history.d.ts +50 -0
- package/lib/types/alerting/notify.d.ts +89 -0
- package/lib/types/alerting/prompt-summary.d.ts +28 -0
- package/lib/types/alerting/rules.d.ts +135 -0
- package/lib/types/alerting/tools.d.ts +30 -0
- package/lib/types/audit/audit-log.d.ts +84 -0
- package/lib/types/audit/recorder.d.ts +50 -0
- package/lib/types/client/api.d.ts +222 -0
- package/lib/types/client/index.d.ts +45 -0
- package/lib/types/client/locales.d.ts +319 -0
- package/lib/types/client/native-panel.d.ts +70 -0
- package/lib/types/client/panel/ClusterTab.d.ts +7 -0
- package/lib/types/client/panel/DeployTab.d.ts +10 -0
- package/lib/types/client/panel/FleetTab.d.ts +10 -0
- package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
- package/lib/types/client/panel/HostsTab.d.ts +25 -0
- package/lib/types/client/panel/LogsTab.d.ts +10 -0
- package/lib/types/client/panel/SshPanel.d.ts +14 -0
- package/lib/types/client/panel/TerminalTab.d.ts +27 -0
- package/lib/types/client/panel/TransferTab.d.ts +7 -0
- package/lib/types/client/panel/TunnelEditDialog.d.ts +15 -0
- package/lib/types/client/panel/TunnelsTab.d.ts +27 -0
- package/lib/types/client/panel/controller.d.ts +253 -0
- package/lib/types/client/panel/helpers.d.ts +45 -0
- package/lib/types/client/panel/tabs.d.ts +62 -0
- package/lib/types/client/panel/xterm.css.d.ts +2 -0
- package/lib/types/client/settings-binding.d.ts +71 -0
- package/lib/types/deploy/orchestrator.d.ts +158 -0
- package/lib/types/deploy/tools.d.ts +14 -0
- package/lib/types/dsh-home.d.ts +16 -0
- package/lib/types/engine/cluster.d.ts +19 -0
- package/lib/types/engine/connection-pool.d.ts +183 -0
- package/lib/types/engine/proxy-command.d.ts +36 -0
- package/lib/types/engine/pty.d.ts +32 -0
- package/lib/types/engine/sftp.d.ts +20 -0
- package/lib/types/engine/terminal-sessions.d.ts +67 -0
- package/lib/types/engine/tunnel-discovery.d.ts +89 -0
- package/lib/types/engine/tunnel-remarks.d.ts +49 -0
- package/lib/types/engine/tunnel.d.ts +76 -0
- package/lib/types/engine.d.ts +103 -0
- package/lib/types/http.d.ts +59 -0
- package/lib/types/index.d.ts +128 -0
- package/lib/types/inspect/checks.d.ts +118 -0
- package/lib/types/inspect/inspection.d.ts +111 -0
- package/lib/types/inspect/tools.d.ts +50 -0
- package/lib/types/logs/search.d.ts +131 -0
- package/lib/types/logs/tools.d.ts +6 -0
- package/lib/types/loopback.d.ts +64 -0
- package/lib/types/monitor/loop.d.ts +133 -0
- package/lib/types/monitor/metrics.d.ts +151 -0
- package/lib/types/mount-once.d.ts +55 -0
- package/lib/types/protocol.d.ts +524 -0
- package/lib/types/routes.d.ts +82 -0
- package/lib/types/security/known-hosts.d.ts +153 -0
- package/lib/types/security/master-secret.d.ts +157 -0
- package/lib/types/security/redact.d.ts +44 -0
- package/lib/types/security/secrets.d.ts +70 -0
- package/lib/types/ssh-config.d.ts +42 -0
- package/lib/types/store.d.ts +183 -0
- package/lib/types/tool-surface.d.ts +72 -0
- package/lib/types/tools.d.ts +56 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +126 -6
- package/src/activity/history.ts +117 -0
- package/src/alerting/notify.ts +212 -0
- package/src/alerting/prompt-summary.ts +71 -0
- package/src/alerting/rules.ts +281 -0
- package/src/alerting/tools.ts +263 -0
- package/src/audit/audit-log.ts +199 -0
- package/src/audit/recorder.ts +73 -0
- package/src/client/api.ts +782 -0
- package/src/client/css-modules.d.ts +5 -0
- package/src/client/index.ts +150 -0
- package/src/client/locales.ts +654 -0
- package/src/client/native-panel.tsx +141 -0
- package/src/client/panel/ClusterTab.tsx +141 -0
- package/src/client/panel/DeployTab.tsx +314 -0
- package/src/client/panel/FleetTab.tsx +494 -0
- package/src/client/panel/HostFormDialog.tsx +289 -0
- package/src/client/panel/HostsTab.tsx +395 -0
- package/src/client/panel/LogsTab.tsx +208 -0
- package/src/client/panel/SshPanel.tsx +105 -0
- package/src/client/panel/TerminalTab.tsx +550 -0
- package/src/client/panel/TransferTab.tsx +238 -0
- package/src/client/panel/TunnelEditDialog.tsx +174 -0
- package/src/client/panel/TunnelsTab.tsx +328 -0
- package/src/client/panel/controller.ts +507 -0
- package/src/client/panel/helpers.ts +84 -0
- package/src/client/panel/panel.module.css +1734 -0
- package/src/client/panel/tabs.ts +52 -0
- package/src/client/panel/xterm.css.ts +2 -0
- package/src/client/settings-binding.ts +184 -0
- package/src/deploy/orchestrator.ts +326 -0
- package/src/deploy/tools.ts +225 -0
- package/src/dsh-home.ts +42 -0
- package/src/engine/cluster.ts +60 -0
- package/src/engine/connection-pool.ts +721 -0
- package/src/engine/proxy-command.ts +248 -0
- package/src/engine/pty.ts +78 -0
- package/src/engine/sftp.ts +229 -0
- package/src/engine/terminal-sessions.ts +280 -0
- package/src/engine/tunnel-discovery.ts +353 -0
- package/src/engine/tunnel-remarks.ts +120 -0
- package/src/engine/tunnel.ts +300 -0
- package/src/engine.ts +195 -0
- package/src/http.ts +127 -0
- package/src/index.ts +690 -0
- package/src/inspect/checks.ts +251 -0
- package/src/inspect/inspection.ts +321 -0
- package/src/inspect/tools.ts +366 -0
- package/src/logs/search.ts +251 -0
- package/src/logs/tools.ts +160 -0
- package/src/loopback.ts +119 -0
- package/src/monitor/loop.ts +265 -0
- package/src/monitor/metrics.ts +333 -0
- package/src/mount-once.ts +142 -0
- package/src/protocol.ts +534 -0
- package/src/routes.ts +998 -0
- package/src/security/known-hosts.ts +342 -0
- package/src/security/master-secret.ts +334 -0
- package/src/security/redact.ts +119 -0
- package/src/security/secrets.ts +152 -0
- package/src/ssh-config.ts +182 -0
- package/src/store.ts +757 -0
- package/src/tool-surface.ts +96 -0
- package/src/tools.ts +550 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* User remarks for port forwards this plugin does not own.
|
|
3
|
+
*
|
|
4
|
+
* An external forward's identity (`ext-<pid>-<index>`) changes every time the
|
|
5
|
+
* process behind it restarts, so a remark cannot hang off the tunnel id — it
|
|
6
|
+
* would evaporate on the next restart and the row would silently revert to an
|
|
7
|
+
* anonymous port. Remarks are therefore keyed by the local listening port,
|
|
8
|
+
* which is the one part of a forward that survives a restart.
|
|
9
|
+
*
|
|
10
|
+
* Precedence when both exist: a user remark wins over `~/.ssh/forwards.conf`,
|
|
11
|
+
* because the remark is the more recent, more specific statement of intent.
|
|
12
|
+
* Clearing the remark (saving both fields empty) deletes the entry, and the
|
|
13
|
+
* forwards.conf name shows through again — the file stays the user's, and this
|
|
14
|
+
* plugin never rewrites it.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
18
|
+
import { dirname, join } from 'node:path'
|
|
19
|
+
import { dshHome } from '../dsh-home.ts'
|
|
20
|
+
|
|
21
|
+
/** A name/description pair the operator attached to one local port. */
|
|
22
|
+
export interface TunnelRemark {
|
|
23
|
+
name?: string
|
|
24
|
+
description?: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Where remarks live. Separate from the host store: no secret ever lands here. */
|
|
28
|
+
export function tunnelRemarksPath(): string {
|
|
29
|
+
return join(dshHome(), 'dsh-ssh-hub', 'tunnel-remarks.json')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Trim a value to a remark field, treating blank as absent. */
|
|
33
|
+
function clean(value: unknown): string | undefined {
|
|
34
|
+
if (typeof value !== 'string') return undefined
|
|
35
|
+
const trimmed = value.trim()
|
|
36
|
+
return trimmed === '' ? undefined : trimmed
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Read every stored remark, keyed by local port.
|
|
41
|
+
*
|
|
42
|
+
* A corrupt or hand-edited file yields an empty map rather than throwing: the
|
|
43
|
+
* tunnel list is the primary feature, and losing annotations must not take the
|
|
44
|
+
* whole tab down with an exception.
|
|
45
|
+
*
|
|
46
|
+
* @param path - override for tests.
|
|
47
|
+
* @returns remarks keyed by the local port as a string.
|
|
48
|
+
*/
|
|
49
|
+
export function readTunnelRemarks(path: string = tunnelRemarksPath()): Record<string, TunnelRemark> {
|
|
50
|
+
if (!existsSync(path)) return {}
|
|
51
|
+
let parsed: unknown
|
|
52
|
+
try {
|
|
53
|
+
parsed = JSON.parse(readFileSync(path, 'utf8'))
|
|
54
|
+
} catch {
|
|
55
|
+
return {}
|
|
56
|
+
}
|
|
57
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
|
|
58
|
+
const out: Record<string, TunnelRemark> = {}
|
|
59
|
+
for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
|
|
60
|
+
// Only ports are meaningful keys; anything else is junk from a bad edit.
|
|
61
|
+
if (!/^\d+$/.test(key)) continue
|
|
62
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) continue
|
|
63
|
+
const record = value as Record<string, unknown>
|
|
64
|
+
const remark: TunnelRemark = {}
|
|
65
|
+
const name = clean(record.name)
|
|
66
|
+
const description = clean(record.description)
|
|
67
|
+
if (name !== undefined) remark.name = name
|
|
68
|
+
if (description !== undefined) remark.description = description
|
|
69
|
+
if (remark.name !== undefined || remark.description !== undefined) out[key] = remark
|
|
70
|
+
}
|
|
71
|
+
return out
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Replace the whole remarks file (atomic via a 0600 temp file + rename). */
|
|
75
|
+
export function writeTunnelRemarks(remarks: Record<string, TunnelRemark>, path: string = tunnelRemarksPath()): void {
|
|
76
|
+
const dir = dirname(path)
|
|
77
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
78
|
+
const tmp = `${path}.tmp`
|
|
79
|
+
writeFileSync(tmp, `${JSON.stringify(remarks, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
80
|
+
renameSync(tmp, path)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Replace the remark for one port.
|
|
85
|
+
*
|
|
86
|
+
* The pair is replaced wholesale rather than merged: the edit dialog shows both
|
|
87
|
+
* fields at once, so "empty" is an instruction to clear that field, not to keep
|
|
88
|
+
* the old value. When both end up empty the entry is removed entirely, which is
|
|
89
|
+
* how `~/.ssh/forwards.conf` becomes visible again.
|
|
90
|
+
*
|
|
91
|
+
* @param localPort - the listening port that identifies the forward.
|
|
92
|
+
* @param remark - the desired pair; absent fields mean cleared.
|
|
93
|
+
* @param path - override for tests.
|
|
94
|
+
* @returns the stored remark, or undefined when the entry was deleted.
|
|
95
|
+
*/
|
|
96
|
+
export function setTunnelRemark(
|
|
97
|
+
localPort: number,
|
|
98
|
+
remark: TunnelRemark,
|
|
99
|
+
path: string = tunnelRemarksPath(),
|
|
100
|
+
): TunnelRemark | undefined {
|
|
101
|
+
if (!Number.isInteger(localPort) || localPort < 1 || localPort > 65535) {
|
|
102
|
+
throw new Error('localPort must be an integer in 1..65535')
|
|
103
|
+
}
|
|
104
|
+
const remarks = readTunnelRemarks(path)
|
|
105
|
+
const key = String(localPort)
|
|
106
|
+
const next: TunnelRemark = {}
|
|
107
|
+
const name = clean(remark.name)
|
|
108
|
+
const description = clean(remark.description)
|
|
109
|
+
if (name !== undefined) next.name = name
|
|
110
|
+
if (description !== undefined) next.description = description
|
|
111
|
+
if (next.name === undefined && next.description === undefined) {
|
|
112
|
+
if (remarks[key] === undefined) return undefined
|
|
113
|
+
delete remarks[key]
|
|
114
|
+
writeTunnelRemarks(remarks, path)
|
|
115
|
+
return undefined
|
|
116
|
+
}
|
|
117
|
+
remarks[key] = next
|
|
118
|
+
writeTunnelRemarks(remarks, path)
|
|
119
|
+
return next
|
|
120
|
+
}
|
|
@@ -0,0 +1,300 @@
|
|
|
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
|
+
import { readForwardsConf } from './tunnel-discovery.ts'
|
|
11
|
+
|
|
12
|
+
/** One active tunnel record (server + pinned connection + live sockets). */
|
|
13
|
+
export interface TunnelRecord {
|
|
14
|
+
info: TunnelInfo
|
|
15
|
+
server: NetServer
|
|
16
|
+
alias: string
|
|
17
|
+
/** The pooled connection this tunnel pins; siblings on one alias may share it. */
|
|
18
|
+
record: PoolRecord
|
|
19
|
+
sockets: Set<Socket>
|
|
20
|
+
/** Detach the link-death hook startTunnel installs on the pooled client. */
|
|
21
|
+
detachLink?: () => void
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The engine slice the tunnel module needs (adds the tunnel registry). */
|
|
25
|
+
export interface TunnelEngine extends PoolEngine {
|
|
26
|
+
readonly tunnels: Map<string, TunnelRecord>
|
|
27
|
+
nextTunnelId: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Destroy one socket or channel stream, tolerating an already-dead peer. */
|
|
31
|
+
function destroyQuietly(target: { destroy(): void }): void {
|
|
32
|
+
try { target.destroy() } catch { /* already closed */ }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Tear down one tunnel because the SSH link behind it is gone. Idempotent: the
|
|
37
|
+
* tunnel registry is the guard, so a socket callback or a link-death hook that
|
|
38
|
+
* arrives after a manual stop does nothing instead of tearing down twice, and
|
|
39
|
+
* no teardown error can escape into the net connection handler — an exception
|
|
40
|
+
* there terminates the whole host process.
|
|
41
|
+
*/
|
|
42
|
+
function abortTunnel(engine: TunnelEngine, id: string): void {
|
|
43
|
+
try { stopTunnel(engine, id) } catch { /* teardown already in progress */ }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Start a local port-forward tunnel (listens on 127.0.0.1 only). */
|
|
47
|
+
export async function startTunnel(
|
|
48
|
+
engine: TunnelEngine,
|
|
49
|
+
alias: string,
|
|
50
|
+
options: { remotePort: number; remoteHost?: string; localPort?: number; name?: string; description?: string },
|
|
51
|
+
): Promise<TunnelInfo> {
|
|
52
|
+
if (!Number.isInteger(options.remotePort) || options.remotePort < 1 || options.remotePort > 65535) {
|
|
53
|
+
throw new Error('remotePort must be an integer in 1..65535')
|
|
54
|
+
}
|
|
55
|
+
if (options.localPort !== undefined && (!Number.isInteger(options.localPort) || options.localPort < 1 || options.localPort > 65535)) {
|
|
56
|
+
throw new Error('localPort must be an integer in 1..65535')
|
|
57
|
+
}
|
|
58
|
+
const entry = engine.store.find(alias)
|
|
59
|
+
if (entry === undefined) throw new Error('alias \'' + alias + '\' not found — add it first')
|
|
60
|
+
const remoteHost = options.remoteHost ?? '127.0.0.1'
|
|
61
|
+
const id = 'tun-' + engine.nextTunnelId
|
|
62
|
+
engine.nextTunnelId += 1
|
|
63
|
+
const info: TunnelInfo = {
|
|
64
|
+
id,
|
|
65
|
+
alias,
|
|
66
|
+
localPort: 0,
|
|
67
|
+
remoteHost,
|
|
68
|
+
remotePort: options.remotePort,
|
|
69
|
+
state: 'connecting',
|
|
70
|
+
startedAt: Date.now(),
|
|
71
|
+
name: options.name,
|
|
72
|
+
description: options.description,
|
|
73
|
+
}
|
|
74
|
+
// Reuse the live pooled connection when one exists so sibling tunnels on
|
|
75
|
+
// one alias multiplex over it (and no orphaned connection leaks); recycle
|
|
76
|
+
// a broken one first.
|
|
77
|
+
const existing = engine.pool.get(alias)
|
|
78
|
+
if (existing !== undefined && existing.broken) disposeRecord(engine, alias, existing)
|
|
79
|
+
const record = engine.pool.get(alias) ?? (await acquire(engine, alias))
|
|
80
|
+
const client = record.client
|
|
81
|
+
const sockets = new Set<Socket>()
|
|
82
|
+
// A tunnel whose SSH link died can only refuse what it is handed, so every
|
|
83
|
+
// path that learns the link is gone tears the tunnel down as well instead
|
|
84
|
+
// of leaving a listener alive on a connection that forwards nothing.
|
|
85
|
+
const onLinkClosed = (): void => { abortTunnel(engine, id) }
|
|
86
|
+
const detachLink = (): void => { client.off('close', onLinkClosed) }
|
|
87
|
+
const server = createServer((socket) => {
|
|
88
|
+
sockets.add(socket)
|
|
89
|
+
socket.on('close', () => { sockets.delete(socket) })
|
|
90
|
+
// The link can die between taking the record above and this connection.
|
|
91
|
+
if (record.broken) {
|
|
92
|
+
destroyQuietly(socket)
|
|
93
|
+
abortTunnel(engine, id)
|
|
94
|
+
return
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
client.forwardOut('127.0.0.1', 0, remoteHost, options.remotePort, (error, stream) => {
|
|
98
|
+
if (error !== undefined) {
|
|
99
|
+
// A refused remote channel is the remote service's answer, not a
|
|
100
|
+
// dead SSH link: the tunnel itself stays up for the next attempt.
|
|
101
|
+
destroyQuietly(socket)
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
// Both ends of the pipe can die independently; destroy the pair so an
|
|
105
|
+
// unhandled 'error' event can never crash the host process.
|
|
106
|
+
const destroy = (): void => {
|
|
107
|
+
destroyQuietly(socket)
|
|
108
|
+
try { stream.close() } catch { /* gone */ }
|
|
109
|
+
}
|
|
110
|
+
stream.on('error', destroy)
|
|
111
|
+
socket.on('error', destroy)
|
|
112
|
+
stream.on('close', destroy)
|
|
113
|
+
socket.on('close', destroy)
|
|
114
|
+
stream.pipe(socket).pipe(stream)
|
|
115
|
+
})
|
|
116
|
+
} catch {
|
|
117
|
+
// ssh2 reports 'Not connected' by throwing out of forwardOut rather than
|
|
118
|
+
// through the callback; an exception escaping this connection handler
|
|
119
|
+
// is an uncaught exception that takes the host process down with it.
|
|
120
|
+
destroyQuietly(socket)
|
|
121
|
+
abortTunnel(engine, id)
|
|
122
|
+
}
|
|
123
|
+
})
|
|
124
|
+
try {
|
|
125
|
+
await new Promise<void>((resolve, reject) => {
|
|
126
|
+
server.once('error', reject)
|
|
127
|
+
server.listen(options.localPort ?? 0, '127.0.0.1', () => {
|
|
128
|
+
server.removeListener('error', reject)
|
|
129
|
+
resolve()
|
|
130
|
+
})
|
|
131
|
+
})
|
|
132
|
+
} catch (error) {
|
|
133
|
+
// Roll back: never leave an unpinned orphan connection behind.
|
|
134
|
+
if (!record.pinned && record.inFlight === 0) disposeRecord(engine, alias, record)
|
|
135
|
+
throw error
|
|
136
|
+
}
|
|
137
|
+
record.pinned = true
|
|
138
|
+
const address = server.address()
|
|
139
|
+
info.localPort = typeof address === 'object' && address !== null ? address.port : 0
|
|
140
|
+
info.state = 'forwarding'
|
|
141
|
+
engine.tunnels.set(id, { info, server, alias, record, sockets, detachLink })
|
|
142
|
+
// A dead link must not keep a listener alive: without this hook the tunnel
|
|
143
|
+
// outlives its connection and every later local connection hits the dead
|
|
144
|
+
// forwardOut path above.
|
|
145
|
+
client.once('close', onLinkClosed)
|
|
146
|
+
if (record.broken) {
|
|
147
|
+
// A link that died while the listener was binding already emitted 'close',
|
|
148
|
+
// so the pool's broken flag is the only signal left for that window. The
|
|
149
|
+
// tunnel retires right away, and the start reports that instead of
|
|
150
|
+
// handing the caller a forwarding tunnel that no longer exists.
|
|
151
|
+
info.state = 'failed'
|
|
152
|
+
info.error = 'ssh link closed while the tunnel was starting'
|
|
153
|
+
abortTunnel(engine, id)
|
|
154
|
+
}
|
|
155
|
+
return info
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** All active tunnels. */
|
|
159
|
+
export function listTunnels(engine: TunnelEngine): TunnelInfo[] {
|
|
160
|
+
const forwardsMap = readForwardsConf()
|
|
161
|
+
return [...engine.tunnels.values()].map(tunnel => {
|
|
162
|
+
const conf = forwardsMap.get(tunnel.info.localPort)
|
|
163
|
+
return {
|
|
164
|
+
...tunnel.info,
|
|
165
|
+
name: tunnel.info.name ?? conf?.name,
|
|
166
|
+
description: tunnel.info.description ?? conf?.description,
|
|
167
|
+
}
|
|
168
|
+
})
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Fields an editor may change on an existing tunnel. */
|
|
172
|
+
export interface TunnelUpdate {
|
|
173
|
+
/** New service name; an empty string (or null) clears it, letting forwards.conf show through. */
|
|
174
|
+
name?: string | null
|
|
175
|
+
/** New remark; an empty string (or null) clears it. */
|
|
176
|
+
description?: string | null
|
|
177
|
+
/** New remote target host. */
|
|
178
|
+
remoteHost?: string
|
|
179
|
+
/** New remote target port. */
|
|
180
|
+
remotePort?: number
|
|
181
|
+
/** New local listening port. */
|
|
182
|
+
localPort?: number
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** What an edit did, so a caller can tell a rename from a rebuild. */
|
|
186
|
+
export interface TunnelUpdateResult {
|
|
187
|
+
tunnel: TunnelInfo
|
|
188
|
+
/** True when the forward was torn down and rebuilt because its routing changed. */
|
|
189
|
+
restarted: boolean
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Normalise an optional text patch: undefined keeps, blank clears. */
|
|
193
|
+
function textPatch(value: string | null | undefined): string | undefined {
|
|
194
|
+
if (value === null || value === undefined) return undefined
|
|
195
|
+
const trimmed = value.trim()
|
|
196
|
+
return trimmed === '' ? undefined : trimmed
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Edit an existing tunnel.
|
|
201
|
+
*
|
|
202
|
+
* A name or remark change is applied to the live record in place — renaming a
|
|
203
|
+
* forward costs nothing and must not interrupt traffic. A routing change cannot
|
|
204
|
+
* be done in place: the listener is bound to the old target, so the forward is
|
|
205
|
+
* stopped and rebuilt from the new parameters, and the caller is told
|
|
206
|
+
* (`restarted: true`) rather than left to guess whether connections dropped.
|
|
207
|
+
*
|
|
208
|
+
* When the rebuild fails the previous forward is already closed. That is
|
|
209
|
+
* reported explicitly instead of surfacing a bare "connect failed", which would
|
|
210
|
+
* read as if the old tunnel were still serving.
|
|
211
|
+
*
|
|
212
|
+
* @param engine - the tunnel engine.
|
|
213
|
+
* @param id - tunnel id to edit.
|
|
214
|
+
* @param patch - fields to change; omitted fields keep their current value.
|
|
215
|
+
* @returns the resulting tunnel and whether it was rebuilt.
|
|
216
|
+
*/
|
|
217
|
+
export async function updateTunnel(
|
|
218
|
+
engine: TunnelEngine,
|
|
219
|
+
id: string,
|
|
220
|
+
patch: TunnelUpdate,
|
|
221
|
+
): Promise<TunnelUpdateResult> {
|
|
222
|
+
const existing = engine.tunnels.get(id)
|
|
223
|
+
if (existing === undefined) throw new Error(`tunnel '${id}' not found`)
|
|
224
|
+
|
|
225
|
+
const remoteHost = patch.remoteHost ?? existing.info.remoteHost
|
|
226
|
+
const remotePort = patch.remotePort ?? existing.info.remotePort
|
|
227
|
+
const localPort = patch.localPort ?? existing.info.localPort
|
|
228
|
+
if (!Number.isInteger(remotePort) || remotePort < 1 || remotePort > 65535) {
|
|
229
|
+
throw new Error('remotePort must be an integer in 1..65535')
|
|
230
|
+
}
|
|
231
|
+
if (!Number.isInteger(localPort) || localPort < 1 || localPort > 65535) {
|
|
232
|
+
throw new Error('localPort must be an integer in 1..65535')
|
|
233
|
+
}
|
|
234
|
+
if (remoteHost.trim() === '') throw new Error('remoteHost must not be empty')
|
|
235
|
+
|
|
236
|
+
const routingChanged = remoteHost !== existing.info.remoteHost
|
|
237
|
+
|| remotePort !== existing.info.remotePort
|
|
238
|
+
|| localPort !== existing.info.localPort
|
|
239
|
+
|
|
240
|
+
const name = patch.name === undefined ? existing.info.name : textPatch(patch.name)
|
|
241
|
+
const description = patch.description === undefined ? existing.info.description : textPatch(patch.description)
|
|
242
|
+
|
|
243
|
+
if (!routingChanged) {
|
|
244
|
+
const info: TunnelInfo = { ...existing.info }
|
|
245
|
+
// Rebuilt rather than mutated so the returned object never aliases the
|
|
246
|
+
// record's previous info (a caller holding the old snapshot keeps it).
|
|
247
|
+
if (name === undefined) delete info.name
|
|
248
|
+
else info.name = name
|
|
249
|
+
if (description === undefined) delete info.description
|
|
250
|
+
else info.description = description
|
|
251
|
+
existing.info = info
|
|
252
|
+
return { tunnel: info, restarted: false }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const alias = existing.alias
|
|
256
|
+
stopTunnel(engine, id)
|
|
257
|
+
try {
|
|
258
|
+
const tunnel = await startTunnel(engine, alias, { remotePort, remoteHost, localPort, name, description })
|
|
259
|
+
return { tunnel, restarted: true }
|
|
260
|
+
} catch (error) {
|
|
261
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
262
|
+
throw new Error(`tunnel could not be rebuilt: ${reason} (the previous forward was closed)`)
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Stop one tunnel (closes the listener, live sockets, and the pinned connection). */
|
|
267
|
+
export function stopTunnel(engine: TunnelEngine, id: string): boolean {
|
|
268
|
+
const tunnel = engine.tunnels.get(id)
|
|
269
|
+
if (tunnel === undefined) return false
|
|
270
|
+
engine.tunnels.delete(id)
|
|
271
|
+
// Drop the link-death hook first: a stop is never the link's death, and a
|
|
272
|
+
// long-lived pooled client outlives many tunnels.
|
|
273
|
+
try { tunnel.detachLink?.() } catch { /* already detached */ }
|
|
274
|
+
try { tunnel.server.close() } catch { /* already closed */ }
|
|
275
|
+
for (const socket of tunnel.sockets) {
|
|
276
|
+
destroyQuietly(socket)
|
|
277
|
+
}
|
|
278
|
+
tunnel.sockets.clear()
|
|
279
|
+
// Sibling tunnels on the same alias share the pinned connection: release it
|
|
280
|
+
// only once the last tunnel using it is gone. A record the pool has since
|
|
281
|
+
// replaced (e.g. after a broken-connection recycle) is ended directly.
|
|
282
|
+
const shared = [...engine.tunnels.values()].some(candidate => candidate.record === tunnel.record)
|
|
283
|
+
if (!shared) {
|
|
284
|
+
if (engine.pool.get(tunnel.alias) === tunnel.record) disposeRecord(engine, tunnel.alias, tunnel.record)
|
|
285
|
+
else endRecordChain(tunnel.record)
|
|
286
|
+
}
|
|
287
|
+
return true
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Stop all tunnels (optionally for one alias). */
|
|
291
|
+
export function stopAllTunnels(engine: TunnelEngine, alias?: string): number {
|
|
292
|
+
let count = 0
|
|
293
|
+
for (const [id, tunnel] of [...engine.tunnels]) {
|
|
294
|
+
if (alias === undefined || tunnel.alias === alias) {
|
|
295
|
+
stopTunnel(engine, id)
|
|
296
|
+
count += 1
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return count
|
|
300
|
+
}
|
package/src/engine.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
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
|
+
type ResolvedEngineOptions,
|
|
20
|
+
} from './engine/connection-pool.ts'
|
|
21
|
+
import { openShell, type ShellSession } from './engine/pty.ts'
|
|
22
|
+
import { download, ls, upload } from './engine/sftp.ts'
|
|
23
|
+
import { listTunnels, startTunnel, stopAllTunnels, stopTunnel, updateTunnel, type TunnelRecord, type TunnelUpdate, type TunnelUpdateResult } from './engine/tunnel.ts'
|
|
24
|
+
import { cluster } from './engine/cluster.ts'
|
|
25
|
+
|
|
26
|
+
export type { EngineOptions, KeyboardInteractiveHandler } from './engine/connection-pool.ts'
|
|
27
|
+
export type { ShellSession } from './engine/pty.ts'
|
|
28
|
+
export type { PoolRecord } from './engine/connection-pool.ts'
|
|
29
|
+
export type { TunnelRecord, TunnelUpdate, TunnelUpdateResult } from './engine/tunnel.ts'
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The engine. Owns the pool, tunnels, and all operations. One instance per
|
|
33
|
+
* plugin apply; dispose() closes every connection.
|
|
34
|
+
*/
|
|
35
|
+
export class SshEngine {
|
|
36
|
+
readonly store: HostStore
|
|
37
|
+
readonly opts: ResolvedEngineOptions
|
|
38
|
+
readonly pool = new Map<string, PoolRecord>()
|
|
39
|
+
readonly acquireQueue = new Map<string, Promise<PoolRecord>>()
|
|
40
|
+
readonly tunnels = new Map<string, TunnelRecord>()
|
|
41
|
+
nextTunnelId = 1
|
|
42
|
+
private sweepTimer: NodeJS.Timeout | undefined
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param store - the host config store.
|
|
46
|
+
* @param options - engine knobs (defaults applied).
|
|
47
|
+
*/
|
|
48
|
+
constructor(store: HostStore, options?: EngineOptions) {
|
|
49
|
+
this.store = store
|
|
50
|
+
this.opts = { ...DEFAULTS, ...options }
|
|
51
|
+
this.sweepTimer = setInterval(() => sweepPool(this), Math.max(10_000, this.opts.idleTimeoutMs / 4))
|
|
52
|
+
this.sweepTimer.unref?.()
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Change the pre-ready ceiling (TCP connect + key exchange + user
|
|
57
|
+
* authentication) for connections opened from now on. A pooled connection
|
|
58
|
+
* keeps serving until it reconnects, because the ceiling governs the
|
|
59
|
+
* connect path only.
|
|
60
|
+
*/
|
|
61
|
+
setConnectTimeout(timeoutMs: number): void {
|
|
62
|
+
this.opts.connectTimeoutMs = timeoutMs
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---------------------------------------------------------------- config
|
|
66
|
+
|
|
67
|
+
/** Secret-free host list (filtered by the optional query). */
|
|
68
|
+
list(query?: string): SshHostSummary[] {
|
|
69
|
+
const needle = query?.trim().toLowerCase()
|
|
70
|
+
return this.store.list()
|
|
71
|
+
.filter(entry => needle === undefined || needle === ''
|
|
72
|
+
|| entry.alias.toLowerCase().includes(needle)
|
|
73
|
+
|| (entry.description ?? '').toLowerCase().includes(needle)
|
|
74
|
+
|| entry.host.toLowerCase().includes(needle)
|
|
75
|
+
|| entry.tags.some(tag => tag.toLowerCase().includes(needle)))
|
|
76
|
+
.map(entry => this.store.summarize(entry))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** One host summary by alias. */
|
|
80
|
+
find(alias: string): SshHostSummary | undefined {
|
|
81
|
+
const entry = this.store.find(alias)
|
|
82
|
+
return entry === undefined ? undefined : this.store.summarize(entry)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ------------------------------------------------------------ exec
|
|
86
|
+
|
|
87
|
+
/** Run one command on `alias` (reusing the pooled connection). */
|
|
88
|
+
async exec(alias: string, command: string, timeoutMs?: number, signal?: AbortSignal): Promise<ExecResult> {
|
|
89
|
+
return execCommand(this, alias, command, timeoutMs, signal)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Run one command against many hosts concurrently. */
|
|
93
|
+
async cluster(options: {
|
|
94
|
+
command: string
|
|
95
|
+
aliases?: string[]
|
|
96
|
+
environment?: string
|
|
97
|
+
tags?: string[]
|
|
98
|
+
timeoutMs?: number
|
|
99
|
+
maxWorkers?: number
|
|
100
|
+
signal?: AbortSignal
|
|
101
|
+
}): Promise<ClusterResult[]> {
|
|
102
|
+
return cluster(this, options)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// -------------------------------------------------------------- shell
|
|
106
|
+
|
|
107
|
+
/** Open a PTY shell session for the web terminal (standalone connection). */
|
|
108
|
+
async openShell(
|
|
109
|
+
alias: string,
|
|
110
|
+
size: { cols: number; rows: number },
|
|
111
|
+
onKeyboardInteractive?: KeyboardInteractiveHandler,
|
|
112
|
+
): Promise<ShellSession> {
|
|
113
|
+
return openShell(this, alias, size, onKeyboardInteractive)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// -------------------------------------------------------------- sftp
|
|
117
|
+
|
|
118
|
+
/** Upload one local file (or directory tree) to a remote path. */
|
|
119
|
+
async upload(alias: string, localPath: string, remotePath: string, recursive: boolean, onProgress?: (progress: TransferProgress) => void): Promise<{ bytes: number; files: number }> {
|
|
120
|
+
return upload(this, alias, localPath, remotePath, recursive, onProgress)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Download one remote file to a local path. */
|
|
124
|
+
async download(alias: string, remotePath: string, localPath: string, onProgress?: (progress: TransferProgress) => void): Promise<{ bytes: number }> {
|
|
125
|
+
return download(this, alias, remotePath, localPath, onProgress)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** List a remote directory (file browser). */
|
|
129
|
+
async ls(alias: string, path: string): Promise<import('./protocol.ts').RemoteDirEntry[]> {
|
|
130
|
+
return ls(this, alias, path)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ------------------------------------------------------------- tunnel
|
|
134
|
+
|
|
135
|
+
/** Start a local port-forward tunnel (listens on 127.0.0.1 only). */
|
|
136
|
+
async startTunnel(alias: string, options: { remotePort: number; remoteHost?: string; localPort?: number; name?: string; description?: string }): Promise<TunnelInfo> {
|
|
137
|
+
return startTunnel(this, alias, options)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** All active tunnels. */
|
|
141
|
+
listTunnels(): TunnelInfo[] {
|
|
142
|
+
return listTunnels(this)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Edit one tunnel. A name/remark change is applied in place; a routing change
|
|
147
|
+
* rebuilds the forward and reports `restarted: true`.
|
|
148
|
+
*/
|
|
149
|
+
async updateTunnel(id: string, patch: TunnelUpdate): Promise<TunnelUpdateResult> {
|
|
150
|
+
return updateTunnel(this, id, patch)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Stop one tunnel (closes the listener, live sockets, and the pinned connection). */
|
|
154
|
+
stopTunnel(id: string): boolean {
|
|
155
|
+
return stopTunnel(this, id)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Stop all tunnels (optionally for one alias). */
|
|
159
|
+
stopAllTunnels(alias?: string): number {
|
|
160
|
+
return stopAllTunnels(this, alias)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Drop every live artifact bound to one alias: stop its tunnels and close
|
|
165
|
+
* the pooled connection. Host entries that are deleted or whose connection
|
|
166
|
+
* fields change must never keep serving a stale, previously authenticated
|
|
167
|
+
* connection — the next operation re-connects from the current config.
|
|
168
|
+
*/
|
|
169
|
+
dropAlias(alias: string): void {
|
|
170
|
+
stopAllTunnels(this, alias)
|
|
171
|
+
disposeRecord(this, alias)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ------------------------------------------------------------- misc
|
|
175
|
+
|
|
176
|
+
/** Probe connectivity with a cross-platform shell command. */
|
|
177
|
+
async test(alias: string): Promise<TestResult> {
|
|
178
|
+
const started = Date.now()
|
|
179
|
+
try {
|
|
180
|
+
const result = await this.exec(alias, 'echo ok', 10_000)
|
|
181
|
+
return result.success
|
|
182
|
+
? { ok: true, latencyMs: result.durationMs }
|
|
183
|
+
: { ok: false, latencyMs: result.durationMs, error: 'remote exit code ' + result.exitCode }
|
|
184
|
+
} catch (error) {
|
|
185
|
+
return { ok: false, latencyMs: Date.now() - started, error: error instanceof Error ? error.message : String(error) }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Close every pooled connection and tunnel. */
|
|
190
|
+
dispose(): void {
|
|
191
|
+
if (this.sweepTimer !== undefined) clearInterval(this.sweepTimer)
|
|
192
|
+
for (const id of [...this.tunnels.keys()]) stopTunnel(this, id)
|
|
193
|
+
for (const alias of [...this.pool.keys()]) disposeRecord(this, alias)
|
|
194
|
+
}
|
|
195
|
+
}
|