dsh-ssh-hub 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +271 -2
  3. package/cordis.patch.yml +16 -0
  4. package/icon.svg +3 -0
  5. package/lib/client.js +13975 -0
  6. package/lib/index.js +6908 -0
  7. package/lib/types/activity/history.d.ts +50 -0
  8. package/lib/types/alerting/notify.d.ts +89 -0
  9. package/lib/types/alerting/prompt-summary.d.ts +28 -0
  10. package/lib/types/alerting/rules.d.ts +135 -0
  11. package/lib/types/alerting/tools.d.ts +30 -0
  12. package/lib/types/audit/audit-log.d.ts +84 -0
  13. package/lib/types/audit/recorder.d.ts +50 -0
  14. package/lib/types/client/api.d.ts +222 -0
  15. package/lib/types/client/index.d.ts +45 -0
  16. package/lib/types/client/locales.d.ts +319 -0
  17. package/lib/types/client/native-panel.d.ts +70 -0
  18. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  19. package/lib/types/client/panel/DeployTab.d.ts +10 -0
  20. package/lib/types/client/panel/FleetTab.d.ts +10 -0
  21. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  22. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  23. package/lib/types/client/panel/LogsTab.d.ts +10 -0
  24. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  25. package/lib/types/client/panel/TerminalTab.d.ts +27 -0
  26. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  27. package/lib/types/client/panel/TunnelEditDialog.d.ts +15 -0
  28. package/lib/types/client/panel/TunnelsTab.d.ts +27 -0
  29. package/lib/types/client/panel/controller.d.ts +253 -0
  30. package/lib/types/client/panel/helpers.d.ts +45 -0
  31. package/lib/types/client/panel/tabs.d.ts +62 -0
  32. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  33. package/lib/types/client/settings-binding.d.ts +71 -0
  34. package/lib/types/deploy/orchestrator.d.ts +158 -0
  35. package/lib/types/deploy/tools.d.ts +14 -0
  36. package/lib/types/dsh-home.d.ts +16 -0
  37. package/lib/types/engine/cluster.d.ts +19 -0
  38. package/lib/types/engine/connection-pool.d.ts +183 -0
  39. package/lib/types/engine/proxy-command.d.ts +36 -0
  40. package/lib/types/engine/pty.d.ts +32 -0
  41. package/lib/types/engine/sftp.d.ts +20 -0
  42. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  43. package/lib/types/engine/tunnel-discovery.d.ts +89 -0
  44. package/lib/types/engine/tunnel-remarks.d.ts +49 -0
  45. package/lib/types/engine/tunnel.d.ts +76 -0
  46. package/lib/types/engine.d.ts +103 -0
  47. package/lib/types/http.d.ts +59 -0
  48. package/lib/types/index.d.ts +128 -0
  49. package/lib/types/inspect/checks.d.ts +118 -0
  50. package/lib/types/inspect/inspection.d.ts +111 -0
  51. package/lib/types/inspect/tools.d.ts +50 -0
  52. package/lib/types/logs/search.d.ts +131 -0
  53. package/lib/types/logs/tools.d.ts +6 -0
  54. package/lib/types/loopback.d.ts +64 -0
  55. package/lib/types/monitor/loop.d.ts +133 -0
  56. package/lib/types/monitor/metrics.d.ts +151 -0
  57. package/lib/types/mount-once.d.ts +55 -0
  58. package/lib/types/protocol.d.ts +524 -0
  59. package/lib/types/routes.d.ts +82 -0
  60. package/lib/types/security/known-hosts.d.ts +153 -0
  61. package/lib/types/security/master-secret.d.ts +157 -0
  62. package/lib/types/security/redact.d.ts +44 -0
  63. package/lib/types/security/secrets.d.ts +70 -0
  64. package/lib/types/ssh-config.d.ts +42 -0
  65. package/lib/types/store.d.ts +183 -0
  66. package/lib/types/tool-surface.d.ts +72 -0
  67. package/lib/types/tools.d.ts +56 -0
  68. package/locale/en.json +6 -0
  69. package/locale/zh.json +6 -0
  70. package/package.json +126 -6
  71. package/src/activity/history.ts +117 -0
  72. package/src/alerting/notify.ts +212 -0
  73. package/src/alerting/prompt-summary.ts +71 -0
  74. package/src/alerting/rules.ts +281 -0
  75. package/src/alerting/tools.ts +263 -0
  76. package/src/audit/audit-log.ts +199 -0
  77. package/src/audit/recorder.ts +73 -0
  78. package/src/client/api.ts +782 -0
  79. package/src/client/css-modules.d.ts +5 -0
  80. package/src/client/index.ts +150 -0
  81. package/src/client/locales.ts +654 -0
  82. package/src/client/native-panel.tsx +141 -0
  83. package/src/client/panel/ClusterTab.tsx +141 -0
  84. package/src/client/panel/DeployTab.tsx +314 -0
  85. package/src/client/panel/FleetTab.tsx +494 -0
  86. package/src/client/panel/HostFormDialog.tsx +289 -0
  87. package/src/client/panel/HostsTab.tsx +395 -0
  88. package/src/client/panel/LogsTab.tsx +208 -0
  89. package/src/client/panel/SshPanel.tsx +105 -0
  90. package/src/client/panel/TerminalTab.tsx +550 -0
  91. package/src/client/panel/TransferTab.tsx +238 -0
  92. package/src/client/panel/TunnelEditDialog.tsx +174 -0
  93. package/src/client/panel/TunnelsTab.tsx +328 -0
  94. package/src/client/panel/controller.ts +507 -0
  95. package/src/client/panel/helpers.ts +84 -0
  96. package/src/client/panel/panel.module.css +1734 -0
  97. package/src/client/panel/tabs.ts +52 -0
  98. package/src/client/panel/xterm.css.ts +2 -0
  99. package/src/client/settings-binding.ts +184 -0
  100. package/src/deploy/orchestrator.ts +326 -0
  101. package/src/deploy/tools.ts +225 -0
  102. package/src/dsh-home.ts +42 -0
  103. package/src/engine/cluster.ts +60 -0
  104. package/src/engine/connection-pool.ts +721 -0
  105. package/src/engine/proxy-command.ts +248 -0
  106. package/src/engine/pty.ts +78 -0
  107. package/src/engine/sftp.ts +229 -0
  108. package/src/engine/terminal-sessions.ts +280 -0
  109. package/src/engine/tunnel-discovery.ts +353 -0
  110. package/src/engine/tunnel-remarks.ts +120 -0
  111. package/src/engine/tunnel.ts +300 -0
  112. package/src/engine.ts +195 -0
  113. package/src/http.ts +127 -0
  114. package/src/index.ts +690 -0
  115. package/src/inspect/checks.ts +251 -0
  116. package/src/inspect/inspection.ts +321 -0
  117. package/src/inspect/tools.ts +366 -0
  118. package/src/logs/search.ts +251 -0
  119. package/src/logs/tools.ts +160 -0
  120. package/src/loopback.ts +119 -0
  121. package/src/monitor/loop.ts +265 -0
  122. package/src/monitor/metrics.ts +333 -0
  123. package/src/mount-once.ts +142 -0
  124. package/src/protocol.ts +534 -0
  125. package/src/routes.ts +998 -0
  126. package/src/security/known-hosts.ts +342 -0
  127. package/src/security/master-secret.ts +334 -0
  128. package/src/security/redact.ts +119 -0
  129. package/src/security/secrets.ts +152 -0
  130. package/src/ssh-config.ts +182 -0
  131. package/src/store.ts +757 -0
  132. package/src/tool-surface.ts +96 -0
  133. package/src/tools.ts +550 -0
package/src/routes.ts ADDED
@@ -0,0 +1,998 @@
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 { 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 { discoverExternalTunnels } from './engine/tunnel-discovery.ts'
21
+ import { readTunnelRemarks, setTunnelRemark } from './engine/tunnel-remarks.ts'
22
+ import { readJsonBody, writeJson } from './http.ts'
23
+ import { isLoopbackRequest } from './loopback.ts'
24
+ import { SSH_API, type HostPayload, type TerminalServerFrame } from './protocol.ts'
25
+ import type { DeployRunRow, LogSearchRow, MasterSecretPayload, MasterSecretResult, DeployHostRow, LogHostRow } from './protocol.ts'
26
+ import type { ActivityHistory } from './activity/history.ts'
27
+ import type { HostStore } from './store.ts'
28
+ import type { Monitor } from './monitor/loop.ts'
29
+ import { TIERS, type MetricStore } from './monitor/metrics.ts'
30
+ import type { Inspector } from './inspect/inspection.ts'
31
+ import type { AlertEngine } from './alerting/rules.ts'
32
+ import type { AlertEvent } from './alerting/tools.ts'
33
+ import { deploy, type DeployPlan, type DeployResult } from './deploy/orchestrator.ts'
34
+ import { searchLogs, type LogSearchRequest, type LogSearchResult } from './logs/search.ts'
35
+
36
+ /**
37
+ * Project a finished deployment into its history record.
38
+ *
39
+ * The panel needs one row per host with the step that failed, not the nested
40
+ * batch structure the orchestrator returns — a batch is an implementation
41
+ * detail of concurrency, while "which host broke and at which step" is the
42
+ * question an operator actually asks.
43
+ *
44
+ * @param result - the orchestrator's outcome.
45
+ * @param hostCount - how many hosts the run intended to reach.
46
+ * @returns the record to persist.
47
+ */
48
+ function deployRunFrom(result: DeployResult, hostCount: number): DeployRunRow {
49
+ const hosts: DeployHostRow[] = []
50
+ for (const batch of result.batches) {
51
+ for (const host of batch.results) {
52
+ hosts.push({
53
+ alias: host.alias,
54
+ ok: host.ok,
55
+ // `DeployHostResult` does not report per-step detail — it reports the
56
+ // last exit code and whether the health probe passed. So the record
57
+ // carries the same facts rather than inventing step names.
58
+ steps: [],
59
+ ...(host.healthy === undefined ? {} : { healthy: host.healthy }),
60
+ ...(host.rolledBack === undefined ? {} : { rolledBack: host.rolledBack }),
61
+ ...(host.error === undefined ? {} : { error: host.error }),
62
+ ...(host.exitCode === undefined || host.exitCode === null ? {} : { exitCode: host.exitCode }),
63
+ })
64
+ }
65
+ }
66
+ // Hosts skipped after an earlier failure have no result row; they still
67
+ // belong in the record, marked as not attempted.
68
+ for (const alias of result.skipped) {
69
+ if (hosts.some(row => row.alias === alias)) continue
70
+ hosts.push({ alias, ok: false, steps: [], error: 'skipped: an earlier batch failed' })
71
+ }
72
+ return {
73
+ id: `${result.planId}-${String(Date.now())}`,
74
+ planId: result.planId,
75
+ at: Date.now(),
76
+ batchSize: result.batches[0]?.aliases.length ?? hostCount,
77
+ hostCount,
78
+ ok: result.ok,
79
+ hosts,
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Project a finished log search into its history record.
85
+ * @param result - the search outcome.
86
+ * @param pattern - the pattern that was searched for.
87
+ * @param source - the log source that was read.
88
+ * @param targets - the hosts that were asked.
89
+ * @returns the record to persist.
90
+ */
91
+ function logSearchFrom(
92
+ result: LogSearchResult,
93
+ pattern: string,
94
+ source: string,
95
+ targets: string[],
96
+ ): LogSearchRow {
97
+ return {
98
+ at: Date.now(),
99
+ pattern,
100
+ source,
101
+ targets,
102
+ hosts: result.results.map(host => ({
103
+ alias: host.alias,
104
+ ok: host.ok,
105
+ lines: host.lines,
106
+ // The wire shape names the count `total`; the search layer reports it as
107
+ // `totalMatches`. Translating here keeps one name on the panel side.
108
+ total: host.totalMatches ?? host.lines.length,
109
+ truncated: host.truncated === true,
110
+ ...(host.error === undefined ? {} : { error: host.error }),
111
+ ...(host.durationMs === undefined ? {} : { durationMs: host.durationMs }),
112
+ })),
113
+ }
114
+ }
115
+
116
+ /** Cap on declared upload bodies (staged to disk before SFTP). */
117
+ const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024
118
+
119
+ /**
120
+ * One noServer WebSocket server for terminal upgrades: the browser half uses
121
+ * a standards-compliant WebSocket, so the host must speak real RFC 6455
122
+ * frames (the webserver hands us the raw upgraded socket).
123
+ */
124
+ const terminalWss = new WebSocketServer({ noServer: true })
125
+
126
+ /** URL query helper (first value, decoded). */
127
+ function queryParam(url: URL, name: string): string | undefined {
128
+ const value = url.searchParams.get(name)
129
+ return value === null ? undefined : value
130
+ }
131
+
132
+ /**
133
+ * Parse a `limit` query value into a bounded positive integer.
134
+ *
135
+ * A limit is a display concern, so a malformed or absent value falls back to
136
+ * the default instead of failing the request: a panel asking for history
137
+ * should get history, not a 400 about its own query string.
138
+ *
139
+ * @param raw - the raw query value, if any.
140
+ * @param fallback - the value to use when absent or unparsable.
141
+ * @param max - the hard ceiling.
142
+ * @returns a bounded limit.
143
+ */
144
+ function clampLimit(raw: string | undefined, fallback: number, max: number): number {
145
+ if (raw === undefined || raw === '') return fallback
146
+ const value = Number(raw)
147
+ if (!Number.isFinite(value) || value <= 0) return fallback
148
+ return Math.min(Math.floor(value), max)
149
+ }
150
+
151
+ /** Route family dependencies. */
152
+ export interface SshRoutesDeps {
153
+ /** The host store (CRUD). */
154
+ store: HostStore
155
+ /** The engine (ops). */
156
+ engine: SshEngine
157
+ /** The monitoring loop (status readout). */
158
+ monitor?: Monitor
159
+ /** The metric store (history readout). */
160
+ metrics?: MetricStore
161
+ /** The inspection history (rounds and diff). */
162
+ inspector?: Inspector
163
+ /** The alert engine (rule states). */
164
+ alerts?: AlertEngine
165
+ /** The alert event feed. */
166
+ alertEvents?: AlertEvent[]
167
+ /**
168
+ * Report the live security posture (encryption configured vs active).
169
+ *
170
+ * A callback rather than a value so the route always reads the current
171
+ * config: toggling encryptCredentials in settings must be reflected on the
172
+ * next request, not after a remount.
173
+ */
174
+ security?: () => {
175
+ encryptConfigured: boolean
176
+ secret: { available: boolean; source: 'env' | 'file' | 'none' }
177
+ hostKeyPolicy: string
178
+ auditEnabled: boolean
179
+ }
180
+ /** Temp dir for upload/download staging (tests inject a sandbox). */
181
+ stagingDir?: string
182
+ /** Upload byte cap override (tests); defaults to MAX_UPLOAD_BYTES. */
183
+ maxUploadBytes?: number
184
+ /** The key file the panel manages (for the status report). */
185
+ keyPath?: string
186
+ /** Aliases whose stored credentials are still plaintext. */
187
+ plaintext?: () => { aliases: string[] }
188
+ /**
189
+ * Store or clear the master secret. Mutating, so the route fences it
190
+ * exactly like any other write; the operation itself decides whether a
191
+ * rotation is required and refuses a change that would strand credentials.
192
+ */
193
+ setSecret?: (payload: MasterSecretPayload) => MasterSecretResult
194
+ /** Deployment history (recorded runs, newest first). */
195
+ deployHistory?: ActivityHistory<DeployRunRow>
196
+ /** Log-search history (recorded searches, newest first). */
197
+ logHistory?: ActivityHistory<LogSearchRow>
198
+ }
199
+
200
+ /**
201
+ * Build every /api/dsh-ssh route (exact paths) plus the terminal upgrade.
202
+ * @param deps - store, engine, staging dir.
203
+ * @returns routes and the upgrade route.
204
+ */
205
+ export function makeRoutes(deps: SshRoutesDeps): { routes: WebRoute[]; upgrade: WebUpgradeRoute; terminalSessions: TerminalSessionRegistry } {
206
+ const { store, engine } = deps
207
+ const staging = deps.stagingDir ?? join(tmpdir(), 'dsh-ssh-uploads')
208
+ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
209
+ // The upload route stages request bodies here; it must exist before the
210
+ // first request (a missing dir would hang the first upload forever).
211
+ // 0700 keeps in-flight transfers unreadable to other local users (the
212
+ // staged files below are 0600; downloads are pre-created 0600 as well).
213
+ mkdirSync(staging, { recursive: true, mode: 0o700 })
214
+
215
+ /** Guard helper: fence + method check. */
216
+ const guard = (req: IncomingMessage, res: ServerResponse, method: string): boolean => {
217
+ if (!isLoopbackRequest(req)) {
218
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
219
+ return false
220
+ }
221
+ if (req.method !== method) {
222
+ writeJson(res, 405, { error: `method not allowed: ${req.method}` })
223
+ return false
224
+ }
225
+ return true
226
+ }
227
+
228
+ const routes: WebRoute[] = [
229
+ // ---------------------------------------------------------- monitor
230
+ {
231
+ // The monitoring loop's own health. The panel's first question about a
232
+ // quiet fleet is "is anything watching it?", and this answers that
233
+ // without inferring it from an empty alert list.
234
+ kind: 'exact',
235
+ path: '/api/dsh-ssh/monitor',
236
+ handler: async (req, res) => {
237
+ if (!guard(req, res, 'GET')) return
238
+ if (deps.monitor === undefined) {
239
+ writeJson(res, 200, { enabled: false, running: false, reason: 'monitor not mounted' })
240
+ return
241
+ }
242
+ writeJson(res, 200, { enabled: true, ...deps.monitor.status() })
243
+ },
244
+ },
245
+ {
246
+ // Manual round trigger: the same path the timer takes, so the panel's
247
+ // "check now" cannot produce a different result than the loop.
248
+ kind: 'exact',
249
+ path: '/api/dsh-ssh/monitor/tick',
250
+ handler: async (req, res) => {
251
+ if (!guard(req, res, 'POST')) return
252
+ if (deps.monitor === undefined) {
253
+ writeJson(res, 200, { ran: false, reason: 'monitor not mounted' })
254
+ return
255
+ }
256
+ // A failure inside the round is reported, not swallowed into a bare
257
+ // 400: the webserver turns a thrown handler into an empty 400, which
258
+ // tells an operator nothing about what broke. A manual trigger is a
259
+ // diagnostic act, so it must say what happened.
260
+ let tick
261
+ try {
262
+ tick = await deps.monitor.tick()
263
+ } catch (error) {
264
+ writeJson(res, 500, { ran: false, error: error instanceof Error ? error.message : String(error) })
265
+ return
266
+ }
267
+ // A missing tick means the round did not run, and the reason matters:
268
+ // "no hosts" and "a round is already in flight" are different
269
+ // problems with different fixes, and reporting both as the latter
270
+ // sends the operator looking for a stuck round that does not exist.
271
+ if (tick === undefined) {
272
+ const last = deps.monitor.ticks.at(-1)
273
+ writeJson(res, 200, {
274
+ ran: false,
275
+ reason: last?.skippedBecause ?? '既没有需要巡检的主机,也没有正在进行的轮次',
276
+ })
277
+ return
278
+ }
279
+ writeJson(res, 200, { ...tick })
280
+ },
281
+ },
282
+ {
283
+ // The recent rounds, newest first, for the inspection history panel.
284
+ kind: 'exact',
285
+ path: '/api/dsh-ssh/inspection',
286
+ handler: async (req, res) => {
287
+ if (!guard(req, res, 'GET')) return
288
+ if (deps.inspector === undefined) {
289
+ writeJson(res, 200, { rounds: [] })
290
+ return
291
+ }
292
+ const url = new URL(req.url ?? '/', 'http://localhost')
293
+ const limit = Number(queryParam(url, 'limit') ?? '10')
294
+ const rounds = deps.inspector.read(Number.isFinite(limit) && limit > 0 ? Math.min(limit, 50) : 10)
295
+ // Newest first: the panel shows the latest round at the top.
296
+ writeJson(res, 200, { rounds: [...rounds].reverse() })
297
+ },
298
+ },
299
+ {
300
+ // The change set between the two most recent retained rounds.
301
+ kind: 'exact',
302
+ path: '/api/dsh-ssh/inspection/diff',
303
+ handler: async (req, res) => {
304
+ if (!guard(req, res, 'GET')) return
305
+ if (deps.inspector === undefined) {
306
+ writeJson(res, 200, { changes: [] })
307
+ return
308
+ }
309
+ writeJson(res, 200, { changes: deps.inspector.diff() })
310
+ },
311
+ },
312
+ {
313
+ // The alert states and the recent event feed.
314
+ kind: 'exact',
315
+ path: '/api/dsh-ssh/alerts',
316
+ handler: async (req, res) => {
317
+ if (!guard(req, res, 'GET')) return
318
+ writeJson(res, 200, {
319
+ states: deps.alerts?.list() ?? [],
320
+ events: (deps.alertEvents ?? []).slice(-50).reverse(),
321
+ })
322
+ },
323
+ },
324
+ {
325
+ // The security posture: whether credentials are actually encrypted,
326
+ // and why not when the switch is on but nothing is encrypted. That
327
+ // mismatch is the most confusing state this plugin can present, so it
328
+ // is reported directly rather than left to be inferred.
329
+ kind: 'exact',
330
+ path: '/api/dsh-ssh/security',
331
+ handler: async (req, res) => {
332
+ if (!guard(req, res, 'GET')) return
333
+ const status = deps.security?.()
334
+ writeJson(res, 200, {
335
+ ...(status ?? { encryptConfigured: false, secret: { available: false, source: 'none' } }),
336
+ // The plaintext list belongs with the posture, not in a separate
337
+ // call: "encryption is on" and "which entries are still readable
338
+ // without the key" are one question with one answer.
339
+ ...(deps.plaintext === undefined ? {} : { plaintextAliases: deps.plaintext().aliases }),
340
+ ...(deps.keyPath === undefined ? {} : { keyPath: deps.keyPath }),
341
+ })
342
+ },
343
+ },
344
+ {
345
+ // Store or clear the master secret. This is a WRITE, so it takes the
346
+ // loopback fence and the POST method like every other mutation. The
347
+ // response reports the resulting source and how many entries were
348
+ // re-encrypted, because a secret change that silently skipped rotation
349
+ // would lock the operator out of their own credentials.
350
+ kind: 'exact',
351
+ path: '/api/dsh-ssh/security/secret',
352
+ handler: async (req, res) => {
353
+ if (!guard(req, res, 'POST')) return
354
+ if (deps.setSecret === undefined) {
355
+ writeJson(res, 200, { ok: false, source: 'none', rotated: 0, error: 'secret management is not mounted' })
356
+ return
357
+ }
358
+ let payload: MasterSecretPayload
359
+ try {
360
+ payload = (await readJsonBody(req)) as MasterSecretPayload
361
+ } catch (error) {
362
+ writeJson(res, 400, { error: error instanceof Error ? error.message : 'invalid JSON body' })
363
+ return
364
+ }
365
+ if (payload.action !== 'set' && payload.action !== 'clear') {
366
+ writeJson(res, 400, { error: "action must be 'set' or 'clear'" })
367
+ return
368
+ }
369
+ try {
370
+ writeJson(res, 200, deps.setSecret(payload))
371
+ } catch (error) {
372
+ // A throw here would become an empty 400 from the webserver, which
373
+ // tells the operator nothing about which step failed.
374
+ writeJson(res, 500, { ok: false, source: 'none', rotated: 0, error: error instanceof Error ? error.message : String(error) })
375
+ }
376
+ },
377
+ },
378
+ {
379
+ // Recorded deployment runs. A rollout's outcome matters after the
380
+ // panel has moved on, so it is retained rather than shown once.
381
+ kind: 'exact',
382
+ path: '/api/dsh-ssh/deploy/history',
383
+ handler: async (req, res) => {
384
+ if (!guard(req, res, 'GET')) return
385
+ const url = new URL(req.url ?? '/', 'http://localhost')
386
+ const limit = clampLimit(queryParam(url, 'limit'), 20, 100)
387
+ writeJson(res, 200, { runs: deps.deployHistory?.read(limit) ?? [] })
388
+ },
389
+ },
390
+ {
391
+ // Recorded log searches, same reasoning as the deployment history.
392
+ kind: 'exact',
393
+ path: '/api/dsh-ssh/logs/history',
394
+ handler: async (req, res) => {
395
+ if (!guard(req, res, 'GET')) return
396
+ const url = new URL(req.url ?? '/', 'http://localhost')
397
+ const limit = clampLimit(queryParam(url, 'limit'), 20, 100)
398
+ writeJson(res, 200, { searches: deps.logHistory?.read(limit) ?? [] })
399
+ },
400
+ },
401
+ {
402
+ // A metric series for one host and tier.
403
+ kind: 'exact',
404
+ path: '/api/dsh-ssh/metrics',
405
+ handler: async (req, res) => {
406
+ if (!guard(req, res, 'GET')) return
407
+ if (deps.metrics === undefined) {
408
+ writeJson(res, 200, { series: [] })
409
+ return
410
+ }
411
+ const url = new URL(req.url ?? '/', 'http://localhost')
412
+ const alias = queryParam(url, 'alias')
413
+ if (alias === undefined || alias === '') {
414
+ writeJson(res, 400, { error: 'alias is required' })
415
+ return
416
+ }
417
+ const tierParam = queryParam(url, 'tier') ?? '1m'
418
+ const tier = TIERS.find(candidate => candidate.name === tierParam)
419
+ if (tier === undefined) {
420
+ writeJson(res, 400, { error: `unknown tier: ${tierParam} (expected raw|1m|15m|1h)` })
421
+ return
422
+ }
423
+ const metric = queryParam(url, 'metric')
424
+ const limitRaw = Number(queryParam(url, 'limit') ?? '120')
425
+ const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(limitRaw, 2000) : 120
426
+ writeJson(res, 200, {
427
+ alias,
428
+ tier: tier.name,
429
+ ...(metric !== undefined ? { metric } : {}),
430
+ series: deps.metrics.series(alias, tier.name, metric, limit),
431
+ })
432
+ },
433
+ },
434
+ {
435
+ // Run a deployment plan from the panel. A write with real consequences
436
+ // on remote machines, so: loopback fence, POST only, and the outcome is
437
+ // recorded into the history before it is returned.
438
+ kind: 'exact',
439
+ path: '/api/dsh-ssh/deploy',
440
+ handler: async (req, res) => {
441
+ if (!guard(req, res, 'POST')) return
442
+ let body: { plan?: DeployPlan; targets?: string[] }
443
+ try {
444
+ body = (await readJsonBody(req)) as { plan?: DeployPlan; targets?: string[] }
445
+ } catch (error) {
446
+ writeJson(res, 400, { error: error instanceof Error ? error.message : 'invalid JSON body' })
447
+ return
448
+ }
449
+ const plan = body.plan
450
+ if (plan === undefined || typeof plan.id !== 'string' || !Array.isArray(plan.steps) || plan.steps.length === 0) {
451
+ writeJson(res, 400, { error: 'plan.id and a non-empty plan.steps are required' })
452
+ return
453
+ }
454
+ // Every step needs a rollback command, or a failed batch cannot be
455
+ // undone; refuse such a plan here rather than discovering it mid-run.
456
+ const withoutRollback = plan.steps.filter(step => typeof step.rollbackCommand !== 'string' || step.rollbackCommand.trim() === '')
457
+ if (withoutRollback.length > 0) {
458
+ writeJson(res, 400, {
459
+ error: `every step needs a rollbackCommand; missing on: ${withoutRollback.map(step => step.name).join(', ')}`,
460
+ })
461
+ return
462
+ }
463
+ const targets = Array.isArray(body.targets) && body.targets.length > 0
464
+ ? body.targets.filter(alias => typeof alias === 'string' && alias !== '')
465
+ : store.list().map(entry => entry.alias)
466
+ if (targets.length === 0) {
467
+ writeJson(res, 400, { error: 'no hosts to deploy to' })
468
+ return
469
+ }
470
+ let result
471
+ try {
472
+ result = await deploy(engine, plan, targets)
473
+ } catch (error) {
474
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
475
+ return
476
+ }
477
+ const record = deployRunFrom(result, targets.length)
478
+ deps.deployHistory?.append(record)
479
+ writeJson(res, 200, { run: record, result })
480
+ },
481
+ },
482
+ {
483
+ // Cross-host log search. Read-only on the remote side, but it does run
484
+ // commands (journalctl / grep) on servers, so it stays fenced; and it is
485
+ // POST because the pattern and target set travel in the body.
486
+ kind: 'exact',
487
+ path: '/api/dsh-ssh/logs',
488
+ handler: async (req, res) => {
489
+ if (!guard(req, res, 'POST')) return
490
+ let body: { request?: LogSearchRequest; targets?: string[] }
491
+ try {
492
+ body = (await readJsonBody(req)) as { request?: LogSearchRequest; targets?: string[] }
493
+ } catch (error) {
494
+ writeJson(res, 400, { error: error instanceof Error ? error.message : 'invalid JSON body' })
495
+ return
496
+ }
497
+ const request = body.request
498
+ if (request === undefined || typeof request.pattern !== 'string' || request.pattern === '') {
499
+ writeJson(res, 400, { error: 'request.pattern is required' })
500
+ return
501
+ }
502
+ const targets = Array.isArray(body.targets) && body.targets.length > 0
503
+ ? body.targets.filter(alias => typeof alias === 'string' && alias !== '')
504
+ : store.list().map(entry => entry.alias)
505
+ let result
506
+ try {
507
+ result = await searchLogs(engine, request, targets)
508
+ } catch (error) {
509
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
510
+ return
511
+ }
512
+ const record = logSearchFrom(result, request.pattern, request.source ?? 'journal', targets)
513
+ deps.logHistory?.append(record)
514
+ writeJson(res, 200, { search: record })
515
+ },
516
+ },
517
+ // ------------------------------------------------------------ hosts
518
+ {
519
+ kind: 'exact',
520
+ path: SSH_API.hosts,
521
+ handler: async (req, res) => {
522
+ // One handler per path (the webserver keyed route registry rejects
523
+ // duplicate (kind, path)); dispatch by HTTP method here.
524
+ const method = req.method ?? 'GET'
525
+ if (!isLoopbackRequest(req)) {
526
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
527
+ return
528
+ }
529
+ const url = new URL(req.url ?? '/', 'http://localhost')
530
+ if (method === 'GET') {
531
+ writeJson(res, 200, { hosts: engine.list(queryParam(url, 'query')) })
532
+ return
533
+ }
534
+ if (method === 'POST') {
535
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
536
+ if (body === null) {
537
+ writeJson(res, 400, { error: 'invalid JSON body' })
538
+ return
539
+ }
540
+ try {
541
+ const entry = store.create(body as unknown as HostPayload)
542
+ writeJson(res, 201, { host: store.summarize(entry) })
543
+ } catch (error) {
544
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
545
+ }
546
+ return
547
+ }
548
+ if (method !== 'PATCH' && method !== 'DELETE') {
549
+ writeJson(res, 405, { error: `method not allowed: ${method}` })
550
+ return
551
+ }
552
+ const alias = queryParam(url, 'alias')
553
+ if (alias === undefined || alias === '') {
554
+ writeJson(res, 400, { error: 'alias query parameter is required' })
555
+ return
556
+ }
557
+ if (method === 'PATCH') {
558
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
559
+ if (body === null) {
560
+ writeJson(res, 400, { error: 'invalid JSON body' })
561
+ return
562
+ }
563
+ try {
564
+ const entry = store.update(alias, body as unknown as Partial<HostPayload>)
565
+ // Connection-relevant changes invalidate the pooled connection:
566
+ // without this the pool would keep running commands on the old
567
+ // host/credentials until the idle sweep (up to 30 min later).
568
+ // Agent forwarding belongs here too: it is fixed per connection
569
+ // (ssh2 negotiates it when the channel opens), so toggling it must
570
+ // reconnect or the new setting silently never takes effect.
571
+ const patch = body as Record<string, unknown>
572
+ if (['host', 'port', 'user', 'auth', 'proxyJump', 'proxyCommand', 'forwardAgent'].some(key => patch[key] !== undefined)) {
573
+ engine.dropAlias(alias)
574
+ }
575
+ writeJson(res, 200, { host: store.summarize(entry) })
576
+ } catch (error) {
577
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
578
+ }
579
+ return
580
+ }
581
+ if (method === 'DELETE') {
582
+ try {
583
+ engine.dropAlias(alias)
584
+ store.delete(alias)
585
+ // Metric history is keyed by alias alone, so it has to go with the
586
+ // host. Leaving it behind lets the next host to reuse this name
587
+ // inherit another machine's numbers, and those numbers look real.
588
+ deps.metrics?.forget(alias)
589
+ writeJson(res, 200, { ok: true })
590
+ } catch (error) {
591
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
592
+ }
593
+ return
594
+ }
595
+ writeJson(res, 405, { error: `method not allowed: ${method}` })
596
+ },
597
+ },
598
+ {
599
+ kind: 'exact',
600
+ path: SSH_API.importSshConfig,
601
+ handler: async (req, res) => {
602
+ if (!guard(req, res, 'POST')) return
603
+ try {
604
+ writeJson(res, 200, { result: store.importFromSshConfig() })
605
+ } catch (error) {
606
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
607
+ }
608
+ },
609
+ },
610
+ {
611
+ kind: 'exact',
612
+ path: SSH_API.localConfig,
613
+ handler: async (req, res) => {
614
+ if (!guard(req, res, 'GET')) return
615
+ try {
616
+ writeJson(res, 200, { hosts: store.listLocalConfigHosts() })
617
+ } catch (error) {
618
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
619
+ }
620
+ },
621
+ },
622
+ // ------------------------------------------------------------ ops
623
+ {
624
+ kind: 'exact',
625
+ path: SSH_API.test,
626
+ handler: async (req, res) => {
627
+ if (!guard(req, res, 'POST')) return
628
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
629
+ const alias = typeof body?.alias === 'string' ? body.alias : ''
630
+ if (alias === '') {
631
+ writeJson(res, 400, { error: 'alias is required' })
632
+ return
633
+ }
634
+ try {
635
+ writeJson(res, 200, { result: await engine.test(alias) })
636
+ } catch (error) {
637
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
638
+ }
639
+ },
640
+ },
641
+ {
642
+ kind: 'exact',
643
+ path: SSH_API.exec,
644
+ handler: async (req, res) => {
645
+ if (!guard(req, res, 'POST')) return
646
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
647
+ const alias = typeof body?.alias === 'string' ? body.alias : ''
648
+ const command = typeof body?.command === 'string' ? body.command : ''
649
+ if (alias === '' || command === '') {
650
+ writeJson(res, 400, { error: 'alias and command are required' })
651
+ return
652
+ }
653
+ const timeoutMs = typeof body?.timeoutMs === 'number' ? body.timeoutMs : undefined
654
+ try {
655
+ writeJson(res, 200, { result: await engine.exec(alias, command, timeoutMs) })
656
+ } catch (error) {
657
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
658
+ }
659
+ },
660
+ },
661
+ {
662
+ kind: 'exact',
663
+ path: SSH_API.cluster,
664
+ handler: async (req, res) => {
665
+ if (!guard(req, res, 'POST')) return
666
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
667
+ const command = typeof body?.command === 'string' ? body.command : ''
668
+ if (command === '') {
669
+ writeJson(res, 400, { error: 'command is required' })
670
+ return
671
+ }
672
+ const aliases = Array.isArray(body?.aliases) ? body.aliases.filter((x): x is string => typeof x === 'string') : undefined
673
+ const tags = Array.isArray(body?.tags) ? body.tags.filter((x): x is string => typeof x === 'string') : undefined
674
+ const environment = typeof body?.environment === 'string' ? body.environment : undefined
675
+ const timeoutMs = typeof body?.timeoutMs === 'number' ? body.timeoutMs : undefined
676
+ const maxWorkers = typeof body?.maxWorkers === 'number' ? body.maxWorkers : undefined
677
+ const hasAliases = aliases?.some(alias => alias.trim() !== '') === true
678
+ const hasEnvironment = typeof environment === 'string' && environment.trim() !== ''
679
+ const hasTags = tags?.some(tag => tag.trim() !== '') === true
680
+ if (!hasAliases && !hasEnvironment && !hasTags) {
681
+ writeJson(res, 400, { error: 'ssh_cluster requires aliases, environment, or tags to limit the target set' })
682
+ return
683
+ }
684
+ try {
685
+ writeJson(res, 200, { results: await engine.cluster({ command, aliases, environment, tags, timeoutMs, maxWorkers }) })
686
+ } catch (error) {
687
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
688
+ }
689
+ },
690
+ },
691
+ // ------------------------------------------------------------- ls
692
+ {
693
+ kind: 'exact',
694
+ path: SSH_API.ls,
695
+ handler: async (req, res) => {
696
+ if (!guard(req, res, 'GET')) return
697
+ const url = new URL(req.url ?? '/', 'http://localhost')
698
+ const alias = queryParam(url, 'alias')
699
+ const path = queryParam(url, 'path') ?? '/'
700
+ if (alias === undefined || alias === '') {
701
+ writeJson(res, 400, { error: 'alias query parameter is required' })
702
+ return
703
+ }
704
+ try {
705
+ writeJson(res, 200, { entries: await engine.ls(alias, path) })
706
+ } catch (error) {
707
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
708
+ }
709
+ },
710
+ },
711
+ // --------------------------------------------------------- tunnel
712
+ {
713
+ kind: 'exact',
714
+ path: SSH_API.tunnel,
715
+ handler: async (req, res) => {
716
+ if (!guard(req, res, 'POST')) return
717
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
718
+ const action = typeof body?.action === 'string' ? body.action : ''
719
+ if (action === 'list') {
720
+ const managed = engine.listTunnels()
721
+ // Forwards started outside this plugin (`ssh -N -L …`) are real and
722
+ // were invisible: the tab only knew what it had created itself.
723
+ const external = await discoverExternalTunnels(managed, readTunnelRemarks())
724
+ writeJson(res, 200, { tunnels: [...managed, ...external] })
725
+ return
726
+ }
727
+ if (action === 'start') {
728
+ const alias = typeof body?.alias === 'string' ? body.alias : ''
729
+ const remotePort = typeof body?.remotePort === 'number' ? body.remotePort : undefined
730
+ if (alias === '' || remotePort === undefined) {
731
+ writeJson(res, 400, { error: 'alias and remotePort are required' })
732
+ return
733
+ }
734
+ try {
735
+ const tunnel = await engine.startTunnel(alias, {
736
+ remotePort,
737
+ remoteHost: typeof body?.remoteHost === 'string' && body.remoteHost !== '' ? body.remoteHost : undefined,
738
+ localPort: typeof body?.localPort === 'number' ? body.localPort : undefined,
739
+ name: typeof body?.name === 'string' && body.name.trim() !== '' ? body.name.trim() : undefined,
740
+ description: typeof body?.description === 'string' && body.description.trim() !== '' ? body.description.trim() : undefined,
741
+ })
742
+ writeJson(res, 200, { tunnel })
743
+ } catch (error) {
744
+ writeJson(res, 500, { error: error instanceof Error ? error.message : String(error) })
745
+ }
746
+ return
747
+ }
748
+ if (action === 'stop') {
749
+ const id = typeof body?.tunnelId === 'string' ? body.tunnelId : ''
750
+ if (id === '') {
751
+ writeJson(res, 400, { error: 'tunnelId is required' })
752
+ return
753
+ }
754
+ writeJson(res, 200, { ok: engine.stopTunnel(id) })
755
+ return
756
+ }
757
+ // Editing a tunnel this plugin owns: name/remark change in place, a
758
+ // routing change rebuilds the forward (and says so in `restarted`).
759
+ if (action === 'update') {
760
+ const id = typeof body?.tunnelId === 'string' ? body.tunnelId : ''
761
+ if (id === '') {
762
+ writeJson(res, 400, { error: 'tunnelId is required' })
763
+ return
764
+ }
765
+ try {
766
+ const result = await engine.updateTunnel(id, {
767
+ // Present means "set this value"; an empty string is the explicit
768
+ // clear, which the engine turns into "fall back to forwards.conf".
769
+ name: typeof body?.name === 'string' ? body.name : undefined,
770
+ description: typeof body?.description === 'string' ? body.description : undefined,
771
+ remoteHost: typeof body?.remoteHost === 'string' && body.remoteHost.trim() !== '' ? body.remoteHost.trim() : undefined,
772
+ remotePort: typeof body?.remotePort === 'number' ? body.remotePort : undefined,
773
+ localPort: typeof body?.localPort === 'number' ? body.localPort : undefined,
774
+ })
775
+ writeJson(res, 200, result)
776
+ } catch (error) {
777
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
778
+ }
779
+ return
780
+ }
781
+ // Editing a tunnel another process owns: only the name/remark can be
782
+ // changed, because the forward itself belongs to a process we must not
783
+ // touch. The remark persists by local port so it survives a restart.
784
+ if (action === 'remark') {
785
+ const localPort = typeof body?.localPort === 'number' ? body.localPort : undefined
786
+ if (localPort === undefined || !Number.isInteger(localPort) || localPort < 1 || localPort > 65535) {
787
+ writeJson(res, 400, { error: 'localPort must be an integer in 1..65535' })
788
+ return
789
+ }
790
+ try {
791
+ const stored = setTunnelRemark(localPort, {
792
+ name: typeof body?.name === 'string' ? body.name : undefined,
793
+ description: typeof body?.description === 'string' ? body.description : undefined,
794
+ })
795
+ writeJson(res, 200, { ok: true, remark: stored ?? null })
796
+ } catch (error) {
797
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
798
+ }
799
+ return
800
+ }
801
+ if (action === 'stop-all') {
802
+ const alias = typeof body?.alias === 'string' ? body.alias : undefined
803
+ writeJson(res, 200, { stopped: engine.stopAllTunnels(alias === '' ? undefined : alias) })
804
+ return
805
+ }
806
+ writeJson(res, 400, { error: `unknown action '${action}'` })
807
+ },
808
+ },
809
+ // --------------------------------------------------------- upload
810
+ {
811
+ kind: 'exact',
812
+ path: SSH_API.upload,
813
+ handler: async (req, res) => {
814
+ if (!guard(req, res, 'POST')) return
815
+ const url = new URL(req.url ?? '/', 'http://localhost')
816
+ const alias = queryParam(url, 'alias')
817
+ const remotePath = queryParam(url, 'remotePath')
818
+ if (alias === undefined || remotePath === undefined) {
819
+ writeJson(res, 400, { error: 'alias and remotePath query parameters are required' })
820
+ return
821
+ }
822
+ const declared = Number(req.headers['content-length'])
823
+ if (Number.isFinite(declared) && declared > maxUploadBytes) {
824
+ writeJson(res, 413, { error: 'upload body too large' })
825
+ return
826
+ }
827
+ res.writeHead(200, {
828
+ 'content-type': 'application/x-ndjson; charset=utf-8',
829
+ 'cache-control': 'no-cache',
830
+ 'referrer-policy': 'no-referrer',
831
+ })
832
+ const emit = (line: unknown): void => {
833
+ try { res.write(JSON.stringify(line) + '\n') } catch { /* client gone */ }
834
+ }
835
+ // Stage the uploaded bytes, then SFTP them out with progress frames.
836
+ const tmp = join(staging, `upload-${randomBytes(6).toString('hex')}`)
837
+ const sink = createWriteStream(tmp, { mode: 0o600 })
838
+ let settled = false
839
+ // End the response only after the tmp file is gone, and unlink only
840
+ // after the sink is fully closed: destroying a WriteStream whose
841
+ // fs.open is still pending lets the open RE-CREATE the file after
842
+ // an early unlink, leaving staging populated (this raced the
843
+ // response end and made the byte-cap test flaky).
844
+ const cleanup = (): void => {
845
+ void unlink(tmp).catch(() => undefined).finally(() => {
846
+ try { res.end() } catch { /* closed */ }
847
+ })
848
+ }
849
+ // Every terminal path (sink error, client abort, response loss) must
850
+ // emit a result frame, end the response, and remove the tmp file.
851
+ const fail = (error: unknown): void => {
852
+ if (settled) return
853
+ settled = true
854
+ emit({ type: 'result', ok: false, error: error instanceof Error ? error.message : String(error) })
855
+ if (sink.destroyed) {
856
+ cleanup()
857
+ } else {
858
+ sink.once('close', cleanup)
859
+ try { sink.destroy() } catch { cleanup() }
860
+ }
861
+ }
862
+ const done = (): void => {
863
+ if (settled) return
864
+ settled = true
865
+ try { res.end() } catch { /* closed */ }
866
+ }
867
+ sink.on('error', (error) => fail(error))
868
+ req.on('error', (error) => fail(error))
869
+ req.on('aborted', () => fail('upload aborted by the client'))
870
+ res.on('error', () => fail('response stream closed'))
871
+ res.on('close', () => { if (!res.writableEnded) fail('connection closed') })
872
+ // The content-length pre-check above can be bypassed by chunked or
873
+ // header-less requests: count the bytes as they actually arrive and
874
+ // abort the moment the cap is exceeded.
875
+ let received = 0
876
+ let capped = false
877
+ req.on('data', (chunk: Buffer) => {
878
+ received += chunk.byteLength
879
+ if (received > maxUploadBytes && !capped) {
880
+ capped = true
881
+ fail('upload body too large')
882
+ // Keep the socket alive until the response flush finishes:
883
+ // destroying the request here races res.end() and the client
884
+ // sees a hang-up instead of the result frame. Drain the rest of
885
+ // the body so the socket can close cleanly afterwards.
886
+ res.on('finish', () => { try { req.destroy() } catch { /* closed */ } })
887
+ req.resume()
888
+ }
889
+ })
890
+ req.pipe(sink)
891
+ sink.on('finish', async () => {
892
+ if (settled) return
893
+ emit({ type: 'progress', progress: { phase: 'connecting', file: remotePath, transferred: 0, total: 0, percent: 0 } })
894
+ try {
895
+ const outcome = await engine.upload(alias, tmp, remotePath, false, progress => emit({ type: 'progress', progress }))
896
+ emit({ type: 'result', ok: true, transferredBytes: outcome.bytes })
897
+ } catch (error) {
898
+ emit({ type: 'result', ok: false, error: error instanceof Error ? error.message : String(error) })
899
+ } finally {
900
+ await unlink(tmp).catch(() => undefined)
901
+ done()
902
+ }
903
+ })
904
+ },
905
+ },
906
+ // ------------------------------------------------------- download
907
+ {
908
+ kind: 'exact',
909
+ path: SSH_API.download,
910
+ handler: async (req, res) => {
911
+ if (!guard(req, res, 'GET')) return
912
+ const url = new URL(req.url ?? '/', 'http://localhost')
913
+ const alias = queryParam(url, 'alias')
914
+ const remotePath = queryParam(url, 'remotePath')
915
+ if (alias === undefined || remotePath === undefined) {
916
+ writeJson(res, 400, { error: 'alias and remotePath query parameters are required' })
917
+ return
918
+ }
919
+ const tmp = join(staging, `download-${randomBytes(6).toString('hex')}`)
920
+ try {
921
+ // Pre-create with 0600: ssh2's fastGet opens the destination with
922
+ // umask-default permissions and a pre-created file keeps the mode.
923
+ closeSync(openSync(tmp, 'w', 0o600))
924
+ const outcome = await engine.download(alias, remotePath, tmp)
925
+ res.writeHead(200, {
926
+ 'content-type': 'application/octet-stream',
927
+ 'content-length': String(outcome.bytes),
928
+ 'content-disposition': `attachment; filename="${basename(remotePath).replace(/"/g, '')}"`,
929
+ 'referrer-policy': 'no-referrer',
930
+ })
931
+ await new Promise<void>((resolve, reject) => {
932
+ const source = createReadStream(tmp)
933
+ source.on('error', reject)
934
+ res.on('error', reject)
935
+ source.pipe(res)
936
+ source.on('end', resolve)
937
+ })
938
+ } catch (error) {
939
+ if (!res.headersSent) {
940
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
941
+ } else {
942
+ // Mid-stream failure after headers: destroy so the browser does
943
+ // not hang waiting for the promised content-length bytes.
944
+ res.destroy()
945
+ }
946
+ } finally {
947
+ await unlink(tmp).catch(() => undefined)
948
+ }
949
+ },
950
+ },
951
+ ]
952
+
953
+ // ---------------------------------------------- terminal (upgrade)
954
+ // The shell outlives the view that opened it: a session is created once and
955
+ // any later socket attaches by id, so a panel switch or a dropped socket
956
+ // does not tear the remote shell down (engine/terminal-sessions.ts).
957
+ const terminalSessions = new TerminalSessionRegistry({
958
+ openShell: (alias, size, onKeyboardInteractive) => engine.openShell(alias, size, onKeyboardInteractive),
959
+ })
960
+ const upgrade: WebUpgradeRoute = {
961
+ path: SSH_API.terminal,
962
+ handler: (req, socket, head) => {
963
+ if (!isLoopbackRequest(req)) {
964
+ socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n')
965
+ socket.destroy()
966
+ return
967
+ }
968
+ const url = new URL(req.url ?? '/', 'http://localhost')
969
+ const alias = queryParam(url, 'alias')
970
+ const sessionId = queryParam(url, 'session')
971
+ if (alias === undefined && sessionId === undefined) {
972
+ socket.write('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n')
973
+ socket.destroy()
974
+ return
975
+ }
976
+ const cols = Number.parseInt(queryParam(url, 'cols') ?? '80', 10)
977
+ const rows = Number.parseInt(queryParam(url, 'rows') ?? '24', 10)
978
+ const size = {
979
+ cols: Number.isFinite(cols) ? cols : 80,
980
+ rows: Number.isFinite(rows) ? rows : 24,
981
+ }
982
+ terminalWss.handleUpgrade(req, socket, head, (ws) => {
983
+ if (sessionId !== undefined) {
984
+ if (terminalSessions.attach(ws, sessionId, size)) return
985
+ // The session was reaped or the host restarted: tell the view so it
986
+ // can fall back to a fresh connect instead of sitting blank.
987
+ const expired: TerminalServerFrame = { type: 'exit', code: null, error: 'terminal session expired' }
988
+ try { ws.send(JSON.stringify(expired)) } catch { /* socket raced away */ }
989
+ try { ws.close(1000) } catch { /* already closed */ }
990
+ return
991
+ }
992
+ void terminalSessions.open(ws, alias as string, size)
993
+ })
994
+ },
995
+ }
996
+
997
+ return { routes, upgrade, terminalSessions }
998
+ }