dsh-remote-deck 0.0.0-stage → 1.46.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 +21 -0
- package/README.md +227 -2
- package/README.zh-CN.md +201 -0
- package/client.js +8645 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +19 -0
- package/index.js +701 -0
- package/lib/api.js +1452 -0
- package/lib/bash-result.js +93 -0
- package/lib/connection.js +1133 -0
- package/lib/delete.js +199 -0
- package/lib/drafts.js +299 -0
- package/lib/encoding.js +247 -0
- package/lib/file-edit.js +339 -0
- package/lib/file-ops.js +402 -0
- package/lib/forwards.js +186 -0
- package/lib/fs-actions.js +235 -0
- package/lib/guide.js +162 -0
- package/lib/metrics.js +523 -0
- package/lib/remote-shells.js +320 -0
- package/lib/remote-terminal.js +427 -0
- package/lib/routing.js +695 -0
- package/lib/ssh-config.js +118 -0
- package/lib/terminal.js +123 -0
- package/lib/tool-forward.js +185 -0
- package/lib/transfer.js +235 -0
- package/lib/upload-chunks.js +306 -0
- package/lib/util.js +154 -0
- package/locale/README.md +160 -0
- package/locale/en-ui.json +477 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +63 -4
- package/vendor/codemirror/LICENSE +21 -0
- package/vendor/codemirror/README.md +18 -0
- package/vendor/codemirror/addon/edit/closebrackets.min.js +8 -0
- package/vendor/codemirror/addon/edit/matchbrackets.min.js +8 -0
- package/vendor/codemirror/addon/search/search.min.js +8 -0
- package/vendor/codemirror/addon/search/searchcursor.min.js +8 -0
- package/vendor/codemirror/addon/selection/active-line.min.js +8 -0
- package/vendor/codemirror/lib/codemirror.css +344 -0
- package/vendor/codemirror/lib/codemirror.min.js +8 -0
- package/vendor/codemirror/mode/clike/clike.min.js +8 -0
- package/vendor/codemirror/mode/css/css.min.js +8 -0
- package/vendor/codemirror/mode/go/go.min.js +8 -0
- package/vendor/codemirror/mode/htmlmixed/htmlmixed.min.js +8 -0
- package/vendor/codemirror/mode/javascript/javascript.min.js +8 -0
- package/vendor/codemirror/mode/markdown/markdown.min.js +8 -0
- package/vendor/codemirror/mode/python/python.min.js +8 -0
- package/vendor/codemirror/mode/rust/rust.min.js +8 -0
- package/vendor/codemirror/mode/shell/shell.min.js +8 -0
- package/vendor/codemirror/mode/xml/xml.min.js +8 -0
- package/vendor/codemirror/mode/yaml/yaml.min.js +8 -0
- package/vendor/node_modules/asn1/Jenkinsfile +65 -0
- package/vendor/node_modules/asn1/LICENSE +19 -0
- package/vendor/node_modules/asn1/README.md +50 -0
- package/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
- package/vendor/node_modules/asn1/lib/ber/index.js +27 -0
- package/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
- package/vendor/node_modules/asn1/lib/ber/types.js +36 -0
- package/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
- package/vendor/node_modules/asn1/lib/index.js +20 -0
- package/vendor/node_modules/asn1/package.json +31 -0
- package/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
- package/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
- package/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
- package/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
- package/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
- package/vendor/node_modules/safer-buffer/LICENSE +21 -0
- package/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
- package/vendor/node_modules/safer-buffer/Readme.md +156 -0
- package/vendor/node_modules/safer-buffer/dangerous.js +58 -0
- package/vendor/node_modules/safer-buffer/package.json +34 -0
- package/vendor/node_modules/safer-buffer/safer.js +77 -0
- package/vendor/node_modules/safer-buffer/tests.js +406 -0
- package/vendor/node_modules/ssh2/LICENSE +19 -0
- package/vendor/node_modules/ssh2/README.md +1529 -0
- package/vendor/node_modules/ssh2/SFTP.md +413 -0
- package/vendor/node_modules/ssh2/lib/Channel.js +295 -0
- package/vendor/node_modules/ssh2/lib/agent.js +1123 -0
- package/vendor/node_modules/ssh2/lib/client.js +2176 -0
- package/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
- package/vendor/node_modules/ssh2/lib/index.js +44 -0
- package/vendor/node_modules/ssh2/lib/keygen.js +582 -0
- package/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
- package/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
- package/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
- package/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
- package/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
- package/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
- package/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
- package/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
- package/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
- package/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
- package/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
- package/vendor/node_modules/ssh2/lib/server.js +1380 -0
- package/vendor/node_modules/ssh2/lib/utils.js +336 -0
- package/vendor/node_modules/ssh2/package.json +49 -0
- package/vendor/node_modules/tweetnacl/AUTHORS.md +28 -0
- package/vendor/node_modules/tweetnacl/CHANGELOG.md +221 -0
- package/vendor/node_modules/tweetnacl/LICENSE +24 -0
- package/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
- package/vendor/node_modules/tweetnacl/README.md +459 -0
- package/vendor/node_modules/tweetnacl/nacl-fast.js +2388 -0
- package/vendor/node_modules/tweetnacl/nacl-fast.min.js +2 -0
- package/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
- package/vendor/node_modules/tweetnacl/nacl.js +1175 -0
- package/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
- package/vendor/node_modules/tweetnacl/package.json +58 -0
- package/vendor/xterm/LICENSE.addon-fit +19 -0
- package/vendor/xterm/LICENSE.xterm +21 -0
- package/vendor/xterm/README.md +9 -0
- package/vendor/xterm/addon-fit.js +2 -0
- package/vendor/xterm/xterm.css +218 -0
- package/vendor/xterm/xterm.js +2 -0
|
@@ -0,0 +1,1133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Connections, credentials and live SSH sessions.
|
|
3
|
+
*
|
|
4
|
+
* Each configured machine owns one persistent ssh2 client. Commands open an
|
|
5
|
+
* exec channel on that client, files use its SFTP channel, so a session costs
|
|
6
|
+
* one handshake instead of one per operation. The client keeps itself alive
|
|
7
|
+
* and, when it was connected on purpose, reconnects with backoff.
|
|
8
|
+
*/
|
|
9
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
10
|
+
import { StringDecoder } from 'node:string_decoder'
|
|
11
|
+
import { readFile } from 'node:fs/promises'
|
|
12
|
+
import { createRequire } from 'node:module'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
import {
|
|
15
|
+
HOST_COLORS,
|
|
16
|
+
errorText,
|
|
17
|
+
fsError,
|
|
18
|
+
nowIso,
|
|
19
|
+
readJsonFile,
|
|
20
|
+
writeJsonFile,
|
|
21
|
+
} from './util.js'
|
|
22
|
+
|
|
23
|
+
const CONNECTIONS_VERSION = 2
|
|
24
|
+
// Six lines, in order: kernel name, kernel release, arch, shell, home, and the
|
|
25
|
+
// distribution's own name — `uname` only ever says "Linux", which tells a reader
|
|
26
|
+
// nothing about what they are actually on.
|
|
27
|
+
const PROBE_SCRIPT = `printf '%s\n' "$(uname -s)" "$(uname -r)" "$(uname -m)" "$SHELL" "$HOME" "$( if [ -r /etc/os-release ]; then . /etc/os-release; printf '%s' "\${PRETTY_NAME:-\${NAME:-}}"; elif command -v sw_vers >/dev/null 2>&1; then printf '%s %s' "$(sw_vers -productName)" "$(sw_vers -productVersion)"; fi )"`
|
|
28
|
+
const RECONNECT_DELAYS_MS = [1000, 2000, 4000, 8000, 15000]
|
|
29
|
+
|
|
30
|
+
export class ConnectionStore {
|
|
31
|
+
constructor({ dataDir, legacyDir }) {
|
|
32
|
+
this.file = join(dataDir, 'connections.json')
|
|
33
|
+
this.legacyFile = join(legacyDir, 'connections.json')
|
|
34
|
+
this.records = []
|
|
35
|
+
this.load()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
load() {
|
|
39
|
+
const current = readJsonFile(this.file, null)
|
|
40
|
+
if (current !== null && Array.isArray(current.connections)) {
|
|
41
|
+
this.records = current.connections.filter((row) => row && row.id)
|
|
42
|
+
return
|
|
43
|
+
}
|
|
44
|
+
// First run after the rename: adopt dsh-remote-ssh connections once.
|
|
45
|
+
const legacy = readJsonFile(this.legacyFile, null)
|
|
46
|
+
if (legacy !== null && Array.isArray(legacy.connections) && legacy.connections.length > 0) {
|
|
47
|
+
this.records = legacy.connections.filter((row) => row && row.id).map((row, index) => this.#normalize(row, index))
|
|
48
|
+
this.save()
|
|
49
|
+
return
|
|
50
|
+
}
|
|
51
|
+
this.records = []
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
save() {
|
|
55
|
+
writeJsonFile(this.file, { version: CONNECTIONS_VERSION, connections: this.records })
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
list() {
|
|
59
|
+
return this.records
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
get(id) {
|
|
63
|
+
return this.records.find((row) => row.id === id)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
#nextColor() {
|
|
67
|
+
return HOST_COLORS[this.records.length % HOST_COLORS.length]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
#normalize(input, index) {
|
|
71
|
+
const existing = typeof input.id === 'string' ? this.get(input.id) : undefined
|
|
72
|
+
const color = typeof input.color === 'string' && HOST_COLORS.includes(input.color)
|
|
73
|
+
? input.color
|
|
74
|
+
: existing?.color ?? HOST_COLORS[(index ?? this.records.length) % HOST_COLORS.length]
|
|
75
|
+
return {
|
|
76
|
+
id: input.id,
|
|
77
|
+
name: String(input.name || '').trim() || String(input.host || '').trim() || 'remote',
|
|
78
|
+
host: String(input.host || '').trim(),
|
|
79
|
+
port: Number.isInteger(input.port) && input.port > 0 && input.port < 65536 ? input.port : 22,
|
|
80
|
+
username: String(input.username || '').trim() || 'root',
|
|
81
|
+
authType: input.authType === 'password' ? 'password' : 'key',
|
|
82
|
+
privateKeyPath: typeof input.privateKeyPath === 'string' ? input.privateKeyPath.trim() : '',
|
|
83
|
+
jump: typeof input.jump === 'string' ? input.jump.trim() : '',
|
|
84
|
+
color,
|
|
85
|
+
autoConnect: input.autoConnect === true,
|
|
86
|
+
notes: typeof input.notes === 'string' ? input.notes : '',
|
|
87
|
+
createdAt: existing?.createdAt ?? input.createdAt ?? nowIso(),
|
|
88
|
+
updatedAt: nowIso(),
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
upsert(input) {
|
|
93
|
+
const id = typeof input.id === 'string' && input.id.length > 0 ? input.id : randomUUID()
|
|
94
|
+
const existing = this.get(id)
|
|
95
|
+
const record = this.#normalize({ ...input, id, createdAt: existing?.createdAt }, this.records.length)
|
|
96
|
+
if (existing) this.records = this.records.map((row) => (row.id === id ? record : row))
|
|
97
|
+
else this.records.push(record)
|
|
98
|
+
this.save()
|
|
99
|
+
return record
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
remove(id) {
|
|
103
|
+
this.records = this.records.filter((row) => row.id !== id)
|
|
104
|
+
this.save()
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export class Secrets {
|
|
109
|
+
constructor({ dataDir, legacyDir, credentials }) {
|
|
110
|
+
this.credentials = credentials
|
|
111
|
+
this.file = join(dataDir, 'secrets.json')
|
|
112
|
+
this.legacyFile = join(legacyDir, 'secrets.json')
|
|
113
|
+
this.local = readJsonFile(this.file, null) ?? readJsonFile(this.legacyFile, {})
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
#ref(connectionId, kind) {
|
|
117
|
+
return `REMOTE_DECK_${connectionId.replace(/-/g, '_')}_${kind}`
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
#legacyRef(connectionId, kind) {
|
|
121
|
+
return `REMOTE_SSH_${connectionId.replace(/-/g, '_')}_${kind}`
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async #resolve(ref) {
|
|
125
|
+
if (this.credentials === undefined) return null
|
|
126
|
+
try {
|
|
127
|
+
const hit = await this.credentials.resolve(ref)
|
|
128
|
+
if (hit && typeof hit.value === 'string' && hit.value.length > 0) return hit.value
|
|
129
|
+
} catch {
|
|
130
|
+
/* credential store unavailable: fall back to the local file */
|
|
131
|
+
}
|
|
132
|
+
return null
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async get(connectionId, kind) {
|
|
136
|
+
const value = await this.#resolve(this.#ref(connectionId, kind))
|
|
137
|
+
if (value !== null) return value
|
|
138
|
+
const legacy = await this.#resolve(this.#legacyRef(connectionId, kind))
|
|
139
|
+
if (legacy !== null) {
|
|
140
|
+
// Move the secret forward so later releases only look at the new name.
|
|
141
|
+
await this.set(connectionId, kind, legacy)
|
|
142
|
+
return legacy
|
|
143
|
+
}
|
|
144
|
+
const local = this.local[`${connectionId}:${kind}`]
|
|
145
|
+
return typeof local === 'string' && local.length > 0 ? local : null
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async set(connectionId, kind, value) {
|
|
149
|
+
if (typeof value !== 'string' || value.length === 0) return this.clear(connectionId, kind)
|
|
150
|
+
if (this.credentials !== undefined) {
|
|
151
|
+
try {
|
|
152
|
+
await this.credentials.set(this.#ref(connectionId, kind), value)
|
|
153
|
+
return
|
|
154
|
+
} catch {
|
|
155
|
+
/* fall through to the local file */
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
this.local[`${connectionId}:${kind}`] = value
|
|
159
|
+
writeJsonFile(this.file, this.local)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async clear(connectionId, kind) {
|
|
163
|
+
if (this.credentials !== undefined) {
|
|
164
|
+
try {
|
|
165
|
+
await this.credentials.unset(this.#ref(connectionId, kind))
|
|
166
|
+
await this.credentials.unset(this.#legacyRef(connectionId, kind))
|
|
167
|
+
} catch {
|
|
168
|
+
/* ignore */
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
delete this.local[`${connectionId}:${kind}`]
|
|
172
|
+
writeJsonFile(this.file, this.local)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async describe(connectionId) {
|
|
176
|
+
const [password, passphrase] = await Promise.all([
|
|
177
|
+
this.get(connectionId, 'PASSWORD'),
|
|
178
|
+
this.get(connectionId, 'PASSPHRASE'),
|
|
179
|
+
])
|
|
180
|
+
return { password: password !== null, passphrase: passphrase !== null }
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ssh2 is vendored under vendor/node_modules so the plugin has no npm
|
|
185
|
+
// dependencies and plugin managers never run install scripts. Loading it with
|
|
186
|
+
// createRequire avoids the ESM/CJS interop differences between the DSH plugin
|
|
187
|
+
// loader instances (the UI host, session runner and asset server resolve
|
|
188
|
+
// dynamic imports differently).
|
|
189
|
+
const requireFromPlugin = createRequire(import.meta.url)
|
|
190
|
+
let ssh2ClientClass = null
|
|
191
|
+
|
|
192
|
+
function pickSsh2Client(value) {
|
|
193
|
+
for (const candidate of [value, value?.default, value?.default?.default]) {
|
|
194
|
+
if (candidate && typeof candidate.Client === 'function') return candidate.Client
|
|
195
|
+
}
|
|
196
|
+
return null
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function loadSsh2Client() {
|
|
200
|
+
if (ssh2ClientClass !== null) return ssh2ClientClass
|
|
201
|
+
let failure = null
|
|
202
|
+
try {
|
|
203
|
+
const required = requireFromPlugin('../vendor/node_modules/ssh2/lib/index.js')
|
|
204
|
+
const client = pickSsh2Client(required)
|
|
205
|
+
if (client !== null) {
|
|
206
|
+
ssh2ClientClass = client
|
|
207
|
+
return client
|
|
208
|
+
}
|
|
209
|
+
failure = new Error('require() returned a module without a Client constructor')
|
|
210
|
+
} catch (error) {
|
|
211
|
+
failure = error
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
const loaded = await import('../vendor/node_modules/ssh2/lib/index.js')
|
|
215
|
+
const client = pickSsh2Client(loaded)
|
|
216
|
+
if (client !== null) {
|
|
217
|
+
ssh2ClientClass = client
|
|
218
|
+
return client
|
|
219
|
+
}
|
|
220
|
+
failure = new Error('import() returned a module without a Client constructor')
|
|
221
|
+
} catch (error) {
|
|
222
|
+
failure = error
|
|
223
|
+
}
|
|
224
|
+
if (process.env.DSH_REMOTE_DECK_DEBUG === '1') {
|
|
225
|
+
console.error('[remote-deck] ssh2 load failed', process.pid, errorText(failure))
|
|
226
|
+
}
|
|
227
|
+
throw fsError('REMOTE_DECK_NO_SSH2', `the bundled ssh2 Client is unavailable (pid ${process.pid}): ${errorText(failure)}`)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Load the bundled ssh2 once and verify the Client constructor is usable.
|
|
232
|
+
* DSH loads the plugin in several runtime instances; this runs in each of them
|
|
233
|
+
* so a broken loader shape is visible in the diagnostics instead of surfacing
|
|
234
|
+
* later as "ssh2.Client is not a constructor" during a session run.
|
|
235
|
+
*/
|
|
236
|
+
export async function ssh2SelfTest() {
|
|
237
|
+
const started = Date.now()
|
|
238
|
+
try {
|
|
239
|
+
const Client = await loadSsh2Client()
|
|
240
|
+
const probe = new Client()
|
|
241
|
+
try {
|
|
242
|
+
probe.end()
|
|
243
|
+
} catch {
|
|
244
|
+
/* constructor-only probe */
|
|
245
|
+
}
|
|
246
|
+
return { ok: true, pid: process.pid, ms: Date.now() - started }
|
|
247
|
+
} catch (error) {
|
|
248
|
+
return { ok: false, pid: process.pid, ms: Date.now() - started, error: errorText(error) }
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* One ProxyJump hop: `[user@]host[:port]`, the syntax ssh itself accepts. A
|
|
254
|
+
* value may name a comma-separated chain, ordered from the client outwards.
|
|
255
|
+
*/
|
|
256
|
+
export function parseJumpSpec(value) {
|
|
257
|
+
const hops = []
|
|
258
|
+
for (const part of String(value ?? '').split(',')) {
|
|
259
|
+
const text = part.trim()
|
|
260
|
+
if (text.length === 0) continue
|
|
261
|
+
const match = /^(?:([^@]+)@)?(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(text)
|
|
262
|
+
if (match === null) continue
|
|
263
|
+
const host = match[2].replace(/^\[/, '').replace(/\]$/, '').trim()
|
|
264
|
+
if (host.length === 0) continue
|
|
265
|
+
const port = match[3] === undefined ? 22 : Number(match[3])
|
|
266
|
+
hops.push({
|
|
267
|
+
user: (match[1] ?? '').trim(),
|
|
268
|
+
host,
|
|
269
|
+
port: Number.isInteger(port) && port > 0 && port < 65536 ? port : 22,
|
|
270
|
+
})
|
|
271
|
+
}
|
|
272
|
+
return hops
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export class RemoteHost {
|
|
276
|
+
constructor(record, hooks) {
|
|
277
|
+
this.record = record
|
|
278
|
+
this.hooks = hooks ?? {}
|
|
279
|
+
this.client = null
|
|
280
|
+
this.sftp = null
|
|
281
|
+
this.state = 'disconnected'
|
|
282
|
+
this.error = ''
|
|
283
|
+
this.since = null
|
|
284
|
+
this.latencyMs = null
|
|
285
|
+
this.sys = null
|
|
286
|
+
this.connecting = null
|
|
287
|
+
this.wanted = false
|
|
288
|
+
this.disposed = false
|
|
289
|
+
this.reconnectAttempt = 0
|
|
290
|
+
this.reconnectTimer = null
|
|
291
|
+
this.pendingExec = new Set()
|
|
292
|
+
this.jumpClients = []
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
#failPendingExec(message) {
|
|
296
|
+
const pending = this.pendingExec
|
|
297
|
+
this.pendingExec = new Set()
|
|
298
|
+
for (const entry of pending) {
|
|
299
|
+
try {
|
|
300
|
+
entry.fail(message)
|
|
301
|
+
} catch {
|
|
302
|
+
/* ignore */
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
status() {
|
|
308
|
+
return {
|
|
309
|
+
id: this.record.id,
|
|
310
|
+
state: this.state,
|
|
311
|
+
error: this.error || undefined,
|
|
312
|
+
since: this.since,
|
|
313
|
+
latencyMs: this.latencyMs,
|
|
314
|
+
sys: this.sys,
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async connect(secrets) {
|
|
319
|
+
if (this.state === 'connected' && this.client !== null) return
|
|
320
|
+
if (this.connecting !== null) return this.connecting
|
|
321
|
+
this.wanted = true
|
|
322
|
+
clearTimeout(this.reconnectTimer)
|
|
323
|
+
this.connecting = this.#connect(secrets)
|
|
324
|
+
.catch((error) => {
|
|
325
|
+
// Any failure before the client is created (ssh2 missing, unreadable
|
|
326
|
+
// key, bad config) must still leave a visible error state.
|
|
327
|
+
if (this.state !== 'disconnected') {
|
|
328
|
+
this.state = 'error'
|
|
329
|
+
this.error = errorText(error)
|
|
330
|
+
}
|
|
331
|
+
throw error
|
|
332
|
+
})
|
|
333
|
+
.finally(() => {
|
|
334
|
+
this.connecting = null
|
|
335
|
+
})
|
|
336
|
+
return this.connecting
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async #connect(secrets) {
|
|
340
|
+
this.state = 'connecting'
|
|
341
|
+
this.error = ''
|
|
342
|
+
const Ssh2Client = await loadSsh2Client()
|
|
343
|
+
const pinnedFingerprint = normalizeHostKeyFingerprint(this.record.hostKeyFingerprint)
|
|
344
|
+
const config = {
|
|
345
|
+
host: this.record.host,
|
|
346
|
+
port: this.record.port,
|
|
347
|
+
username: this.record.username,
|
|
348
|
+
readyTimeout: 20000,
|
|
349
|
+
keepaliveInterval: 15000,
|
|
350
|
+
keepaliveCountMax: 3,
|
|
351
|
+
}
|
|
352
|
+
if (pinnedFingerprint !== null) {
|
|
353
|
+
config.hostVerifier = (key) => {
|
|
354
|
+
const actual = `SHA256:${createHash('sha256').update(key).digest('base64')}`.replace(/=+$/, '')
|
|
355
|
+
const expected = pinnedFingerprint.replace(/=+$/, '')
|
|
356
|
+
const ok = actual === expected
|
|
357
|
+
if (!ok) this.error = 'Host key fingerprint does not match the pinned value'
|
|
358
|
+
return ok
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
if (this.record.authType === 'password') {
|
|
362
|
+
const password = await secrets.get(this.record.id, 'PASSWORD')
|
|
363
|
+
if (password === null) throw fsError('REMOTE_DECK_NO_SECRET', 'No stored password for this connection; edit it and set one.')
|
|
364
|
+
config.password = password
|
|
365
|
+
} else {
|
|
366
|
+
if (!this.record.privateKeyPath) throw fsError('REMOTE_DECK_NO_KEY', 'No private key path configured.')
|
|
367
|
+
let key
|
|
368
|
+
try {
|
|
369
|
+
key = await readFile(this.record.privateKeyPath)
|
|
370
|
+
} catch (error) {
|
|
371
|
+
throw fsError('REMOTE_DECK_NO_KEY', `Cannot read the private key: ${errorText(error)}`)
|
|
372
|
+
}
|
|
373
|
+
config.privateKey = key
|
|
374
|
+
const passphrase = await secrets.get(this.record.id, 'PASSPHRASE')
|
|
375
|
+
if (passphrase !== null) config.passphrase = passphrase
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const hops = parseJumpSpec(this.record.jump)
|
|
379
|
+
if (hops.length > 0) {
|
|
380
|
+
try {
|
|
381
|
+
config.sock = await this.#openJumpChain(hops, secrets)
|
|
382
|
+
} catch (error) {
|
|
383
|
+
this.state = 'error'
|
|
384
|
+
this.error = errorText(error)
|
|
385
|
+
this.#closeJumpClients()
|
|
386
|
+
throw error
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const client = new Ssh2Client()
|
|
391
|
+
this.client = client
|
|
392
|
+
if (Number.isFinite(this.record.readyTimeoutMs) && this.record.readyTimeoutMs > 0) {
|
|
393
|
+
config.readyTimeout = Math.round(this.record.readyTimeoutMs)
|
|
394
|
+
}
|
|
395
|
+
await new Promise((resolve, reject) => {
|
|
396
|
+
let settled = false
|
|
397
|
+
const fail = (error) => {
|
|
398
|
+
if (settled) return
|
|
399
|
+
settled = true
|
|
400
|
+
this.state = 'error'
|
|
401
|
+
this.error = errorText(error)
|
|
402
|
+
try {
|
|
403
|
+
client.end()
|
|
404
|
+
} catch {
|
|
405
|
+
/* ignore */
|
|
406
|
+
}
|
|
407
|
+
this.#closeJumpClients()
|
|
408
|
+
reject(fsError('REMOTE_DECK_CONNECT_FAILED', this.error))
|
|
409
|
+
}
|
|
410
|
+
client.once('ready', () => {
|
|
411
|
+
settled = true
|
|
412
|
+
resolve()
|
|
413
|
+
})
|
|
414
|
+
// A listener must outlive the handshake: ssh2 can emit a second 'error'
|
|
415
|
+
// while cleaning up a timed-out/aborted handshake, and EventEmitter
|
|
416
|
+
// without an 'error' listener throws an uncaught exception that makes
|
|
417
|
+
// the whole DSH host exit.
|
|
418
|
+
client.on('error', (error) => {
|
|
419
|
+
if (settled) {
|
|
420
|
+
this.error = errorText(error)
|
|
421
|
+
this.hooks.onLog?.('ssh error', this.record.name, this.error)
|
|
422
|
+
return
|
|
423
|
+
}
|
|
424
|
+
fail(error)
|
|
425
|
+
})
|
|
426
|
+
client.once('close', () => {
|
|
427
|
+
if (!settled) fail(new Error('Connection closed during handshake'))
|
|
428
|
+
})
|
|
429
|
+
try {
|
|
430
|
+
client.connect(config)
|
|
431
|
+
} catch (error) {
|
|
432
|
+
fail(error)
|
|
433
|
+
}
|
|
434
|
+
})
|
|
435
|
+
|
|
436
|
+
this.sftp = await new Promise((resolve, reject) => {
|
|
437
|
+
client.sftp((error, sftp) => {
|
|
438
|
+
if (error) {
|
|
439
|
+
// A failed SFTP subsystem must not leak a live SSH socket.
|
|
440
|
+
try {
|
|
441
|
+
client.end()
|
|
442
|
+
} catch {
|
|
443
|
+
/* ignore */
|
|
444
|
+
}
|
|
445
|
+
reject(fsError('REMOTE_DECK_SFTP_FAILED', errorText(error)))
|
|
446
|
+
} else {
|
|
447
|
+
resolve(sftp)
|
|
448
|
+
}
|
|
449
|
+
})
|
|
450
|
+
})
|
|
451
|
+
|
|
452
|
+
this.state = 'connected'
|
|
453
|
+
this.since = Date.now()
|
|
454
|
+
this.error = ''
|
|
455
|
+
this.reconnectAttempt = 0
|
|
456
|
+
|
|
457
|
+
client.on('close', () => {
|
|
458
|
+
if (this.client !== client) return
|
|
459
|
+
this.#failPendingExec('Connection closed; the running command was interrupted.')
|
|
460
|
+
this.client = null
|
|
461
|
+
this.sftp = null
|
|
462
|
+
this.#closeJumpClients()
|
|
463
|
+
this.since = null
|
|
464
|
+
if (this.state === 'error') return
|
|
465
|
+
this.state = 'disconnected'
|
|
466
|
+
this.error = 'Connection closed'
|
|
467
|
+
this.#scheduleReconnect(secrets)
|
|
468
|
+
})
|
|
469
|
+
client.on('error', (error) => {
|
|
470
|
+
this.error = errorText(error)
|
|
471
|
+
this.hooks.onLog?.('ssh error', this.record.name, this.error)
|
|
472
|
+
})
|
|
473
|
+
|
|
474
|
+
try {
|
|
475
|
+
await this.probe()
|
|
476
|
+
} catch {
|
|
477
|
+
/* a connected host without a shell still serves files */
|
|
478
|
+
}
|
|
479
|
+
try {
|
|
480
|
+
this.hooks.onConnected?.(this)
|
|
481
|
+
} catch {
|
|
482
|
+
/* restoration hooks must not break the connection */
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
#scheduleReconnect(secrets) {
|
|
487
|
+
if (!this.wanted || this.disposed || this.reconnectTimer !== null) return
|
|
488
|
+
const delay = RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)]
|
|
489
|
+
this.reconnectAttempt += 1
|
|
490
|
+
this.reconnectTimer = setTimeout(() => {
|
|
491
|
+
this.reconnectTimer = null
|
|
492
|
+
if (!this.wanted || this.disposed) return
|
|
493
|
+
this.connect(secrets).catch(() => {
|
|
494
|
+
/* the next close schedules another attempt */
|
|
495
|
+
})
|
|
496
|
+
}, delay)
|
|
497
|
+
if (typeof this.reconnectTimer.unref === 'function') this.reconnectTimer.unref()
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** Round-trip latency plus remote identity, measured over one exec channel. */
|
|
501
|
+
async probe() {
|
|
502
|
+
const started = Date.now()
|
|
503
|
+
const result = await this.runCommand(PROBE_SCRIPT, null, { maxBytes: 64 * 1024, timeoutMs: 10000 })
|
|
504
|
+
const elapsed = Date.now() - started
|
|
505
|
+
const lines = result.stdout.split('\n').map((line) => line.trim())
|
|
506
|
+
this.latencyMs = elapsed
|
|
507
|
+
this.sys = {
|
|
508
|
+
os: lines[0] || '',
|
|
509
|
+
kernel: lines[1] || '',
|
|
510
|
+
arch: lines[2] || '',
|
|
511
|
+
shell: lines[3] || '',
|
|
512
|
+
home: lines[4] || '',
|
|
513
|
+
distro: lines[5] || '',
|
|
514
|
+
}
|
|
515
|
+
return { latencyMs: this.latencyMs, sys: this.sys }
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
async ensure(secrets) {
|
|
519
|
+
if (this.state === 'connected' && this.client !== null) return
|
|
520
|
+
await this.connect(secrets)
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Open the ProxyJump chain and return the stream that reaches the target's
|
|
525
|
+
* own host:port. Each hop authenticates with the configured connection it
|
|
526
|
+
* names when one matches, and otherwise falls back to the target's own
|
|
527
|
+
* credentials — the usual "one key everywhere" setup.
|
|
528
|
+
*/
|
|
529
|
+
async #openJumpChain(hops, secrets) {
|
|
530
|
+
const Ssh2Client = await loadSsh2Client()
|
|
531
|
+
let sock
|
|
532
|
+
for (let index = 0; index < hops.length; index += 1) {
|
|
533
|
+
const hop = hops[index]
|
|
534
|
+
const next = index + 1 < hops.length
|
|
535
|
+
? hops[index + 1]
|
|
536
|
+
: { host: this.record.host, port: this.record.port }
|
|
537
|
+
const auth = await this.#jumpAuth(hop, secrets)
|
|
538
|
+
const label = `${hop.user.length > 0 ? hop.user + '@' : ''}${hop.host}:${hop.port}`
|
|
539
|
+
const client = new Ssh2Client()
|
|
540
|
+
this.jumpClients.push(client)
|
|
541
|
+
await new Promise((resolve, reject) => {
|
|
542
|
+
const fail = (error) => {
|
|
543
|
+
try {
|
|
544
|
+
client.end()
|
|
545
|
+
} catch {
|
|
546
|
+
/* ignore */
|
|
547
|
+
}
|
|
548
|
+
reject(fsError('REMOTE_DECK_JUMP_FAILED', `jump host ${label}: ${errorText(error)}`))
|
|
549
|
+
}
|
|
550
|
+
client.once('ready', resolve)
|
|
551
|
+
client.once('error', fail)
|
|
552
|
+
const hopConfig = {
|
|
553
|
+
host: hop.host,
|
|
554
|
+
port: hop.port,
|
|
555
|
+
username: auth.username,
|
|
556
|
+
readyTimeout: 20000,
|
|
557
|
+
keepaliveInterval: 15000,
|
|
558
|
+
keepaliveCountMax: 3,
|
|
559
|
+
}
|
|
560
|
+
if (auth.privateKey !== undefined) hopConfig.privateKey = auth.privateKey
|
|
561
|
+
if (auth.password !== undefined) hopConfig.password = auth.password
|
|
562
|
+
if (auth.passphrase !== undefined) hopConfig.passphrase = auth.passphrase
|
|
563
|
+
if (sock !== undefined) hopConfig.sock = sock
|
|
564
|
+
try {
|
|
565
|
+
client.connect(hopConfig)
|
|
566
|
+
} catch (error) {
|
|
567
|
+
fail(error)
|
|
568
|
+
}
|
|
569
|
+
})
|
|
570
|
+
sock = await new Promise((resolve, reject) => {
|
|
571
|
+
client.forwardOut('127.0.0.1', 0, next.host, next.port, (error, stream) => {
|
|
572
|
+
if (error) {
|
|
573
|
+
reject(fsError(
|
|
574
|
+
'REMOTE_DECK_JUMP_FORWARD_FAILED',
|
|
575
|
+
`jump host ${label} could not reach ${next.host}:${next.port}: ${errorText(error)}`,
|
|
576
|
+
))
|
|
577
|
+
} else {
|
|
578
|
+
resolve(stream)
|
|
579
|
+
}
|
|
580
|
+
})
|
|
581
|
+
})
|
|
582
|
+
}
|
|
583
|
+
return sock
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
async #jumpAuth(hop, secrets) {
|
|
587
|
+
const resolver = this.hooks.resolveHop
|
|
588
|
+
const resolved = typeof resolver === 'function' ? await resolver(hop) : undefined
|
|
589
|
+
const record = resolved ?? this.record
|
|
590
|
+
const username = hop.user.length > 0 ? hop.user : record.username || this.record.username
|
|
591
|
+
if (record.authType === 'password') {
|
|
592
|
+
const password = await secrets.get(record.id, 'PASSWORD')
|
|
593
|
+
if (password === null) throw fsError('REMOTE_DECK_NO_SECRET', `No stored password for jump host ${hop.host}.`)
|
|
594
|
+
return { username, password }
|
|
595
|
+
}
|
|
596
|
+
const keyPath = record.privateKeyPath || this.record.privateKeyPath
|
|
597
|
+
if (!keyPath) throw fsError('REMOTE_DECK_NO_KEY', `No private key configured for jump host ${hop.host}.`)
|
|
598
|
+
let privateKey
|
|
599
|
+
try {
|
|
600
|
+
privateKey = await readFile(keyPath)
|
|
601
|
+
} catch (error) {
|
|
602
|
+
throw fsError('REMOTE_DECK_NO_KEY', `Cannot read the jump host key: ${errorText(error)}`)
|
|
603
|
+
}
|
|
604
|
+
const passphrase = await secrets.get(record.id, 'PASSPHRASE')
|
|
605
|
+
return passphrase === null ? { username, privateKey } : { username, privateKey, passphrase }
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
#closeJumpClients() {
|
|
609
|
+
for (const client of this.jumpClients) {
|
|
610
|
+
try {
|
|
611
|
+
client.end()
|
|
612
|
+
} catch {
|
|
613
|
+
/* ignore */
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
this.jumpClients = []
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
disconnect() {
|
|
620
|
+
this.wanted = false
|
|
621
|
+
this.#failPendingExec('Connection closed; the running command was interrupted.')
|
|
622
|
+
clearTimeout(this.reconnectTimer)
|
|
623
|
+
this.reconnectTimer = null
|
|
624
|
+
if (this.client !== null) {
|
|
625
|
+
try {
|
|
626
|
+
this.client.end()
|
|
627
|
+
} catch {
|
|
628
|
+
/* ignore */
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
this.client = null
|
|
632
|
+
this.sftp = null
|
|
633
|
+
this.#closeJumpClients()
|
|
634
|
+
this.state = 'disconnected'
|
|
635
|
+
this.since = null
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
requireSftp() {
|
|
639
|
+
if (this.sftp === null || this.state !== 'connected') {
|
|
640
|
+
throw fsError('REMOTE_DECK_NOT_CONNECTED', `Connection "${this.record.name}" is not connected.`)
|
|
641
|
+
}
|
|
642
|
+
return this.sftp
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
async runCommand(command, cwd, options) {
|
|
646
|
+
const client = this.client
|
|
647
|
+
if (client === null || this.state !== 'connected') {
|
|
648
|
+
throw fsError('REMOTE_DECK_NOT_CONNECTED', `Connection "${this.record.name}" is not connected.`)
|
|
649
|
+
}
|
|
650
|
+
const opts = options ?? {}
|
|
651
|
+
const script = buildCommandScript(command, cwd)
|
|
652
|
+
const cap = opts.maxBytes ?? 4 * 1024 * 1024
|
|
653
|
+
const deadlineMs = Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0 ? Math.round(opts.timeoutMs) : 0
|
|
654
|
+
return await new Promise((resolve) => {
|
|
655
|
+
let deadlineTimer = null
|
|
656
|
+
const out = []
|
|
657
|
+
const err = []
|
|
658
|
+
let outBytes = 0
|
|
659
|
+
let errBytes = 0
|
|
660
|
+
let truncatedOut = false
|
|
661
|
+
let truncatedErr = false
|
|
662
|
+
let finished = false
|
|
663
|
+
const finish = (result) => {
|
|
664
|
+
if (finished) return
|
|
665
|
+
finished = true
|
|
666
|
+
if (deadlineTimer !== null) clearTimeout(deadlineTimer)
|
|
667
|
+
this.pendingExec.delete(entry)
|
|
668
|
+
resolve({
|
|
669
|
+
code: typeof result.code === 'number' ? result.code : -1,
|
|
670
|
+
signal: result.signal ?? null,
|
|
671
|
+
stdout: result.stdout ?? '',
|
|
672
|
+
stderr: result.stderr ?? '',
|
|
673
|
+
truncatedOut,
|
|
674
|
+
truncatedErr,
|
|
675
|
+
transportError: result.transportError ?? null,
|
|
676
|
+
})
|
|
677
|
+
}
|
|
678
|
+
const entry = {
|
|
679
|
+
stream: null,
|
|
680
|
+
fail: (message) => {
|
|
681
|
+
try {
|
|
682
|
+
if (entry.stream !== null) entry.stream.close()
|
|
683
|
+
} catch {
|
|
684
|
+
/* ignore */
|
|
685
|
+
}
|
|
686
|
+
finish({ stdout: Buffer.concat(out).toString('utf8'), stderr: message, transportError: message })
|
|
687
|
+
},
|
|
688
|
+
}
|
|
689
|
+
this.pendingExec.add(entry)
|
|
690
|
+
if (deadlineMs > 0) {
|
|
691
|
+
deadlineTimer = setTimeout(() => {
|
|
692
|
+
try {
|
|
693
|
+
entry.stream?.close()
|
|
694
|
+
} catch {
|
|
695
|
+
/* ignore */
|
|
696
|
+
}
|
|
697
|
+
finish({ transportError: `command timed out after ${deadlineMs}ms` })
|
|
698
|
+
}, deadlineMs)
|
|
699
|
+
deadlineTimer.unref?.()
|
|
700
|
+
}
|
|
701
|
+
try {
|
|
702
|
+
client.exec(script, (error, stream) => {
|
|
703
|
+
if (finished) {
|
|
704
|
+
try {
|
|
705
|
+
stream.close()
|
|
706
|
+
} catch {
|
|
707
|
+
/* ignore */
|
|
708
|
+
}
|
|
709
|
+
return
|
|
710
|
+
}
|
|
711
|
+
if (error) {
|
|
712
|
+
finish({ stdout: '', stderr: '', transportError: errorText(error) })
|
|
713
|
+
return
|
|
714
|
+
}
|
|
715
|
+
entry.stream = stream
|
|
716
|
+
stream.on('data', (chunk) => {
|
|
717
|
+
if (outBytes >= cap) {
|
|
718
|
+
truncatedOut = true
|
|
719
|
+
return
|
|
720
|
+
}
|
|
721
|
+
const room = cap - outBytes
|
|
722
|
+
if (chunk.length > room) {
|
|
723
|
+
out.push(chunk.subarray(0, room))
|
|
724
|
+
outBytes = cap
|
|
725
|
+
truncatedOut = true
|
|
726
|
+
return
|
|
727
|
+
}
|
|
728
|
+
out.push(chunk)
|
|
729
|
+
outBytes += chunk.length
|
|
730
|
+
})
|
|
731
|
+
stream.stderr.on('data', (chunk) => {
|
|
732
|
+
if (errBytes >= cap) {
|
|
733
|
+
truncatedErr = true
|
|
734
|
+
return
|
|
735
|
+
}
|
|
736
|
+
const room = cap - errBytes
|
|
737
|
+
if (chunk.length > room) {
|
|
738
|
+
err.push(chunk.subarray(0, room))
|
|
739
|
+
errBytes = cap
|
|
740
|
+
truncatedErr = true
|
|
741
|
+
return
|
|
742
|
+
}
|
|
743
|
+
err.push(chunk)
|
|
744
|
+
errBytes += chunk.length
|
|
745
|
+
})
|
|
746
|
+
stream.on('close', (code, signal) => {
|
|
747
|
+
finish({
|
|
748
|
+
code: typeof code === 'number' ? code : -1,
|
|
749
|
+
signal: signal ?? null,
|
|
750
|
+
stdout: Buffer.concat(out).toString('utf8'),
|
|
751
|
+
stderr: Buffer.concat(err).toString('utf8'),
|
|
752
|
+
})
|
|
753
|
+
})
|
|
754
|
+
stream.on('error', (streamError) => {
|
|
755
|
+
finish({
|
|
756
|
+
stdout: Buffer.concat(out).toString('utf8'),
|
|
757
|
+
stderr: Buffer.concat(err).toString('utf8'),
|
|
758
|
+
transportError: errorText(streamError),
|
|
759
|
+
})
|
|
760
|
+
})
|
|
761
|
+
stream.stderr.on('error', (streamError) => {
|
|
762
|
+
finish({
|
|
763
|
+
stdout: Buffer.concat(out).toString('utf8'),
|
|
764
|
+
stderr: Buffer.concat(err).toString('utf8'),
|
|
765
|
+
transportError: errorText(streamError),
|
|
766
|
+
})
|
|
767
|
+
})
|
|
768
|
+
// Never leave the remote stdin open: prompting commands must see EOF
|
|
769
|
+
// instead of blocking the whole turn on an interactive prompt.
|
|
770
|
+
try {
|
|
771
|
+
stream.end()
|
|
772
|
+
} catch {
|
|
773
|
+
/* ignore */
|
|
774
|
+
}
|
|
775
|
+
if (opts.signal) {
|
|
776
|
+
const abort = () => {
|
|
777
|
+
try {
|
|
778
|
+
stream.close()
|
|
779
|
+
} catch {
|
|
780
|
+
/* ignore */
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
if (opts.signal.aborted) abort()
|
|
784
|
+
else opts.signal.addEventListener('abort', abort, { once: true })
|
|
785
|
+
}
|
|
786
|
+
})
|
|
787
|
+
} catch (error) {
|
|
788
|
+
finish({ stdout: '', stderr: '', transportError: errorText(error) })
|
|
789
|
+
}
|
|
790
|
+
})
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* Start one supervised remote command.
|
|
794
|
+
*
|
|
795
|
+
* The returned handle owns the SSH channel and the remote pid file:
|
|
796
|
+
* - `onChunk(channel, text)` streams stdout/stderr for a job output ring;
|
|
797
|
+
* - `done` settles with the same shape as `runCommand()`;
|
|
798
|
+
* - `kill(reason)` signals the recorded pid (TERM, then KILL) and closes
|
|
799
|
+
* the channel. It is the only path that terminates the remote process;
|
|
800
|
+
* a foreground timeout must promote to a background job instead.
|
|
801
|
+
*
|
|
802
|
+
* stdin is ended immediately so prompting commands fail fast (1.2.8).
|
|
803
|
+
*/
|
|
804
|
+
async startCommand(command, cwd, options) {
|
|
805
|
+
const client = this.client
|
|
806
|
+
if (client === null || this.state !== 'connected') {
|
|
807
|
+
throw fsError('REMOTE_DECK_NOT_CONNECTED', `Connection "${this.record.name}" is not connected.`)
|
|
808
|
+
}
|
|
809
|
+
const opts = options ?? {}
|
|
810
|
+
const cap = typeof opts.maxBytes === 'number' && opts.maxBytes > 0 ? opts.maxBytes : 4 * 1024 * 1024
|
|
811
|
+
const jobKey = typeof opts.jobKey === 'string' && opts.jobKey.length > 0
|
|
812
|
+
? opts.jobKey
|
|
813
|
+
: randomUUID().replaceAll('-', '').slice(0, 16)
|
|
814
|
+
const pidFile = `/tmp/.dsh-remote-deck/${jobKey}.pid`
|
|
815
|
+
const script = buildSupervisedScript(command, cwd, pidFile)
|
|
816
|
+
const stream = await new Promise((resolve, reject) => {
|
|
817
|
+
try {
|
|
818
|
+
client.exec(script, (error, channel) => {
|
|
819
|
+
if (error) reject(fsError('REMOTE_DECK_EXEC_FAILED', errorText(error)))
|
|
820
|
+
else resolve(channel)
|
|
821
|
+
})
|
|
822
|
+
} catch (error) {
|
|
823
|
+
reject(error)
|
|
824
|
+
}
|
|
825
|
+
})
|
|
826
|
+
const out = []
|
|
827
|
+
const err = []
|
|
828
|
+
let outBytes = 0
|
|
829
|
+
let errBytes = 0
|
|
830
|
+
let truncatedOut = false
|
|
831
|
+
let truncatedErr = false
|
|
832
|
+
let finished = false
|
|
833
|
+
let resolveDone
|
|
834
|
+
const done = new Promise((resolve) => {
|
|
835
|
+
resolveDone = resolve
|
|
836
|
+
})
|
|
837
|
+
const stdoutDecoder = new StringDecoder('utf8')
|
|
838
|
+
const stderrDecoder = new StringDecoder('utf8')
|
|
839
|
+
const emit = (channel, text) => {
|
|
840
|
+
if (typeof opts.onChunk !== 'function' || text.length === 0) return
|
|
841
|
+
try {
|
|
842
|
+
opts.onChunk(channel, text)
|
|
843
|
+
} catch {
|
|
844
|
+
/* consumer detached */
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
const finish = (result) => {
|
|
848
|
+
if (finished) return
|
|
849
|
+
finished = true
|
|
850
|
+
this.pendingExec.delete(entry)
|
|
851
|
+
emit('stdout', stdoutDecoder.end())
|
|
852
|
+
emit('stderr', stderrDecoder.end())
|
|
853
|
+
resolveDone({
|
|
854
|
+
code: typeof result.code === 'number' ? result.code : -1,
|
|
855
|
+
signal: result.signal ?? null,
|
|
856
|
+
stdout: result.stdout ?? '',
|
|
857
|
+
stderr: result.stderr ?? '',
|
|
858
|
+
truncatedOut,
|
|
859
|
+
truncatedErr,
|
|
860
|
+
transportError: result.transportError ?? null,
|
|
861
|
+
})
|
|
862
|
+
}
|
|
863
|
+
const entry = {
|
|
864
|
+
stream,
|
|
865
|
+
fail: (message) => {
|
|
866
|
+
try {
|
|
867
|
+
stream.close()
|
|
868
|
+
} catch {
|
|
869
|
+
/* ignore */
|
|
870
|
+
}
|
|
871
|
+
finish({
|
|
872
|
+
stdout: Buffer.concat(out).toString('utf8'),
|
|
873
|
+
stderr: Buffer.concat(err).toString('utf8'),
|
|
874
|
+
transportError: message,
|
|
875
|
+
})
|
|
876
|
+
},
|
|
877
|
+
}
|
|
878
|
+
this.pendingExec.add(entry)
|
|
879
|
+
stream.on('data', (chunk) => {
|
|
880
|
+
emit('stdout', stdoutDecoder.write(chunk))
|
|
881
|
+
if (outBytes >= cap) {
|
|
882
|
+
truncatedOut = true
|
|
883
|
+
return
|
|
884
|
+
}
|
|
885
|
+
const room = cap - outBytes
|
|
886
|
+
if (chunk.length > room) {
|
|
887
|
+
out.push(chunk.subarray(0, room))
|
|
888
|
+
outBytes = cap
|
|
889
|
+
truncatedOut = true
|
|
890
|
+
return
|
|
891
|
+
}
|
|
892
|
+
out.push(chunk)
|
|
893
|
+
outBytes += chunk.length
|
|
894
|
+
})
|
|
895
|
+
stream.stderr.on('data', (chunk) => {
|
|
896
|
+
emit('stderr', stderrDecoder.write(chunk))
|
|
897
|
+
if (errBytes >= cap) {
|
|
898
|
+
truncatedErr = true
|
|
899
|
+
return
|
|
900
|
+
}
|
|
901
|
+
const room = cap - errBytes
|
|
902
|
+
if (chunk.length > room) {
|
|
903
|
+
err.push(chunk.subarray(0, room))
|
|
904
|
+
errBytes = cap
|
|
905
|
+
truncatedErr = true
|
|
906
|
+
return
|
|
907
|
+
}
|
|
908
|
+
err.push(chunk)
|
|
909
|
+
errBytes += chunk.length
|
|
910
|
+
})
|
|
911
|
+
stream.on('close', (code, signal) => {
|
|
912
|
+
finish({
|
|
913
|
+
code: typeof code === 'number' ? code : -1,
|
|
914
|
+
signal: signal ?? null,
|
|
915
|
+
stdout: Buffer.concat(out).toString('utf8'),
|
|
916
|
+
stderr: Buffer.concat(err).toString('utf8'),
|
|
917
|
+
})
|
|
918
|
+
})
|
|
919
|
+
stream.on('error', (streamError) => {
|
|
920
|
+
finish({
|
|
921
|
+
stdout: Buffer.concat(out).toString('utf8'),
|
|
922
|
+
stderr: Buffer.concat(err).toString('utf8'),
|
|
923
|
+
transportError: errorText(streamError),
|
|
924
|
+
})
|
|
925
|
+
})
|
|
926
|
+
stream.stderr.on('error', (streamError) => {
|
|
927
|
+
finish({
|
|
928
|
+
stdout: Buffer.concat(out).toString('utf8'),
|
|
929
|
+
stderr: Buffer.concat(err).toString('utf8'),
|
|
930
|
+
transportError: errorText(streamError),
|
|
931
|
+
})
|
|
932
|
+
})
|
|
933
|
+
try {
|
|
934
|
+
stream.end()
|
|
935
|
+
} catch {
|
|
936
|
+
/* ignore */
|
|
937
|
+
}
|
|
938
|
+
const handle = {
|
|
939
|
+
jobKey,
|
|
940
|
+
pidFile,
|
|
941
|
+
done,
|
|
942
|
+
kill: async (reason) => {
|
|
943
|
+
const label = typeof reason === 'string' && reason.length > 0 ? reason : 'killed'
|
|
944
|
+
const graceMs = typeof opts.killGraceMs === 'number' && opts.killGraceMs > 0 ? opts.killGraceMs : 1000
|
|
945
|
+
const killWork = this.killPid(pidFile, graceMs).catch(() => null)
|
|
946
|
+
try {
|
|
947
|
+
await Promise.race([
|
|
948
|
+
killWork,
|
|
949
|
+
new Promise((resolve) => {
|
|
950
|
+
const timer = setTimeout(resolve, Math.max(2000, graceMs * 3))
|
|
951
|
+
timer.unref?.()
|
|
952
|
+
}),
|
|
953
|
+
])
|
|
954
|
+
} catch {
|
|
955
|
+
/* best effort: the channel close below still settles the job */
|
|
956
|
+
}
|
|
957
|
+
try {
|
|
958
|
+
stream.close()
|
|
959
|
+
} catch {
|
|
960
|
+
/* ignore */
|
|
961
|
+
}
|
|
962
|
+
return label
|
|
963
|
+
},
|
|
964
|
+
close: () => {
|
|
965
|
+
try {
|
|
966
|
+
stream.close()
|
|
967
|
+
} catch {
|
|
968
|
+
/* ignore */
|
|
969
|
+
}
|
|
970
|
+
},
|
|
971
|
+
}
|
|
972
|
+
return handle
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
/**
|
|
976
|
+
* Terminate a supervised remote command by its pid file.
|
|
977
|
+
* TERM the process group (falling back to the single pid), wait the grace
|
|
978
|
+
* period, then KILL. Detached grandchildren (setsid) are out of scope.
|
|
979
|
+
*/
|
|
980
|
+
async killPid(pidFile, graceMs) {
|
|
981
|
+
if (typeof pidFile !== 'string' || pidFile.length === 0) return null
|
|
982
|
+
const grace = Math.max(1, Math.round((typeof graceMs === 'number' && graceMs > 0 ? graceMs : 1000) / 1000))
|
|
983
|
+
const script = [
|
|
984
|
+
`p=$(cat ${quote(pidFile)} 2>/dev/null) || exit 0`,
|
|
985
|
+
'if [ -n "$p" ]; then',
|
|
986
|
+
' kill -TERM -- -"$p" 2>/dev/null || kill -TERM "$p" 2>/dev/null || true',
|
|
987
|
+
` sleep ${grace}`,
|
|
988
|
+
' kill -KILL -- -"$p" 2>/dev/null || kill -KILL "$p" 2>/dev/null || true',
|
|
989
|
+
'fi',
|
|
990
|
+
`rm -f ${quote(pidFile)} 2>/dev/null`,
|
|
991
|
+
'exit 0',
|
|
992
|
+
].join('\n')
|
|
993
|
+
return await this.runCommand(script, null, { maxBytes: 64 * 1024, timeoutMs: 8000 })
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/**
|
|
997
|
+
* Open a raw exec channel for callers that stream the output instead of
|
|
998
|
+
* collecting it — a `tar` archive piped straight into an HTTP response, for
|
|
999
|
+
* instance. The caller owns the stream.
|
|
1000
|
+
*/
|
|
1001
|
+
async streamCommand(command, cwd) {
|
|
1002
|
+
const client = this.client
|
|
1003
|
+
if (client === null || this.state !== 'connected') {
|
|
1004
|
+
throw fsError('REMOTE_DECK_NOT_CONNECTED', `Connection "${this.record.name}" is not connected.`)
|
|
1005
|
+
}
|
|
1006
|
+
const script = cwd ? `cd ${quote(cwd)} 2>/dev/null || cd ~; ${command}` : command
|
|
1007
|
+
return await new Promise((resolve, reject) => {
|
|
1008
|
+
try {
|
|
1009
|
+
client.exec(script, (error, stream) => {
|
|
1010
|
+
if (error) reject(fsError('REMOTE_DECK_EXEC_FAILED', errorText(error)))
|
|
1011
|
+
else resolve(stream)
|
|
1012
|
+
})
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
reject(fsError('REMOTE_DECK_EXEC_FAILED', errorText(error)))
|
|
1015
|
+
}
|
|
1016
|
+
})
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
/** Interactive shell (PTY). Caller owns the stream lifecycle. */
|
|
1020
|
+
async shell({ cols = 120, rows = 30, term = 'xterm-256color' } = {}) {
|
|
1021
|
+
const client = this.client
|
|
1022
|
+
if (client === null || this.state !== 'connected') {
|
|
1023
|
+
throw fsError('REMOTE_DECK_NOT_CONNECTED', `Connection "${this.record.name}" is not connected.`)
|
|
1024
|
+
}
|
|
1025
|
+
return await new Promise((resolve, reject) => {
|
|
1026
|
+
client.shell({ term, cols, rows }, (error, stream) => {
|
|
1027
|
+
if (error) reject(fsError('REMOTE_DECK_SHELL_FAILED', errorText(error)))
|
|
1028
|
+
else resolve(stream)
|
|
1029
|
+
})
|
|
1030
|
+
})
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
/**
|
|
1034
|
+
* One command on an interactive shell channel (PTY). Caller owns the stream.
|
|
1035
|
+
*
|
|
1036
|
+
* A terminal consumer needs the command to run *inside* the allocated PTY so it
|
|
1037
|
+
* stays interactive and resizable; the plain shell channel cannot express that,
|
|
1038
|
+
* and ssh2 carries it as an `exec` request with a `pty` option.
|
|
1039
|
+
*/
|
|
1040
|
+
async shellCommand(command, { cols = 120, rows = 30, term = 'xterm-256color' } = {}) {
|
|
1041
|
+
const client = this.client
|
|
1042
|
+
if (client === null || this.state !== 'connected') {
|
|
1043
|
+
throw fsError('REMOTE_DECK_NOT_CONNECTED', `Connection "${this.record.name}" is not connected.`)
|
|
1044
|
+
}
|
|
1045
|
+
return await new Promise((resolve, reject) => {
|
|
1046
|
+
client.exec(command, { pty: { term, cols, rows } }, (error, stream) => {
|
|
1047
|
+
if (error) reject(fsError('REMOTE_DECK_SHELL_FAILED', errorText(error)))
|
|
1048
|
+
else resolve(stream)
|
|
1049
|
+
})
|
|
1050
|
+
})
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
forwardOut(srcIP, srcPort, dstHost, dstPort) {
|
|
1054
|
+
const client = this.client
|
|
1055
|
+
if (client === null || this.state !== 'connected') {
|
|
1056
|
+
// Rejected, never thrown: this is called from a TCP server's connection
|
|
1057
|
+
// callback, where a synchronous throw escapes the promise chain and takes
|
|
1058
|
+
// the whole application down with it.
|
|
1059
|
+
return Promise.reject(fsError(
|
|
1060
|
+
'REMOTE_DECK_NOT_CONNECTED',
|
|
1061
|
+
`Connection "${this.record.name}" is not connected.`,
|
|
1062
|
+
))
|
|
1063
|
+
}
|
|
1064
|
+
return new Promise((resolve, reject) => {
|
|
1065
|
+
client.forwardOut(srcIP, srcPort, dstHost, dstPort, (error, stream) => {
|
|
1066
|
+
if (error) reject(fsError('REMOTE_DECK_FORWARD_FAILED', errorText(error)))
|
|
1067
|
+
else resolve(stream)
|
|
1068
|
+
})
|
|
1069
|
+
})
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
dispose() {
|
|
1073
|
+
this.disposed = true
|
|
1074
|
+
this.disconnect()
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
/**
|
|
1079
|
+
* Build the remote shell script for one command.
|
|
1080
|
+
* A missing working directory is a hard error: silently falling back to the
|
|
1081
|
+
* home directory used to run git and other stateful commands in the wrong
|
|
1082
|
+
* place. The wrapper never reads stdin; callers end the exec channel stdin.
|
|
1083
|
+
*
|
|
1084
|
+
* @param {string} command raw command text
|
|
1085
|
+
* @param {string | null | undefined} cwd remote working directory
|
|
1086
|
+
* @returns {string} POSIX shell script
|
|
1087
|
+
*/
|
|
1088
|
+
export function buildCommandScript(command, cwd) {
|
|
1089
|
+
if (!cwd) return command
|
|
1090
|
+
const notice = quote(`remote-deck: working directory unavailable: ${cwd}`)
|
|
1091
|
+
return `cd ${quote(cwd)} 2>/dev/null || { printf '%s\n' ${notice} >&2; exit 1; }; ${command}`
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
/**
|
|
1095
|
+
* Build the supervised remote shell script: record the shell pid, run the
|
|
1096
|
+
* command, then remove the pid file. Used by startCommand() for job kills.
|
|
1097
|
+
*
|
|
1098
|
+
* @param {string} command raw command text
|
|
1099
|
+
* @param {string | null | undefined} cwd remote working directory
|
|
1100
|
+
* @param {string} pidFile remote pid file path
|
|
1101
|
+
* @returns {string} POSIX shell script
|
|
1102
|
+
*/
|
|
1103
|
+
export function buildSupervisedScript(command, cwd, pidFile) {
|
|
1104
|
+
const clean = `rm -f ${quote(pidFile)} 2>/dev/null`
|
|
1105
|
+
const failure = quote(`remote-deck: working directory unavailable: ${cwd}`)
|
|
1106
|
+
const cdPart = cwd ? `cd ${quote(cwd)} 2>/dev/null || { printf '%s\n' ${failure} >&2; ${clean}; exit 1; }; ` : ''
|
|
1107
|
+
return [
|
|
1108
|
+
'umask 077',
|
|
1109
|
+
'mkdir -p /tmp/.dsh-remote-deck 2>/dev/null && chmod 700 /tmp/.dsh-remote-deck 2>/dev/null || true',
|
|
1110
|
+
"find /tmp/.dsh-remote-deck -maxdepth 1 -name '*.pid' -mmin +180 -delete 2>/dev/null || true",
|
|
1111
|
+
`printf '%s' "$$" > ${quote(pidFile)} 2>/dev/null`,
|
|
1112
|
+
`${cdPart}${command}`,
|
|
1113
|
+
'__rc=$?',
|
|
1114
|
+
// Keep the pid record while background children still share the process
|
|
1115
|
+
// group: 'sleep 30 &' ends the shell but leaves a child that a later
|
|
1116
|
+
// job_kill must still be able to terminate through the recorded pid.
|
|
1117
|
+
'if [ -z "$(jobs -p 2>/dev/null)" ]; then',
|
|
1118
|
+
` ${clean}`,
|
|
1119
|
+
'fi',
|
|
1120
|
+
'exit $__rc',
|
|
1121
|
+
].join('\n')
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
function normalizeHostKeyFingerprint(value) {
|
|
1125
|
+
if (typeof value !== 'string') return null
|
|
1126
|
+
const trimmed = value.trim()
|
|
1127
|
+
if (trimmed.length === 0) return null
|
|
1128
|
+
return trimmed.replace(/^SHA256:/i, 'SHA256:')
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
function quote(value) {
|
|
1132
|
+
return `'${String(value).replace(/'/g, `'\\''`)}'`
|
|
1133
|
+
}
|