@linxin666/dsh-ssh 0.4.19 → 0.4.21

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 (47) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +13 -2
  3. package/README.zh.md +13 -2
  4. package/lib/client.js +726 -109
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +1074 -352
  7. package/lib/types/client/api.d.ts +8 -4
  8. package/lib/types/client/locales.d.ts +27 -1
  9. package/lib/types/client/panel/HostFormDialog.d.ts +3 -3
  10. package/lib/types/client/panel/HostsTab.d.ts +3 -3
  11. package/lib/types/client/panel/KeysTab.d.ts +8 -0
  12. package/lib/types/client/panel/controller.d.ts +1 -1
  13. package/lib/types/connection-trust.d.ts +26 -0
  14. package/lib/types/engine/cluster.d.ts +7 -2
  15. package/lib/types/engine/connection-pool.d.ts +11 -2
  16. package/lib/types/engine/sftp.d.ts +5 -0
  17. package/lib/types/engine/terminal-sessions.d.ts +5 -3
  18. package/lib/types/index.d.ts +6 -5
  19. package/lib/types/protocol.d.ts +41 -0
  20. package/lib/types/routes.d.ts +3 -0
  21. package/lib/types/service.d.ts +148 -0
  22. package/lib/types/store.d.ts +16 -4
  23. package/package.json +1 -1
  24. package/src/client/api.ts +147 -58
  25. package/src/client/locales.ts +55 -2
  26. package/src/client/panel/HostFormDialog.tsx +76 -17
  27. package/src/client/panel/HostsTab.tsx +50 -25
  28. package/src/client/panel/KeysTab.tsx +192 -0
  29. package/src/client/panel/SshPanel.tsx +4 -1
  30. package/src/client/panel/TerminalTab.tsx +14 -9
  31. package/src/client/panel/TunnelsTab.tsx +24 -7
  32. package/src/client/panel/controller.ts +77 -12
  33. package/src/client/panel/helpers.ts +3 -2
  34. package/src/connection-trust.ts +70 -0
  35. package/src/engine/cluster.ts +45 -13
  36. package/src/engine/connection-pool.ts +279 -96
  37. package/src/engine/proxy-command.ts +27 -10
  38. package/src/engine/sftp.ts +69 -35
  39. package/src/engine/terminal-sessions.ts +110 -35
  40. package/src/engine/tunnel.ts +20 -2
  41. package/src/engine.ts +5 -8
  42. package/src/index.ts +113 -39
  43. package/src/protocol.ts +45 -0
  44. package/src/routes.ts +130 -23
  45. package/src/service.ts +158 -0
  46. package/src/store.ts +324 -104
  47. package/src/tools.ts +3 -5
package/src/index.ts CHANGED
@@ -2,10 +2,11 @@
2
2
  * dsh-ssh — host half. Mounts the SSH engine (persistent ssh2 connection
3
3
  * pool, exec / PTY shell / SFTP / tunnels / cluster), the /api/dsh-ssh route
4
4
  * family plus the terminal WebSocket upgrade, the agent tools (ssh_list,
5
- * ssh_exec, ssh_upload, ssh_download, ssh_tunnel, ssh_cluster), and a
6
- * system-prompt announcement. The browser half (./client) renders the host
7
- * manager and web terminal. Everything rides official NPM SDK packages —
8
- * no dsh source changes.
5
+ * ssh_exec, ssh_upload, ssh_download, ssh_tunnel, ssh_cluster), a
6
+ * system-prompt announcement, and the `dshSsh` cordis service a sibling plugin
7
+ * injects to reuse the host inventory and the connection pool. The browser half
8
+ * (./client) renders the host manager and web terminal. Everything rides
9
+ * official NPM SDK packages — no dsh source changes.
9
10
  */
10
11
 
11
12
  import type { Context, Fiber } from '@deepseek-ai/cordis'
@@ -16,9 +17,12 @@ import type {} from '@deepseek-ai/dsh-tools'
16
17
  import { SshEngine } from './engine.ts'
17
18
  import { DEFAULT_CONNECT_TIMEOUT_MS } from './engine/connection-pool.ts'
18
19
  import { makeRoutes } from './routes.ts'
20
+ import type { SshHostSummary } from './protocol.ts'
21
+ import { DSH_SSH_API_VERSION, DSH_SSH_SERVICE, type DshSshHost, type DshSshService } from './service.ts'
19
22
  import { HostStore } from './store.ts'
20
23
  import { sshClusterTool, sshDownloadTool, sshExecTool, sshListTool, sshTunnelTool, sshUploadTool } from './tools.ts'
21
24
  import { mountOnce } from './mount-once.ts'
25
+ import { captureConnection } from './connection-trust.ts'
22
26
  import { PLUGIN_TOOL_SECTION_ORDERS, visibleToolText } from './tool-surface.ts'
23
27
 
24
28
  /** Stable cordis plugin name. */
@@ -139,7 +143,48 @@ const SSH_TOOL_NAMES = ['ssh_list', 'ssh_exec', 'ssh_upload', 'ssh_download', 's
139
143
  export const SSH_GUIDANCE = '本机已安装 dsh-ssh 插件(DSH 远程 SSH 运维):侧边栏「SSH」入口;在 dsh-web 插件全家桶仓库(packages/dsh-ssh)统一维护。能力:主机配置存 $DSH_HOME/dsh-ssh.json(默认 ~/.dsh)(可从 ~/.ssh/config 导入);持久连接池复用长连接(空闲 30 分钟自动断开);ssh_list 列出主机、ssh_exec 执行远程命令、ssh_upload/ssh_download 传输文件、ssh_tunnel 本地端口转发(访问远程数据库/内网服务)、ssh_cluster 按 aliases/environment/tags 至少一种非空 selector 筛选后集群并发执行;支持密钥/密码/ssh-agent 认证、passphrase 密钥、ProxyJump 跳板机(别名或 [user@]host[:port] 地址)与 OpenSSH 语义的 ProxyCommand(跳过堡垒机客户端场景,只能由用户在 GUI 配置,agent 不可写);Web 终端走 WebSocket。限制:主机操作由用户在 GUI 中配置后 agent 方可使用;密码以明文存在用户主目录私有文件(权限 0600);命令输出原样返回、可能含敏感信息;断线重连可能重放非幂等命令;传输/执行消耗真实远程资源,先确认再操作。路径区分:本机(dsh host)上的文件与命令一律用本地工具(read / write / edit / bash),ssh_* 工具只针对远程主机上的路径。用户提到「SSH / 远程服务器 / 服务器操作 / 跳板机 / 隧道 / 部署 / 上传下载」时即指本插件,请据此协作。'
140
144
 
141
145
  /**
142
- * Mount the SSH engine, routes, tools, and announcement.
146
+ * Project one stored-host summary onto the service face.
147
+ *
148
+ * Everything the summary publishes is forwarded except the ProxyCommand text:
149
+ * the command is a shell line the host process executes with its own
150
+ * privileges, and a sibling plugin drives the host without ever needing it.
151
+ * @param summary - the plugin's own secret-free projection.
152
+ * @returns the same host as the service face reports it.
153
+ */
154
+ function toServiceHost(summary: SshHostSummary): DshSshHost {
155
+ const { proxyCommand: _proxyCommand, ...host } = summary
156
+ return host
157
+ }
158
+
159
+ /**
160
+ * Build the face a sibling plugin receives.
161
+ *
162
+ * Every member forwards to the engine instance this plugin already serves its
163
+ * routes, tools and panel from, so a consumer shares one host store and one
164
+ * connection pool with them instead of opening its own.
165
+ * @param engine - the plugin's engine for this apply.
166
+ * @returns the published service face.
167
+ */
168
+ function createService(engine: SshEngine): DshSshService {
169
+ return {
170
+ apiVersion: DSH_SSH_API_VERSION,
171
+ hosts: {
172
+ list: () => engine.list().map(toServiceHost),
173
+ find: (alias) => {
174
+ const summary = engine.find(alias)
175
+ return summary === undefined ? undefined : toServiceHost(summary)
176
+ },
177
+ },
178
+ exec: (alias, command, options) => engine.exec(alias, command, options?.timeoutMs, options?.signal),
179
+ // A single file: the face carries no recursive/streaming transfer, so a
180
+ // directory upload is refused by the engine rather than walked silently.
181
+ upload: (alias, localPath, remotePath) => engine.upload(alias, localPath, remotePath, false),
182
+ download: (alias, remotePath, localPath) => engine.download(alias, remotePath, localPath),
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Mount the SSH engine, routes, tools, the sibling-plugin service, and announcement.
143
188
  * @param ctx - host plugin context carrying webServer/tools/systemPrompt.
144
189
  * @param config - resolved plugin config (schema defaults applied by the loader).
145
190
  */
@@ -165,8 +210,12 @@ function applyImpl(ctx: Context, config?: ResolvedConfig): void {
165
210
  }
166
211
  }
167
212
 
213
+ // The connection bridge resolves authentication through its calling fiber;
214
+ // capture it in a scope that injects both halves before routes use it.
215
+ const connection = captureConnection(ctx, 'dsh-ssh: connection trust')
216
+
168
217
  // The /api/dsh-ssh route family + terminal upgrade.
169
- const { routes, upgrade, terminalSessions } = makeRoutes({ store, engine })
218
+ const { routes, upgrade, terminalSessions } = makeRoutes({ store, engine, connection })
170
219
  let disposeRoutes: (() => void) | undefined
171
220
 
172
221
  // Agent tools + their prompt sections.
@@ -183,29 +232,47 @@ function applyImpl(ctx: Context, config?: ResolvedConfig): void {
183
232
  // System-prompt announcement.
184
233
  let disposeSection: (() => void) | undefined
185
234
 
235
+ // The sibling-plugin service (`dshSsh`): published while the master switch
236
+ // is on, withdrawn with it. A hand-built context without a cordis registry
237
+ // provides no service store, and the plugin still serves its own surfaces.
238
+ let disposeService: (() => void) | undefined
239
+
186
240
  // Register (or drop) every surface to match the resolved config. Each group
187
- // is kept under one disposer: re-registering first tears the old one down
188
- // so duplicate-name registrations never throw.
241
+ // stays mounted while its own condition holds, so unrelated volatile edits
242
+ // (such as terminalFontFamily or connectTimeoutMs) never tear down routes
243
+ // and kill live terminal sessions.
189
244
  const sync = (): void => {
190
245
  // A settings edit reaches this instance without a remount; apply the
191
246
  // connection ceiling before re-deriving the surfaces so connections opened
192
247
  // by the request that follows use the new value.
193
248
  engine.setConnectTimeout(readConfigField(config?.connectTimeoutMs, DEFAULT_CONNECT_TIMEOUT_MS))
194
249
  const value = resolve()
195
- if (disposeSection !== undefined) {
250
+ const wantSection = value.enabled && value.announceToAgent
251
+ if (!wantSection && disposeSection !== undefined) {
196
252
  disposeSection()
197
253
  disposeSection = undefined
198
254
  }
199
- if (disposeRoutes !== undefined) {
200
- disposeRoutes()
201
- disposeRoutes = undefined
255
+ if (!value.enabled) {
256
+ if (disposeRoutes !== undefined) {
257
+ disposeRoutes()
258
+ disposeRoutes = undefined
259
+ }
260
+ if (disposeTools !== undefined) {
261
+ disposeTools()
262
+ disposeTools = undefined
263
+ }
264
+ // The service follows the master switch only: a settings edit that keeps
265
+ // the plugin on leaves the provision — and every dependent's inject scope —
266
+ // alone, so an unrelated field does not reboot consumers.
267
+ if (disposeService !== undefined) {
268
+ // Unproviding releases every dependent fiber that injected the service;
269
+ // each of those scopes unloads with it.
270
+ disposeService()
271
+ disposeService = undefined
272
+ }
273
+ return
202
274
  }
203
- if (disposeTools !== undefined) {
204
- disposeTools()
205
- disposeTools = undefined
206
- }
207
- if (!value.enabled) return
208
- if (value.announceToAgent) {
275
+ if (wantSection && disposeSection === undefined) {
209
276
  disposeSection = ctx.systemPrompt.section({
210
277
  name: 'plugin:dsh-ssh',
211
278
  order: SECTION_ORDER,
@@ -216,27 +283,34 @@ function applyImpl(ctx: Context, config?: ResolvedConfig): void {
216
283
  text: visibleToolText(ctx.tools, SSH_TOOL_NAMES, SSH_GUIDANCE),
217
284
  })
218
285
  }
219
- disposeRoutes = ctx.effect(
220
- () => {
221
- const disposers = routes.map(route => ctx.webServer.register(route))
222
- const upgradeDisposer = ctx.webServer.registerUpgrade(upgrade)
223
- return () => {
224
- for (const dispose of disposers) dispose()
225
- upgradeDisposer()
226
- // Dropping the routes also ends the terminal sessions they served:
227
- // a live shell must not outlive the surface that can reach it.
228
- terminalSessions.dispose()
229
- }
230
- },
231
- 'dsh-ssh: routes',
232
- )
233
- disposeTools = ctx.effect(
234
- () => {
235
- const disposers = tools.map(tool => ctx.tools.register(tool))
236
- return () => { for (const dispose of disposers) dispose() }
237
- },
238
- 'dsh-ssh: tools',
239
- )
286
+ if (disposeRoutes === undefined) {
287
+ disposeRoutes = ctx.effect(
288
+ () => {
289
+ const disposers = routes.map(route => ctx.webServer.register(route))
290
+ const upgradeDisposer = ctx.webServer.registerUpgrade(upgrade)
291
+ return () => {
292
+ for (const dispose of disposers) dispose()
293
+ upgradeDisposer()
294
+ // Dropping the routes also ends the terminal sessions they served:
295
+ // a live shell must not outlive the surface that can reach it.
296
+ terminalSessions.dispose()
297
+ }
298
+ },
299
+ 'dsh-ssh: routes',
300
+ )
301
+ }
302
+ if (disposeTools === undefined) {
303
+ disposeTools = ctx.effect(
304
+ () => {
305
+ const disposers = tools.map(tool => ctx.tools.register(tool))
306
+ return () => { for (const dispose of disposers) dispose() }
307
+ },
308
+ 'dsh-ssh: tools',
309
+ )
310
+ }
311
+ if (disposeService === undefined && typeof (ctx as { provide?: unknown }).provide === 'function') {
312
+ disposeService = ctx.provide(DSH_SSH_SERVICE, createService(engine))
313
+ }
240
314
  }
241
315
 
242
316
  // A settings edit is committed into this instance's config references and
package/src/protocol.ts CHANGED
@@ -86,6 +86,48 @@ export interface SshHostSummary {
86
86
  updatedAt: number
87
87
  }
88
88
 
89
+ /** Browser-only host projection: includes the key path needed for managed-key matching. */
90
+ export interface SshPanelHostSummary extends SshHostSummary {
91
+ /** Private-key path for key auth; never exposed through the agent/service summary. */
92
+ keyPath?: string
93
+ }
94
+
95
+ /** One managed private-key reference stored in dsh-ssh.json. */
96
+ export interface SshKeyEntry {
97
+ id: string
98
+ name: string
99
+ /** Absolute local path; key contents are never copied or read by the plugin. */
100
+ path: string
101
+ passphrase?: string
102
+ note?: string
103
+ createdAt: number
104
+ updatedAt: number
105
+ }
106
+
107
+ /** Secret-free managed-key projection for the browser. */
108
+ export interface SshKeySummary {
109
+ id: string
110
+ name: string
111
+ path: string
112
+ hasPassphrase: boolean
113
+ note?: string
114
+ /** Whether the local path currently exists (stat-only check). */
115
+ exists: boolean
116
+ /** Aliases whose stored auth.keyPath equals this key's path. */
117
+ usedBy: string[]
118
+ createdAt: number
119
+ updatedAt: number
120
+ }
121
+
122
+ /** Managed-key create/update payload; null passphrase explicitly clears it on update. */
123
+ export interface SshKeyPayload {
124
+ name?: string
125
+ path?: string
126
+ passphrase?: string | null
127
+ /** Empty string clears the note; omission preserves it on update. */
128
+ note?: string
129
+ }
130
+
89
131
  /** Result of one non-interactive command execution. */
90
132
  export interface ExecResult {
91
133
  success: boolean
@@ -162,6 +204,8 @@ export interface HostPayload {
162
204
  * stored secrets (the browser never receives them back).
163
205
  */
164
206
  auth?: SshHostEntry['auth']
207
+ /** Transient managed-key selection resolved Host-side; never persisted on the host row. */
208
+ managedKeyId?: string
165
209
  proxyJump?: string[]
166
210
  /**
167
211
  * ProxyCommand to store. An empty string or 'none' clears a stored value;
@@ -230,6 +274,7 @@ export const SSH_API_BASE = '/api/dsh-ssh' as const
230
274
 
231
275
  export const SSH_API = {
232
276
  hosts: SSH_API_BASE + '/hosts',
277
+ keys: SSH_API_BASE + '/keys',
233
278
  importSshConfig: SSH_API_BASE + '/hosts/import-ssh-config',
234
279
  test: SSH_API_BASE + '/test',
235
280
  exec: SSH_API_BASE + '/exec',
package/src/routes.ts CHANGED
@@ -15,11 +15,16 @@ import { tmpdir } from 'node:os'
15
15
  import { randomBytes } from 'node:crypto'
16
16
  import { WebSocketServer } from 'ws'
17
17
  import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
18
+
19
+ type AuthAwareWebRoute = WebRoute & { readonly auth: 'anonymous' }
20
+ type AuthAwareWebUpgradeRoute = WebUpgradeRoute & { readonly auth: 'anonymous' }
18
21
  import type { SshEngine } from './engine.ts'
22
+ import { hasClusterSelector } from './engine/cluster.ts'
19
23
  import { TerminalSessionRegistry } from './engine/terminal-sessions.ts'
20
24
  import { readJsonBody, writeJson } from './http.ts'
21
25
  import { isLoopbackRequest } from './loopback.ts'
22
- import { SSH_API, type HostPayload, type TerminalServerFrame } from './protocol.ts'
26
+ import { connectionAdmits, type HostConnectionReader } from './connection-trust.ts'
27
+ import { SSH_API, type HostPayload, type SshKeyPayload, type TerminalServerFrame } from './protocol.ts'
23
28
  import type { HostStore } from './store.ts'
24
29
 
25
30
  /** Cap on declared upload bodies (staged to disk before SFTP). */
@@ -38,12 +43,25 @@ function queryParam(url: URL, name: string): string | undefined {
38
43
  return value === null ? undefined : value
39
44
  }
40
45
 
46
+ /** Strip control characters, quotes, and backslashes from a Content-Disposition filename. */
47
+ function safeAttachmentFilename(raw: string): string {
48
+ let clean = ''
49
+ for (let i = 0; i < raw.length; i += 1) {
50
+ const code = raw.charCodeAt(i)
51
+ if (code < 0x20 || code === 0x7f || code === 0x22 || code === 0x5c) continue
52
+ clean += raw[i]!
53
+ }
54
+ return clean === '' ? 'download' : clean
55
+ }
56
+
41
57
  /** Route family dependencies. */
42
58
  export interface SshRoutesDeps {
43
59
  /** The host store (CRUD). */
44
60
  store: HostStore
45
61
  /** The engine (ops). */
46
62
  engine: SshEngine
63
+ /** Optional Host connection trust decision, read afresh for each request. */
64
+ connection?: HostConnectionReader
47
65
  /** Temp dir for upload/download staging (tests inject a sandbox). */
48
66
  stagingDir?: string
49
67
  /** Upload byte cap override (tests); defaults to MAX_UPLOAD_BYTES. */
@@ -65,9 +83,11 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
65
83
  // staged files below are 0600; downloads are pre-created 0600 as well).
66
84
  mkdirSync(staging, { recursive: true, mode: 0o700 })
67
85
 
68
- /** Guard helper: fence + method check. */
86
+ const allowed = (req: IncomingMessage): boolean => connectionAdmits(deps.connection?.(), req) || isLoopbackRequest(req)
87
+
88
+ /** Guard helper: Host connection trust or loopback fence + method check. */
69
89
  const guard = (req: IncomingMessage, res: ServerResponse, method: string): boolean => {
70
- if (!isLoopbackRequest(req)) {
90
+ if (!allowed(req)) {
71
91
  writeJson(res, 403, { error: 'forbidden: loopback-only' })
72
92
  return false
73
93
  }
@@ -87,13 +107,13 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
87
107
  // One handler per path (the webserver keyed route registry rejects
88
108
  // duplicate (kind, path)); dispatch by HTTP method here.
89
109
  const method = req.method ?? 'GET'
90
- if (!isLoopbackRequest(req)) {
110
+ if (!allowed(req)) {
91
111
  writeJson(res, 403, { error: 'forbidden: loopback-only' })
92
112
  return
93
113
  }
94
114
  const url = new URL(req.url ?? '/', 'http://localhost')
95
115
  if (method === 'GET') {
96
- writeJson(res, 200, { hosts: engine.list(queryParam(url, 'query')) })
116
+ writeJson(res, 200, { hosts: store.list(queryParam(url, 'query')).map(entry => store.summarizePanel(entry)) })
97
117
  return
98
118
  }
99
119
  if (method === 'POST') {
@@ -103,8 +123,8 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
103
123
  return
104
124
  }
105
125
  try {
106
- const entry = store.create(body as unknown as HostPayload)
107
- writeJson(res, 201, { host: store.summarize(entry) })
126
+ const entry = store.create(store.resolveManagedKey(body as unknown as HostPayload))
127
+ writeJson(res, 201, { host: store.summarizePanel(entry) })
108
128
  } catch (error) {
109
129
  writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
110
130
  }
@@ -126,18 +146,18 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
126
146
  return
127
147
  }
128
148
  try {
129
- const entry = store.update(alias, body as unknown as Partial<HostPayload>)
149
+ const resolved = store.resolveManagedKey(body as unknown as Partial<HostPayload>)
150
+ const entry = store.update(alias, resolved)
130
151
  // Connection-relevant changes invalidate the pooled connection:
131
152
  // without this the pool would keep running commands on the old
132
153
  // host/credentials until the idle sweep (up to 30 min later).
133
- // Agent forwarding belongs here too: it is fixed per connection
134
- // (ssh2 negotiates it when the channel opens), so toggling it must
135
- // reconnect or the new setting silently never takes effect.
136
- const patch = body as Record<string, unknown>
154
+ // Check the resolved patch so a managedKeyId-only update (which
155
+ // resolves into `resolved.auth`) invalidates the pool too.
156
+ const patch = resolved as Record<string, unknown>
137
157
  if (['host', 'port', 'user', 'auth', 'proxyJump', 'proxyCommand', 'forwardAgent'].some(key => patch[key] !== undefined)) {
138
158
  engine.dropAlias(alias)
139
159
  }
140
- writeJson(res, 200, { host: store.summarize(entry) })
160
+ writeJson(res, 200, { host: store.summarizePanel(entry) })
141
161
  } catch (error) {
142
162
  writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
143
163
  }
@@ -156,6 +176,63 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
156
176
  writeJson(res, 405, { error: `method not allowed: ${method}` })
157
177
  },
158
178
  },
179
+ {
180
+ kind: 'exact',
181
+ path: SSH_API.keys,
182
+ handler: async (req, res) => {
183
+ const method = req.method ?? 'GET'
184
+ if (!allowed(req)) {
185
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
186
+ return
187
+ }
188
+ if (method === 'GET') {
189
+ writeJson(res, 200, { keys: store.listKeys() })
190
+ return
191
+ }
192
+ const url = new URL(req.url ?? '/', 'http://localhost')
193
+ if (method === 'POST') {
194
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
195
+ if (body === null) {
196
+ writeJson(res, 400, { error: 'invalid JSON body' })
197
+ return
198
+ }
199
+ try {
200
+ writeJson(res, 201, { key: store.createKey(body as SshKeyPayload) })
201
+ } catch (error) {
202
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
203
+ }
204
+ return
205
+ }
206
+ if (method !== 'PATCH' && method !== 'DELETE') {
207
+ writeJson(res, 405, { error: `method not allowed: ${method}` })
208
+ return
209
+ }
210
+ const id = queryParam(url, 'id')
211
+ if (id === undefined || id === '') {
212
+ writeJson(res, 400, { error: 'id query parameter is required' })
213
+ return
214
+ }
215
+ if (method === 'DELETE') {
216
+ try {
217
+ store.deleteKey(id)
218
+ writeJson(res, 200, { ok: true })
219
+ } catch (error) {
220
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
221
+ }
222
+ return
223
+ }
224
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
225
+ if (body === null) {
226
+ writeJson(res, 400, { error: 'invalid JSON body' })
227
+ return
228
+ }
229
+ try {
230
+ writeJson(res, 200, { key: store.updateKey(id, body as SshKeyPayload) })
231
+ } catch (error) {
232
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
233
+ }
234
+ },
235
+ },
159
236
  {
160
237
  kind: 'exact',
161
238
  path: SSH_API.importSshConfig,
@@ -223,10 +300,7 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
223
300
  const environment = typeof body?.environment === 'string' ? body.environment : undefined
224
301
  const timeoutMs = typeof body?.timeoutMs === 'number' ? body.timeoutMs : undefined
225
302
  const maxWorkers = typeof body?.maxWorkers === 'number' ? body.maxWorkers : undefined
226
- const hasAliases = aliases?.some(alias => alias.trim() !== '') === true
227
- const hasEnvironment = typeof environment === 'string' && environment.trim() !== ''
228
- const hasTags = tags?.some(tag => tag.trim() !== '') === true
229
- if (!hasAliases && !hasEnvironment && !hasTags) {
303
+ if (!hasClusterSelector({ aliases, environment, tags })) {
230
304
  writeJson(res, 400, { error: 'ssh_cluster requires aliases, environment, or tags to limit the target set' })
231
305
  return
232
306
  }
@@ -331,6 +405,8 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
331
405
  const emit = (line: unknown): void => {
332
406
  try { res.write(JSON.stringify(line) + '\n') } catch { /* client gone */ }
333
407
  }
408
+ // Ensure the private staging directory still exists (e.g. after a /tmp sweep).
409
+ mkdirSync(staging, { recursive: true, mode: 0o700 })
334
410
  // Stage the uploaded bytes, then SFTP them out with progress frames.
335
411
  const tmp = join(staging, `upload-${randomBytes(6).toString('hex')}`)
336
412
  const sink = createWriteStream(tmp, { mode: 0o600 })
@@ -417,22 +493,49 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
417
493
  }
418
494
  const tmp = join(staging, `download-${randomBytes(6).toString('hex')}`)
419
495
  try {
496
+ mkdirSync(staging, { recursive: true, mode: 0o700 })
420
497
  // Pre-create with 0600: ssh2's fastGet opens the destination with
421
498
  // umask-default permissions and a pre-created file keeps the mode.
422
499
  closeSync(openSync(tmp, 'w', 0o600))
423
500
  const outcome = await engine.download(alias, remotePath, tmp)
501
+ if (req.destroyed || res.destroyed) return
424
502
  res.writeHead(200, {
425
503
  'content-type': 'application/octet-stream',
426
504
  'content-length': String(outcome.bytes),
427
- 'content-disposition': `attachment; filename="${basename(remotePath).replace(/"/g, '')}"`,
505
+ 'content-disposition': `attachment; filename="${safeAttachmentFilename(basename(remotePath))}"`,
428
506
  'referrer-policy': 'no-referrer',
429
507
  })
430
508
  await new Promise<void>((resolve, reject) => {
431
509
  const source = createReadStream(tmp)
432
- source.on('error', reject)
433
- res.on('error', reject)
510
+ let settled = false
511
+ const finish = (err?: unknown): void => {
512
+ if (settled) return
513
+ settled = true
514
+ res.off('error', onResError)
515
+ res.off('close', onResClose)
516
+ if (err !== undefined) reject(err)
517
+ else resolve()
518
+ }
519
+ const abortSource = (err?: unknown): void => {
520
+ if (settled) return
521
+ if (source.closed) {
522
+ finish(err)
523
+ return
524
+ }
525
+ source.once('close', () => { finish(err) })
526
+ if (!source.destroyed) {
527
+ try { source.destroy() } catch { finish(err) }
528
+ }
529
+ }
530
+ const onResError = (err: Error): void => { abortSource(err) }
531
+ const onResClose = (): void => {
532
+ if (!res.writableEnded) abortSource()
533
+ }
534
+ source.on('error', (err) => { abortSource(err) })
535
+ source.on('close', () => { finish() })
536
+ res.on('error', onResError)
537
+ res.on('close', onResClose)
434
538
  source.pipe(res)
435
- source.on('end', resolve)
436
539
  })
437
540
  } catch (error) {
438
541
  if (!res.headersSent) {
@@ -459,7 +562,7 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
459
562
  const upgrade: WebUpgradeRoute = {
460
563
  path: SSH_API.terminal,
461
564
  handler: (req, socket, head) => {
462
- if (!isLoopbackRequest(req)) {
565
+ if (!allowed(req)) {
463
566
  socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n')
464
567
  socket.destroy()
465
568
  return
@@ -493,5 +596,9 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
493
596
  },
494
597
  }
495
598
 
496
- return { routes, upgrade, terminalSessions }
599
+ return {
600
+ routes: routes.map((route): AuthAwareWebRoute => ({ ...route, auth: 'anonymous' })),
601
+ upgrade: { ...upgrade, auth: 'anonymous' } as AuthAwareWebUpgradeRoute,
602
+ terminalSessions,
603
+ }
497
604
  }