@fish-under-sea/dsh-ssh-fish 0.0.0-stage → 0.5.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 (80) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +98 -2
  4. package/README.zh.md +99 -0
  5. package/cordis.patch.yml +12 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +16487 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +3511 -0
  10. package/lib/types/client/api.d.ts +141 -0
  11. package/lib/types/client/index.d.ts +37 -0
  12. package/lib/types/client/locales.d.ts +164 -0
  13. package/lib/types/client/native-panel.d.ts +70 -0
  14. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  15. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  16. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  17. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  18. package/lib/types/client/panel/TerminalTab.d.ts +22 -0
  19. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  20. package/lib/types/client/panel/TunnelsTab.d.ts +19 -0
  21. package/lib/types/client/panel/controller.d.ts +89 -0
  22. package/lib/types/client/panel/helpers.d.ts +45 -0
  23. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  24. package/lib/types/client/settings-binding.d.ts +61 -0
  25. package/lib/types/dsh-home.d.ts +16 -0
  26. package/lib/types/engine/cluster.d.ts +19 -0
  27. package/lib/types/engine/connection-pool.d.ts +112 -0
  28. package/lib/types/engine/proxy-command.d.ts +36 -0
  29. package/lib/types/engine/pty.d.ts +32 -0
  30. package/lib/types/engine/sftp.d.ts +20 -0
  31. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  32. package/lib/types/engine/tunnel.d.ts +36 -0
  33. package/lib/types/engine.d.ts +89 -0
  34. package/lib/types/http.d.ts +59 -0
  35. package/lib/types/index.d.ts +83 -0
  36. package/lib/types/loopback.d.ts +24 -0
  37. package/lib/types/mount-once.d.ts +55 -0
  38. package/lib/types/protocol.d.ts +239 -0
  39. package/lib/types/routes.d.ts +33 -0
  40. package/lib/types/ssh-config.d.ts +34 -0
  41. package/lib/types/store.d.ts +71 -0
  42. package/lib/types/tool-surface.d.ts +71 -0
  43. package/lib/types/tools.d.ts +42 -0
  44. package/package.json +106 -4
  45. package/src/client/api.ts +562 -0
  46. package/src/client/css-modules.d.ts +5 -0
  47. package/src/client/index.ts +137 -0
  48. package/src/client/locales.ts +338 -0
  49. package/src/client/native-panel.tsx +141 -0
  50. package/src/client/panel/ClusterTab.tsx +123 -0
  51. package/src/client/panel/HostFormDialog.tsx +258 -0
  52. package/src/client/panel/HostsTab.tsx +325 -0
  53. package/src/client/panel/SshPanel.tsx +90 -0
  54. package/src/client/panel/TerminalTab.tsx +330 -0
  55. package/src/client/panel/TransferTab.tsx +232 -0
  56. package/src/client/panel/TunnelsTab.tsx +244 -0
  57. package/src/client/panel/controller.ts +167 -0
  58. package/src/client/panel/helpers.ts +84 -0
  59. package/src/client/panel/panel.module.css +876 -0
  60. package/src/client/panel/xterm.css.ts +2 -0
  61. package/src/client/settings-binding.ts +165 -0
  62. package/src/dsh-home.ts +42 -0
  63. package/src/engine/cluster.ts +60 -0
  64. package/src/engine/connection-pool.ts +543 -0
  65. package/src/engine/proxy-command.ts +248 -0
  66. package/src/engine/pty.ts +78 -0
  67. package/src/engine/sftp.ts +226 -0
  68. package/src/engine/terminal-sessions.ts +280 -0
  69. package/src/engine/tunnel.ts +194 -0
  70. package/src/engine.ts +176 -0
  71. package/src/http.ts +127 -0
  72. package/src/index.ts +234 -0
  73. package/src/loopback.ts +63 -0
  74. package/src/mount-once.ts +142 -0
  75. package/src/protocol.ts +230 -0
  76. package/src/routes.ts +494 -0
  77. package/src/ssh-config.ts +153 -0
  78. package/src/store.ts +419 -0
  79. package/src/tool-surface.ts +95 -0
  80. package/src/tools.ts +404 -0
package/src/routes.ts ADDED
@@ -0,0 +1,494 @@
1
+ /**
2
+ * The /api/dsh-ssh route family: host CRUD, exec, cluster, SFTP transfer
3
+ * (NDJSON progress stream for uploads, binary stream for downloads), remote
4
+ * listing, tunnels, and the WebSocket PTY terminal upgrade. Every route
5
+ * carries a loopback-only trust fence (plus browser same-origin markers) —
6
+ * these endpoints execute commands on remote servers, so LAN-exposed dsh web
7
+ * deployments must not serve them.
8
+ */
9
+
10
+ import { closeSync, createReadStream, createWriteStream, mkdirSync, openSync } from 'node:fs'
11
+ import { unlink } from 'node:fs/promises'
12
+ import type { IncomingMessage, ServerResponse } from 'node:http'
13
+ import { basename, join } from 'node:path'
14
+ import { tmpdir } from 'node:os'
15
+ import { randomBytes } from 'node:crypto'
16
+ import { WebSocket, WebSocketServer } from 'ws'
17
+ import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
18
+ import type { SshEngine } from './engine.ts'
19
+ import { TerminalSessionRegistry } from './engine/terminal-sessions.ts'
20
+ import { readJsonBody, writeJson } from './http.ts'
21
+ import { isLoopbackRequest } from './loopback.ts'
22
+ import { SSH_API, type HostPayload, type TerminalServerFrame } from './protocol.ts'
23
+ import type { HostStore } from './store.ts'
24
+
25
+ /** Cap on declared upload bodies (staged to disk before SFTP). */
26
+ const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024
27
+
28
+ /**
29
+ * One noServer WebSocket server for terminal upgrades: the browser half uses
30
+ * a standards-compliant WebSocket, so the host must speak real RFC 6455
31
+ * frames (the webserver hands us the raw upgraded socket).
32
+ */
33
+ const terminalWss = new WebSocketServer({ noServer: true })
34
+
35
+ /** URL query helper (first value, decoded). */
36
+ function queryParam(url: URL, name: string): string | undefined {
37
+ const value = url.searchParams.get(name)
38
+ return value === null ? undefined : value
39
+ }
40
+
41
+ /** Route family dependencies. */
42
+ export interface SshRoutesDeps {
43
+ /** The host store (CRUD). */
44
+ store: HostStore
45
+ /** The engine (ops). */
46
+ engine: SshEngine
47
+ /** Temp dir for upload/download staging (tests inject a sandbox). */
48
+ stagingDir?: string
49
+ /** Upload byte cap override (tests); defaults to MAX_UPLOAD_BYTES. */
50
+ maxUploadBytes?: number
51
+ }
52
+
53
+ /**
54
+ * Build every /api/dsh-ssh route (exact paths) plus the terminal upgrade.
55
+ * @param deps - store, engine, staging dir.
56
+ * @returns routes and the upgrade route.
57
+ */
58
+ export function makeRoutes(deps: SshRoutesDeps): { routes: WebRoute[]; upgrade: WebUpgradeRoute; terminalSessions: TerminalSessionRegistry } {
59
+ const { store, engine } = deps
60
+ const staging = deps.stagingDir ?? join(tmpdir(), 'dsh-ssh-uploads')
61
+ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
62
+ // The upload route stages request bodies here; it must exist before the
63
+ // first request (a missing dir would hang the first upload forever).
64
+ // 0700 keeps in-flight transfers unreadable to other local users (the
65
+ // staged files below are 0600; downloads are pre-created 0600 as well).
66
+ mkdirSync(staging, { recursive: true, mode: 0o700 })
67
+
68
+ /** Guard helper: fence + method check. */
69
+ const guard = (req: IncomingMessage, res: ServerResponse, method: string): boolean => {
70
+ if (!isLoopbackRequest(req)) {
71
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
72
+ return false
73
+ }
74
+ if (req.method !== method) {
75
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` })
76
+ return false
77
+ }
78
+ return true
79
+ }
80
+
81
+ const routes: WebRoute[] = [
82
+ // ------------------------------------------------------------ hosts
83
+ {
84
+ kind: 'exact',
85
+ path: SSH_API.hosts,
86
+ handler: async (req, res) => {
87
+ // One handler per path (the webserver keyed route registry rejects
88
+ // duplicate (kind, path)); dispatch by HTTP method here.
89
+ const method = req.method ?? 'GET'
90
+ if (!isLoopbackRequest(req)) {
91
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
92
+ return
93
+ }
94
+ const url = new URL(req.url ?? '/', 'http://localhost')
95
+ if (method === 'GET') {
96
+ writeJson(res, 200, { hosts: engine.list(queryParam(url, 'query')) })
97
+ return
98
+ }
99
+ if (method === 'POST') {
100
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
101
+ if (body === null) {
102
+ writeJson(res, 400, { error: 'invalid JSON body' })
103
+ return
104
+ }
105
+ try {
106
+ const entry = store.create(body as unknown as HostPayload)
107
+ writeJson(res, 201, { host: store.summarize(entry) })
108
+ } catch (error) {
109
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
110
+ }
111
+ return
112
+ }
113
+ if (method !== 'PATCH' && method !== 'DELETE') {
114
+ writeJson(res, 405, { error: `method not allowed: ${method}` })
115
+ return
116
+ }
117
+ const alias = queryParam(url, 'alias')
118
+ if (alias === undefined || alias === '') {
119
+ writeJson(res, 400, { error: 'alias query parameter is required' })
120
+ return
121
+ }
122
+ if (method === 'PATCH') {
123
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
124
+ if (body === null) {
125
+ writeJson(res, 400, { error: 'invalid JSON body' })
126
+ return
127
+ }
128
+ try {
129
+ const entry = store.update(alias, body as unknown as Partial<HostPayload>)
130
+ // Connection-relevant changes invalidate the pooled connection:
131
+ // without this the pool would keep running commands on the old
132
+ // host/credentials until the idle sweep (up to 30 min later).
133
+ const patch = body as Record<string, unknown>
134
+ if (['host', 'port', 'user', 'auth', 'proxyJump', 'proxyCommand'].some(key => patch[key] !== undefined)) {
135
+ engine.dropAlias(alias)
136
+ }
137
+ writeJson(res, 200, { host: store.summarize(entry) })
138
+ } catch (error) {
139
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
140
+ }
141
+ return
142
+ }
143
+ if (method === 'DELETE') {
144
+ try {
145
+ engine.dropAlias(alias)
146
+ store.delete(alias)
147
+ writeJson(res, 200, { ok: true })
148
+ } catch (error) {
149
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
150
+ }
151
+ return
152
+ }
153
+ writeJson(res, 405, { error: `method not allowed: ${method}` })
154
+ },
155
+ },
156
+ {
157
+ kind: 'exact',
158
+ path: SSH_API.importSshConfig,
159
+ handler: async (req, res) => {
160
+ if (!guard(req, res, 'POST')) return
161
+ try {
162
+ writeJson(res, 200, { result: store.importFromSshConfig() })
163
+ } catch (error) {
164
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
165
+ }
166
+ },
167
+ },
168
+ // ------------------------------------------------------------ ops
169
+ {
170
+ kind: 'exact',
171
+ path: SSH_API.test,
172
+ handler: async (req, res) => {
173
+ if (!guard(req, res, 'POST')) return
174
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
175
+ const alias = typeof body?.alias === 'string' ? body.alias : ''
176
+ if (alias === '') {
177
+ writeJson(res, 400, { error: 'alias is required' })
178
+ return
179
+ }
180
+ try {
181
+ writeJson(res, 200, { result: await engine.test(alias) })
182
+ } catch (error) {
183
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
184
+ }
185
+ },
186
+ },
187
+ {
188
+ kind: 'exact',
189
+ path: SSH_API.exec,
190
+ handler: async (req, res) => {
191
+ if (!guard(req, res, 'POST')) return
192
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
193
+ const alias = typeof body?.alias === 'string' ? body.alias : ''
194
+ const command = typeof body?.command === 'string' ? body.command : ''
195
+ if (alias === '' || command === '') {
196
+ writeJson(res, 400, { error: 'alias and command are required' })
197
+ return
198
+ }
199
+ const timeoutMs = typeof body?.timeoutMs === 'number' ? body.timeoutMs : undefined
200
+ try {
201
+ writeJson(res, 200, { result: await engine.exec(alias, command, timeoutMs) })
202
+ } catch (error) {
203
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
204
+ }
205
+ },
206
+ },
207
+ {
208
+ kind: 'exact',
209
+ path: SSH_API.cluster,
210
+ handler: async (req, res) => {
211
+ if (!guard(req, res, 'POST')) return
212
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
213
+ const command = typeof body?.command === 'string' ? body.command : ''
214
+ if (command === '') {
215
+ writeJson(res, 400, { error: 'command is required' })
216
+ return
217
+ }
218
+ const aliases = Array.isArray(body?.aliases) ? body.aliases.filter((x): x is string => typeof x === 'string') : undefined
219
+ const tags = Array.isArray(body?.tags) ? body.tags.filter((x): x is string => typeof x === 'string') : undefined
220
+ const environment = typeof body?.environment === 'string' ? body.environment : undefined
221
+ const timeoutMs = typeof body?.timeoutMs === 'number' ? body.timeoutMs : undefined
222
+ const maxWorkers = typeof body?.maxWorkers === 'number' ? body.maxWorkers : undefined
223
+ const hasAliases = aliases?.some(alias => alias.trim() !== '') === true
224
+ const hasEnvironment = typeof environment === 'string' && environment.trim() !== ''
225
+ const hasTags = tags?.some(tag => tag.trim() !== '') === true
226
+ if (!hasAliases && !hasEnvironment && !hasTags) {
227
+ writeJson(res, 400, { error: 'ssh_cluster requires aliases, environment, or tags to limit the target set' })
228
+ return
229
+ }
230
+ try {
231
+ writeJson(res, 200, { results: await engine.cluster({ command, aliases, environment, tags, timeoutMs, maxWorkers }) })
232
+ } catch (error) {
233
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
234
+ }
235
+ },
236
+ },
237
+ // ------------------------------------------------------------- ls
238
+ {
239
+ kind: 'exact',
240
+ path: SSH_API.ls,
241
+ handler: async (req, res) => {
242
+ if (!guard(req, res, 'GET')) return
243
+ const url = new URL(req.url ?? '/', 'http://localhost')
244
+ const alias = queryParam(url, 'alias')
245
+ const path = queryParam(url, 'path') ?? '/'
246
+ if (alias === undefined || alias === '') {
247
+ writeJson(res, 400, { error: 'alias query parameter is required' })
248
+ return
249
+ }
250
+ try {
251
+ writeJson(res, 200, { entries: await engine.ls(alias, path) })
252
+ } catch (error) {
253
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
254
+ }
255
+ },
256
+ },
257
+ // --------------------------------------------------------- tunnel
258
+ {
259
+ kind: 'exact',
260
+ path: SSH_API.tunnel,
261
+ handler: async (req, res) => {
262
+ if (!guard(req, res, 'POST')) return
263
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
264
+ const action = typeof body?.action === 'string' ? body.action : ''
265
+ if (action === 'list') {
266
+ writeJson(res, 200, { tunnels: engine.listTunnels() })
267
+ return
268
+ }
269
+ if (action === 'start') {
270
+ const alias = typeof body?.alias === 'string' ? body.alias : ''
271
+ const remotePort = typeof body?.remotePort === 'number' ? body.remotePort : undefined
272
+ if (alias === '' || remotePort === undefined) {
273
+ writeJson(res, 400, { error: 'alias and remotePort are required' })
274
+ return
275
+ }
276
+ try {
277
+ const tunnel = await engine.startTunnel(alias, {
278
+ remotePort,
279
+ remoteHost: typeof body?.remoteHost === 'string' && body.remoteHost !== '' ? body.remoteHost : undefined,
280
+ localPort: typeof body?.localPort === 'number' ? body.localPort : undefined,
281
+ })
282
+ writeJson(res, 200, { tunnel })
283
+ } catch (error) {
284
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
285
+ }
286
+ return
287
+ }
288
+ if (action === 'stop') {
289
+ const id = typeof body?.tunnelId === 'string' ? body.tunnelId : ''
290
+ if (id === '') {
291
+ writeJson(res, 400, { error: 'tunnelId is required' })
292
+ return
293
+ }
294
+ writeJson(res, 200, { ok: engine.stopTunnel(id) })
295
+ return
296
+ }
297
+ if (action === 'stop-all') {
298
+ const alias = typeof body?.alias === 'string' ? body.alias : undefined
299
+ writeJson(res, 200, { stopped: engine.stopAllTunnels(alias === '' ? undefined : alias) })
300
+ return
301
+ }
302
+ writeJson(res, 400, { error: `unknown action '${action}'` })
303
+ },
304
+ },
305
+ // --------------------------------------------------------- upload
306
+ {
307
+ kind: 'exact',
308
+ path: SSH_API.upload,
309
+ handler: async (req, res) => {
310
+ if (!guard(req, res, 'POST')) return
311
+ const url = new URL(req.url ?? '/', 'http://localhost')
312
+ const alias = queryParam(url, 'alias')
313
+ const remotePath = queryParam(url, 'remotePath')
314
+ if (alias === undefined || remotePath === undefined) {
315
+ writeJson(res, 400, { error: 'alias and remotePath query parameters are required' })
316
+ return
317
+ }
318
+ const declared = Number(req.headers['content-length'])
319
+ if (Number.isFinite(declared) && declared > maxUploadBytes) {
320
+ writeJson(res, 413, { error: 'upload body too large' })
321
+ return
322
+ }
323
+ res.writeHead(200, {
324
+ 'content-type': 'application/x-ndjson; charset=utf-8',
325
+ 'cache-control': 'no-cache',
326
+ 'referrer-policy': 'no-referrer',
327
+ })
328
+ const emit = (line: unknown): void => {
329
+ try { res.write(JSON.stringify(line) + '\n') } catch { /* client gone */ }
330
+ }
331
+ // Stage the uploaded bytes, then SFTP them out with progress frames.
332
+ const tmp = join(staging, `upload-${randomBytes(6).toString('hex')}`)
333
+ const sink = createWriteStream(tmp, { mode: 0o600 })
334
+ let settled = false
335
+ // Every terminal path (sink error, client abort, response loss) must
336
+ // emit a result frame, end the response, and remove the tmp file.
337
+ const fail = (error: unknown): void => {
338
+ if (settled) return
339
+ settled = true
340
+ emit({ type: 'result', ok: false, error: error instanceof Error ? error.message : String(error) })
341
+ // End the response only after the tmp file is gone, and unlink only
342
+ // after the sink is fully closed: destroying a WriteStream whose
343
+ // fs.open is still pending lets the open RE-CREATE the file after
344
+ // an early unlink, leaving staging populated (this raced the
345
+ // response end and made the byte-cap test flaky).
346
+ const cleanup = (): void => {
347
+ void unlink(tmp).catch(() => undefined).finally(() => {
348
+ try { res.end() } catch { /* closed */ }
349
+ })
350
+ }
351
+ if (sink.destroyed) {
352
+ cleanup()
353
+ } else {
354
+ sink.once('close', cleanup)
355
+ try { sink.destroy() } catch { cleanup() }
356
+ }
357
+ }
358
+ const done = (): void => {
359
+ if (settled) return
360
+ settled = true
361
+ try { res.end() } catch { /* closed */ }
362
+ }
363
+ sink.on('error', (error) => fail(error))
364
+ req.on('error', (error) => fail(error))
365
+ req.on('aborted', () => fail('upload aborted by the client'))
366
+ res.on('error', () => fail('response stream closed'))
367
+ res.on('close', () => { if (!res.writableEnded) fail('connection closed') })
368
+ // The content-length pre-check above can be bypassed by chunked or
369
+ // header-less requests: count the bytes as they actually arrive and
370
+ // abort the moment the cap is exceeded.
371
+ let received = 0
372
+ let capped = false
373
+ req.on('data', (chunk: Buffer) => {
374
+ received += chunk.byteLength
375
+ if (received > maxUploadBytes && !capped) {
376
+ capped = true
377
+ fail('upload body too large')
378
+ // Keep the socket alive until the response flush finishes:
379
+ // destroying the request here races res.end() and the client
380
+ // sees a hang-up instead of the result frame. Drain the rest of
381
+ // the body so the socket can close cleanly afterwards.
382
+ res.on('finish', () => { try { req.destroy() } catch { /* closed */ } })
383
+ req.resume()
384
+ }
385
+ })
386
+ req.pipe(sink)
387
+ sink.on('finish', async () => {
388
+ if (settled) return
389
+ emit({ type: 'progress', progress: { phase: 'connecting', file: remotePath, transferred: 0, total: 0, percent: 0 } })
390
+ try {
391
+ const outcome = await engine.upload(alias, tmp, remotePath, false, progress => emit({ type: 'progress', progress }))
392
+ emit({ type: 'result', ok: true, transferredBytes: outcome.bytes })
393
+ } catch (error) {
394
+ emit({ type: 'result', ok: false, error: error instanceof Error ? error.message : String(error) })
395
+ } finally {
396
+ await unlink(tmp).catch(() => undefined)
397
+ done()
398
+ }
399
+ })
400
+ },
401
+ },
402
+ // ------------------------------------------------------- download
403
+ {
404
+ kind: 'exact',
405
+ path: SSH_API.download,
406
+ handler: async (req, res) => {
407
+ if (!guard(req, res, 'GET')) return
408
+ const url = new URL(req.url ?? '/', 'http://localhost')
409
+ const alias = queryParam(url, 'alias')
410
+ const remotePath = queryParam(url, 'remotePath')
411
+ if (alias === undefined || remotePath === undefined) {
412
+ writeJson(res, 400, { error: 'alias and remotePath query parameters are required' })
413
+ return
414
+ }
415
+ const tmp = join(staging, `download-${randomBytes(6).toString('hex')}`)
416
+ try {
417
+ // Pre-create with 0600: ssh2's fastGet opens the destination with
418
+ // umask-default permissions and a pre-created file keeps the mode.
419
+ closeSync(openSync(tmp, 'w', 0o600))
420
+ const outcome = await engine.download(alias, remotePath, tmp)
421
+ res.writeHead(200, {
422
+ 'content-type': 'application/octet-stream',
423
+ 'content-length': String(outcome.bytes),
424
+ 'content-disposition': `attachment; filename="${basename(remotePath).replace(/"/g, '')}"`,
425
+ 'referrer-policy': 'no-referrer',
426
+ })
427
+ await new Promise<void>((resolve, reject) => {
428
+ const source = createReadStream(tmp)
429
+ source.on('error', reject)
430
+ res.on('error', reject)
431
+ source.pipe(res)
432
+ source.on('end', resolve)
433
+ })
434
+ } catch (error) {
435
+ if (!res.headersSent) {
436
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
437
+ } else {
438
+ // Mid-stream failure after headers: destroy so the browser does
439
+ // not hang waiting for the promised content-length bytes.
440
+ res.destroy()
441
+ }
442
+ } finally {
443
+ await unlink(tmp).catch(() => undefined)
444
+ }
445
+ },
446
+ },
447
+ ]
448
+
449
+ // ---------------------------------------------- terminal (upgrade)
450
+ // The shell outlives the view that opened it: a session is created once and
451
+ // any later socket attaches by id, so a panel switch or a dropped socket
452
+ // does not tear the remote shell down (engine/terminal-sessions.ts).
453
+ const terminalSessions = new TerminalSessionRegistry({
454
+ openShell: (alias, size, onKeyboardInteractive) => engine.openShell(alias, size, onKeyboardInteractive),
455
+ })
456
+ const upgrade: WebUpgradeRoute = {
457
+ path: SSH_API.terminal,
458
+ handler: (req, socket, head) => {
459
+ if (!isLoopbackRequest(req)) {
460
+ socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n')
461
+ socket.destroy()
462
+ return
463
+ }
464
+ const url = new URL(req.url ?? '/', 'http://localhost')
465
+ const alias = queryParam(url, 'alias')
466
+ const sessionId = queryParam(url, 'session')
467
+ if (alias === undefined && sessionId === undefined) {
468
+ socket.write('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n')
469
+ socket.destroy()
470
+ return
471
+ }
472
+ const cols = Number.parseInt(queryParam(url, 'cols') ?? '80', 10)
473
+ const rows = Number.parseInt(queryParam(url, 'rows') ?? '24', 10)
474
+ const size = {
475
+ cols: Number.isFinite(cols) ? cols : 80,
476
+ rows: Number.isFinite(rows) ? rows : 24,
477
+ }
478
+ terminalWss.handleUpgrade(req, socket, head, (ws) => {
479
+ if (sessionId !== undefined) {
480
+ if (terminalSessions.attach(ws, sessionId, size)) return
481
+ // The session was reaped or the host restarted: tell the view so it
482
+ // can fall back to a fresh connect instead of sitting blank.
483
+ const expired: TerminalServerFrame = { type: 'exit', code: null, error: 'terminal session expired' }
484
+ try { ws.send(JSON.stringify(expired)) } catch { /* socket raced away */ }
485
+ try { ws.close(1000) } catch { /* already closed */ }
486
+ return
487
+ }
488
+ void terminalSessions.open(ws, alias as string, size)
489
+ })
490
+ },
491
+ }
492
+
493
+ return { routes, upgrade, terminalSessions }
494
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Minimal `~/.ssh/config` reader for the one-shot host import: Host blocks with
3
+ * `Include` expansion and explicit skip reasons. Values stay raw strings; the
4
+ * store maps them onto a HostPayload.
5
+ *
6
+ * Deliberate simplifications (documented in the package README):
7
+ * - `Match` blocks are skipped — their options are conditional and must never
8
+ * merge into the Host block above them.
9
+ * - A multi-pattern `Host a b` line only exposes its first pattern.
10
+ * - Include pathnames accept `~`, globs, and several whitespace-separated
11
+ * pathnames, but not environment variables, `%` tokens, or quoting.
12
+ * - Relative Include pathnames resolve against the directory of the config
13
+ * file the import started from (OpenSSH: `~/.ssh` for a user config).
14
+ * - A file that already contributed lines is never read twice, which doubles
15
+ * as the Include cycle guard.
16
+ */
17
+
18
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'
19
+ import { homedir } from 'node:os'
20
+ import { dirname, isAbsolute, join } from 'node:path'
21
+ import type { ImportSkipBlock } from './protocol.ts'
22
+
23
+ /** One parsed Host block. */
24
+ export interface SshBlock {
25
+ /** Raw Host line value (may hold several whitespace-separated patterns). */
26
+ pattern: string
27
+ /** Lowercased option key/value pairs; the last occurrence of a key wins. */
28
+ props: Record<string, string>
29
+ }
30
+
31
+ /** One config file read, with every Include expanded in place. */
32
+ export interface SshConfigRead {
33
+ blocks: SshBlock[]
34
+ skipped: ImportSkipBlock[]
35
+ }
36
+
37
+ /** Include recursion guard: a cycle or a runaway chain stops here. */
38
+ const MAX_INCLUDE_DEPTH = 16
39
+
40
+ /** The only line shape ssh_config knows: `Keyword value...` (case-insensitive). */
41
+ const LINE_RE = /^([A-Za-z0-9_-]+)\s+(.+)$/
42
+
43
+ /** Expand a leading `~` the way OpenSSH does for user configuration files. */
44
+ function expandTilde(path: string): string {
45
+ if (path === '~') return homedir()
46
+ if (path.startsWith('~/')) return join(homedir(), path.slice(2))
47
+ return path
48
+ }
49
+
50
+ /** Turn one glob segment into a matcher (`*` and `?` only). */
51
+ function segmentMatcher(segment: string): RegExp {
52
+ const escaped = segment.replace(/[.+^${}()|[\]\\]/g, '\\$&')
53
+ return new RegExp('^' + escaped.replace(/\*/g, '.*').replace(/\?/g, '.') + '$')
54
+ }
55
+
56
+ /**
57
+ * Expand a segment list against the filesystem. Wildcards match whole segments
58
+ * only; matches are sorted so a glob import stays deterministic.
59
+ */
60
+ function globSegments(prefix: string, segments: string[]): string[] {
61
+ const [head, ...rest] = segments
62
+ if (head === undefined) return [prefix]
63
+ if (!/[*?]/.test(head)) return globSegments(join(prefix, head), rest)
64
+ let names: string[]
65
+ try {
66
+ names = readdirSync(prefix)
67
+ } catch {
68
+ return []
69
+ }
70
+ const matcher = segmentMatcher(head)
71
+ return names.filter(name => matcher.test(name)).sort().flatMap(name => globSegments(join(prefix, name), rest))
72
+ }
73
+
74
+ /** Resolve one Include pathname into the existing regular files it names. */
75
+ function resolveInclude(spec: string, baseDir: string): string[] {
76
+ const expanded = expandTilde(spec)
77
+ const full = isAbsolute(expanded) ? expanded : join(baseDir, expanded)
78
+ if (!/[*?]/.test(full)) return existsSync(full) ? [full] : []
79
+ const root = /^([A-Za-z]:[\\/]|[\\/])/.exec(full)?.[1] ?? ''
80
+ const segments = full.slice(root.length).split(/[\\/]+/).filter(part => part !== '')
81
+ const files = globSegments(root === '' ? '.' : root, segments)
82
+ return files.filter(path => {
83
+ try {
84
+ return statSync(path).isFile()
85
+ } catch {
86
+ return false
87
+ }
88
+ })
89
+ }
90
+
91
+ /** Read one file into lines, splicing every `Include` in place. */
92
+ function readLines(file: string, baseDir: string, visited: Set<string>, depth: number): string[] {
93
+ if (depth > MAX_INCLUDE_DEPTH) return []
94
+ let key: string
95
+ try {
96
+ key = realpathSync(file)
97
+ } catch {
98
+ return []
99
+ }
100
+ if (visited.has(key)) return []
101
+ visited.add(key)
102
+ let text: string
103
+ try {
104
+ text = readFileSync(key, 'utf8')
105
+ } catch {
106
+ return []
107
+ }
108
+ const out: string[] = []
109
+ for (const raw of text.split(/\r?\n/)) {
110
+ const match = LINE_RE.exec(raw.trim())
111
+ if (match === null || match[1].toLowerCase() !== 'include') {
112
+ out.push(raw)
113
+ continue
114
+ }
115
+ for (const spec of match[2].trim().split(/\s+/).filter(part => part !== '')) {
116
+ for (const included of resolveInclude(spec, baseDir)) {
117
+ out.push(...readLines(included, baseDir, visited, depth + 1))
118
+ }
119
+ }
120
+ }
121
+ return out
122
+ }
123
+
124
+ /**
125
+ * Parse one ssh_config file (Include expanded) into Host blocks plus the
126
+ * `Match` blocks that were deliberately skipped.
127
+ */
128
+ export function readSshConfigBlocks(configPath: string): SshConfigRead {
129
+ const blocks: SshBlock[] = []
130
+ const skipped: ImportSkipBlock[] = []
131
+ const lines = readLines(configPath, dirname(configPath), new Set<string>(), 0)
132
+ let current: SshBlock | undefined
133
+ for (const raw of lines) {
134
+ const match = LINE_RE.exec(raw.trim())
135
+ if (match === null) continue
136
+ const key = match[1].toLowerCase()
137
+ const value = match[2].trim()
138
+ if (key === 'host') {
139
+ current = { pattern: value, props: {} }
140
+ blocks.push(current)
141
+ continue
142
+ }
143
+ if (key === 'match') {
144
+ // Everything below a Match line is conditional; attributing it to the
145
+ // Host block above would import a wrong HostName / ProxyCommand.
146
+ skipped.push({ name: 'Match ' + value, reason: 'match' })
147
+ current = undefined
148
+ continue
149
+ }
150
+ if (current !== undefined) current.props[key] = value
151
+ }
152
+ return { blocks, skipped }
153
+ }