@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/client/api.ts CHANGED
@@ -10,7 +10,9 @@ import {
10
10
  type HostPayload,
11
11
  type ImportResult,
12
12
  type RemoteDirEntry,
13
- type SshHostSummary,
13
+ type SshKeyPayload,
14
+ type SshKeySummary,
15
+ type SshPanelHostSummary,
14
16
  type TerminalClientFrame,
15
17
  type TerminalServerFrame,
16
18
  type TestResult,
@@ -23,7 +25,11 @@ import { tt } from './panel/helpers.ts'
23
25
  /** Minimal File System Access API surface (not in all lib.dom versions). */
24
26
  interface WindowWithFileSystemAccess {
25
27
  showSaveFilePicker?: (options: { suggestedName?: string }) => Promise<{
26
- createWritable: () => Promise<{ write: (data: Uint8Array) => Promise<void>; close: () => Promise<void> }>
28
+ createWritable: () => Promise<{
29
+ write: (data: Uint8Array) => Promise<void>
30
+ close: () => Promise<void>
31
+ abort?: () => Promise<void>
32
+ }>
27
33
  }>
28
34
  }
29
35
 
@@ -235,29 +241,29 @@ export interface TerminalConnection {
235
241
  /** The browser half's only data entry point. */
236
242
  export class SshApi {
237
243
  // -------------------------------------------------------------- hosts
238
- async listHosts(queryText?: string): Promise<SshHostSummary[]> {
244
+ async listHosts(queryText?: string): Promise<SshPanelHostSummary[]> {
239
245
  const response = await fetch(SSH_API.hosts + query({ query: queryText }))
240
- const body = await readJson<{ hosts: SshHostSummary[] }>(response)
246
+ const body = await readJson<{ hosts: SshPanelHostSummary[] }>(response)
241
247
  return body.hosts
242
248
  }
243
249
 
244
- async createHost(payload: HostPayload): Promise<SshHostSummary> {
250
+ async createHost(payload: HostPayload): Promise<SshPanelHostSummary> {
245
251
  const response = await fetch(SSH_API.hosts, {
246
252
  method: 'POST',
247
253
  headers: { 'content-type': 'application/json' },
248
254
  body: JSON.stringify(payload),
249
255
  })
250
- const body = await readJson<{ host: SshHostSummary }>(response)
256
+ const body = await readJson<{ host: SshPanelHostSummary }>(response)
251
257
  return body.host
252
258
  }
253
259
 
254
- async updateHost(alias: string, patch: HostPayload): Promise<SshHostSummary> {
260
+ async updateHost(alias: string, patch: HostPayload): Promise<SshPanelHostSummary> {
255
261
  const response = await fetch(SSH_API.hosts + query({ alias }), {
256
262
  method: 'PATCH',
257
263
  headers: { 'content-type': 'application/json' },
258
264
  body: JSON.stringify(patch),
259
265
  })
260
- const body = await readJson<{ host: SshHostSummary }>(response)
266
+ const body = await readJson<{ host: SshPanelHostSummary }>(response)
261
267
  return body.host
262
268
  }
263
269
 
@@ -266,6 +272,38 @@ export class SshApi {
266
272
  await readJson<{ ok: boolean }>(response)
267
273
  }
268
274
 
275
+ // -------------------------------------------------------------- managed keys
276
+ async listKeys(): Promise<SshKeySummary[]> {
277
+ const response = await fetch(SSH_API.keys)
278
+ const body = await readJson<{ keys: SshKeySummary[] }>(response)
279
+ return body.keys
280
+ }
281
+
282
+ async createKey(payload: SshKeyPayload): Promise<SshKeySummary> {
283
+ const response = await fetch(SSH_API.keys, {
284
+ method: 'POST',
285
+ headers: { 'content-type': 'application/json' },
286
+ body: JSON.stringify(payload),
287
+ })
288
+ const body = await readJson<{ key: SshKeySummary }>(response)
289
+ return body.key
290
+ }
291
+
292
+ async updateKey(id: string, patch: SshKeyPayload): Promise<SshKeySummary> {
293
+ const response = await fetch(SSH_API.keys + query({ id }), {
294
+ method: 'PATCH',
295
+ headers: { 'content-type': 'application/json' },
296
+ body: JSON.stringify(patch),
297
+ })
298
+ const body = await readJson<{ key: SshKeySummary }>(response)
299
+ return body.key
300
+ }
301
+
302
+ async deleteKey(id: string): Promise<void> {
303
+ const response = await fetch(SSH_API.keys + query({ id }), { method: 'DELETE' })
304
+ await readJson<{ ok: boolean }>(response)
305
+ }
306
+
269
307
  async importSshConfig(): Promise<ImportResult> {
270
308
  const response = await fetch(SSH_API.importSshConfig, { method: 'POST' })
271
309
  const body = await readJson<{ result: ImportResult }>(response)
@@ -384,28 +422,44 @@ export class SshApi {
384
422
  let finalError: string | undefined
385
423
  let sawResult = false
386
424
  let transferredBytes = 0
387
- for (;;) {
388
- const { done, value } = await reader.read()
389
- if (done) break
390
- buffer += decoder.decode(value, { stream: true })
391
- const lines = buffer.split('\n')
392
- buffer = lines.pop() ?? ''
393
- for (const line of lines) {
394
- if (line.trim() === '') continue
395
- let parsed: TransferStreamLine
396
- try {
397
- parsed = JSON.parse(line) as TransferStreamLine
398
- } catch {
399
- continue
400
- }
401
- if (parsed.type === 'progress') {
402
- onProgress?.(parsed.progress)
403
- } else if (parsed.type === 'result') {
404
- sawResult = true
405
- if (parsed.ok) transferredBytes = parsed.transferredBytes ?? 0
406
- finalError = parsed.ok ? undefined : parsed.error ?? 'upload failed'
425
+ let doneReading = false
426
+ const processLine = (line: string): void => {
427
+ if (line.trim() === '') return
428
+ let parsed: TransferStreamLine
429
+ try {
430
+ parsed = JSON.parse(line) as TransferStreamLine
431
+ } catch {
432
+ return
433
+ }
434
+ if (parsed.type === 'progress') {
435
+ onProgress?.(parsed.progress)
436
+ } else if (parsed.type === 'result') {
437
+ sawResult = true
438
+ if (parsed.ok) transferredBytes = parsed.transferredBytes ?? 0
439
+ finalError = parsed.ok ? undefined : parsed.error ?? 'upload failed'
440
+ }
441
+ }
442
+ try {
443
+ for (;;) {
444
+ const { done, value } = await reader.read()
445
+ if (done) {
446
+ doneReading = true
447
+ break
407
448
  }
449
+ buffer += decoder.decode(value, { stream: true })
450
+ const lines = buffer.split('\n')
451
+ buffer = lines.pop() ?? ''
452
+ for (const line of lines) processLine(line)
408
453
  }
454
+ buffer += decoder.decode()
455
+ if (buffer !== '') {
456
+ for (const line of buffer.split('\n')) processLine(line)
457
+ }
458
+ } finally {
459
+ if (!doneReading) {
460
+ try { await reader.cancel() } catch { /* ignore */ }
461
+ }
462
+ try { reader.releaseLock() } catch { /* ignore */ }
409
463
  }
410
464
  if (finalError !== undefined) throw new SshApiError(finalError)
411
465
  if (!sawResult) throw new SshApiError('upload ended without a result frame — the transfer did not complete')
@@ -437,11 +491,21 @@ export class SshApi {
437
491
  ? (window as WindowWithFileSystemAccess).showSaveFilePicker
438
492
  : undefined
439
493
  let streamed = false
440
- let writable: { write: (data: Uint8Array) => Promise<void>; close: () => Promise<void> } | undefined
494
+ let writable: {
495
+ write: (data: Uint8Array) => Promise<void>
496
+ close: () => Promise<void>
497
+ abort?: () => Promise<void>
498
+ } | undefined
441
499
  const chunks: Uint8Array<ArrayBuffer>[] = []
442
500
  let received = 0
443
- const progress = (): void => {
444
- onProgress?.({
501
+ let lastProgressAt = -Infinity
502
+ const PROGRESS_THROTTLE_MS = 100
503
+ const emitProgress = (force = false): void => {
504
+ if (onProgress === undefined) return
505
+ const now = Date.now()
506
+ if (!force && now - lastProgressAt < PROGRESS_THROTTLE_MS) return
507
+ lastProgressAt = now
508
+ onProgress({
445
509
  phase: 'transferring',
446
510
  file: remotePath,
447
511
  transferred: received,
@@ -449,33 +513,52 @@ export class SshApi {
449
513
  percent: total > 0 ? Math.round((received / total) * 1000) / 10 : 0,
450
514
  })
451
515
  }
516
+ let doneReading = false
517
+ let completed = false
452
518
  try {
453
- if (picker !== undefined) {
454
- const handle = await picker.call(window, { suggestedName: filename })
455
- writable = await handle.createWritable()
456
- streamed = true
519
+ try {
520
+ if (picker !== undefined) {
521
+ const handle = await picker.call(window, { suggestedName: filename })
522
+ writable = await handle.createWritable()
523
+ streamed = true
524
+ }
525
+ } catch {
526
+ // User cancelled the save dialog or the API is unavailable: fall back.
457
527
  }
458
- } catch {
459
- // User cancelled the save dialog or the API is unavailable: fall back.
460
- }
461
- for (;;) {
462
- const { done, value } = await reader.read()
463
- if (done) break
464
- if (writable !== undefined) {
465
- await writable.write(value as Uint8Array)
466
- } else {
467
- chunks.push(value as Uint8Array<ArrayBuffer>)
528
+ for (;;) {
529
+ const { done, value } = await reader.read()
530
+ if (done) {
531
+ doneReading = true
532
+ break
533
+ }
534
+ if (writable !== undefined) {
535
+ await writable.write(value as Uint8Array)
536
+ } else {
537
+ chunks.push(value as Uint8Array<ArrayBuffer>)
538
+ }
539
+ received += value.length
540
+ emitProgress(lastProgressAt < 0)
468
541
  }
469
- received += value.length
470
- progress()
471
- }
472
- if (writable !== undefined) await writable.close()
473
- onProgress?.({ phase: 'done', file: remotePath, transferred: received, total: received > 0 ? received : total, percent: 100 })
474
- return {
475
- blob: streamed ? undefined : new Blob(chunks),
476
- filename,
477
- streamed,
478
- bytes: received,
542
+ if (writable !== undefined) await writable.close()
543
+ completed = true
544
+ onProgress?.({ phase: 'done', file: remotePath, transferred: received, total: received > 0 ? received : total, percent: 100 })
545
+ return {
546
+ blob: streamed ? undefined : new Blob(chunks),
547
+ filename,
548
+ streamed,
549
+ bytes: received,
550
+ }
551
+ } finally {
552
+ if (!completed && writable !== undefined) {
553
+ try {
554
+ if (writable.abort !== undefined) await writable.abort()
555
+ else await writable.close()
556
+ } catch { /* ignore */ }
557
+ }
558
+ if (!doneReading) {
559
+ try { await reader.cancel() } catch { /* ignore */ }
560
+ }
561
+ try { reader.releaseLock() } catch { /* ignore */ }
479
562
  }
480
563
  }
481
564
 
@@ -591,6 +674,12 @@ export class SshApi {
591
674
  // A deliberate detach/close must not surface as a transport error: the
592
675
  // view tears down silently, and only an UNEXPECTED close reports exit.
593
676
  let leaving = false
677
+ let exited = false
678
+ const notifyExit = (code: number | null, error?: string): void => {
679
+ if (exited) return
680
+ exited = true
681
+ connection.onExit?.(code, error)
682
+ }
594
683
  const sendFrame = (frame: TerminalClientFrame): void => {
595
684
  if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(frame))
596
685
  }
@@ -622,11 +711,11 @@ export class SshApi {
622
711
  }
623
712
  if (frame.type === 'ready') connection.onReady?.(frame.sessionId, frame.alias)
624
713
  else if (frame.type === 'output') connection.onOutput?.(frame.data)
625
- else if (frame.type === 'exit') connection.onExit?.(frame.code, frame.error)
714
+ else if (frame.type === 'exit') notifyExit(frame.code, frame.error)
626
715
  else if (frame.type === 'auth_prompt') connection.onAuthPrompt?.(frame.name, frame.instructions, frame.prompts)
627
716
  }
628
- socket.onclose = () => { if (!leaving) connection.onExit?.(null, 'connection closed') }
629
- socket.onerror = () => { if (!leaving) connection.onExit?.(null, 'connection error') }
717
+ socket.onclose = () => { if (!leaving) notifyExit(null, 'connection closed') }
718
+ socket.onerror = () => { if (!leaving) notifyExit(null, 'connection error') }
630
719
  return connection
631
720
  }
632
721
  }
@@ -8,6 +8,7 @@ export const zh = {
8
8
  'panel.title': '远程 SSH',
9
9
  'panel.backToConversation': '返回会话',
10
10
  'tab.hosts': '主机',
11
+ 'tab.keys': '密钥',
11
12
  'tab.terminal': '终端',
12
13
  'tab.transfer': '传输',
13
14
  'tab.tunnels': '隧道',
@@ -65,9 +66,15 @@ export const zh = {
65
66
  'form.auth.agent': 'SSH Agent',
66
67
  'form.agentPath': 'Agent 路径',
67
68
  'form.agentPathHint': '留空自动检测(SSH_AUTH_SOCK;Windows 上为原生 ssh-agent 命名管道);也可填 socket 路径或 pageant',
68
- 'form.authKeepHint': '编辑时密码 / 私钥留空将保留已存凭据;Agent 路径留空是合法的自动检测,选「SSH Agent」即切换到 agent 认证。',
69
+ 'form.authKeepHint': '编辑时密码 / 密钥口令留空将保留已存凭据;私钥路径用于匹配受管密钥且不会回读口令。Agent 路径留空是合法的自动检测。',
69
70
  'form.keyPath': '私钥路径',
70
71
  'form.keyPathHint': '如 ~/.ssh/id_ed25519',
72
+ 'form.keyPathRequired': '请选择受管密钥或填写自定义私钥路径。',
73
+ 'form.managedKey': '受管密钥',
74
+ 'form.key.custom': '自定义路径…',
75
+ 'form.key.customHint': '手动填写路径;编辑时口令留空保留原值。',
76
+ 'form.key.managedHint': '路径与口令由受管密钥在宿主侧解析,不会向浏览器回读口令。',
77
+ 'form.keyListError': '受管密钥列表读取失败:{error}。仍可使用自定义路径。',
71
78
  'form.passphrase': '密钥口令',
72
79
  'form.password': '密码',
73
80
  'form.passwordHint': '明文保存在 $DSH_HOME/dsh-ssh.json(本机私有文件)',
@@ -88,6 +95,26 @@ export const zh = {
88
95
  'form.cancel': '取消',
89
96
  'form.required': '请填写必填字段:别名、主机地址、用户名。',
90
97
  'form.portInvalid': '端口必须是 1-65535 之间的整数。',
98
+ // managed keys
99
+ 'keys.add': '新增密钥',
100
+ 'keys.empty': '尚未登记密钥。密钥只保存本机路径与可选口令,不复制或读取私钥内容。',
101
+ 'keys.name': '名称',
102
+ 'keys.col.name': '名称',
103
+ 'keys.col.status': '文件状态',
104
+ 'keys.col.usedBy': '引用主机',
105
+ 'keys.exists': '文件存在',
106
+ 'keys.missing': '文件不存在',
107
+ 'keys.unused': '未被引用',
108
+ 'keys.usedBy': '{count} 台:{hosts}',
109
+ 'keys.pathHint': '绝对路径或 ~ 开头的路径;只检查文件元数据,不读取私钥内容。',
110
+ 'keys.passphraseHint': '可选口令,明文存入本机 0600 配置文件;编辑时留空保留,勾选清除可移除。',
111
+ 'keys.clearPassphrase': '清除已保存的口令',
112
+ 'keys.required': '请填写密钥名称与路径。',
113
+ 'keys.form.create': '新增受管密钥',
114
+ 'keys.form.edit': '编辑受管密钥「{name}」',
115
+ 'keys.editConfirm': '此密钥正被 {count} 台主机引用:{hosts}。本次只修改受管记录,不会自动改写这些主机的现有路径或凭据。继续?',
116
+ 'keys.deleteConfirm': '删除受管密钥「{name}」?{count} 台引用主机({hosts})会保留各自现有私钥路径与凭据,不会被删除或改写。',
117
+ 'keys.deleteConfirmUnused': '删除受管密钥「{name}」?只会删除这条受管记录,不会删除私钥文件。',
91
118
  // terminal
92
119
  'terminal.selectHost': '选择主机',
93
120
  'terminal.connect': '连接',
@@ -183,6 +210,7 @@ export const en: Record<keyof typeof zh, string> = {
183
210
  'panel.title': 'Remote SSH',
184
211
  'panel.backToConversation': 'Back to chat',
185
212
  'tab.hosts': 'Hosts',
213
+ 'tab.keys': 'Keys',
186
214
  'tab.terminal': 'Terminal',
187
215
  'tab.transfer': 'Transfer',
188
216
  'tab.tunnels': 'Tunnels',
@@ -238,9 +266,15 @@ export const en: Record<keyof typeof zh, string> = {
238
266
  'form.auth.agent': 'SSH Agent',
239
267
  'form.agentPath': 'Agent path',
240
268
  'form.agentPathHint': 'Leave empty to auto-detect (SSH_AUTH_SOCK; the native ssh-agent named pipe on Windows), or set a socket path or "pageant"',
241
- 'form.authKeepHint': 'While editing, an empty password or key field keeps the stored credential; an empty agent path is a valid auto-detect, so choosing SSH Agent switches the host to agent auth.',
269
+ 'form.authKeepHint': 'While editing, empty password/passphrase fields keep stored secrets. The private-key path is shown for managed-key matching, never its passphrase. An empty agent path remains a valid auto-detect.',
242
270
  'form.keyPath': 'Private key path',
243
271
  'form.keyPathHint': 'e.g. ~/.ssh/id_ed25519',
272
+ 'form.keyPathRequired': 'Choose a managed key or enter a custom private-key path.',
273
+ 'form.managedKey': 'Managed key',
274
+ 'form.key.custom': 'Custom path…',
275
+ 'form.key.customHint': 'Enter a path yourself; an empty passphrase keeps the old value while editing.',
276
+ 'form.key.managedHint': 'The Host resolves the managed path and passphrase without returning the passphrase to the browser.',
277
+ 'form.keyListError': 'Could not load managed keys: {error}. Custom paths remain available.',
244
278
  'form.passphrase': 'Key passphrase',
245
279
  'form.password': 'Password',
246
280
  'form.passwordHint': 'Stored in plaintext in $DSH_HOME/dsh-ssh.json (private local file)',
@@ -261,6 +295,25 @@ export const en: Record<keyof typeof zh, string> = {
261
295
  'form.cancel': 'Cancel',
262
296
  'form.required': 'Required fields missing: alias, host, user.',
263
297
  'form.portInvalid': 'Port must be an integer between 1 and 65535.',
298
+ 'keys.add': 'Add key',
299
+ 'keys.empty': 'No managed keys yet. A key stores only a local path and optional passphrase; private-key contents are never copied or read.',
300
+ 'keys.name': 'Name',
301
+ 'keys.col.name': 'Name',
302
+ 'keys.col.status': 'File status',
303
+ 'keys.col.usedBy': 'Used by',
304
+ 'keys.exists': 'File exists',
305
+ 'keys.missing': 'File missing',
306
+ 'keys.unused': 'Unused',
307
+ 'keys.usedBy': '{count}: {hosts}',
308
+ 'keys.pathHint': 'An absolute or ~-relative path; only file metadata is checked, never private-key contents.',
309
+ 'keys.passphraseHint': 'Optional passphrase stored in plaintext in the local 0600 config. Blank preserves it while editing; use the clear checkbox to remove it.',
310
+ 'keys.clearPassphrase': 'Clear the saved passphrase',
311
+ 'keys.required': 'Enter both a key name and path.',
312
+ 'keys.form.create': 'Add managed key',
313
+ 'keys.form.edit': 'Edit managed key "{name}"',
314
+ 'keys.editConfirm': '{count} hosts reference this key: {hosts}. This edits only the managed record; existing host paths and credentials are not rewritten. Continue?',
315
+ 'keys.deleteConfirm': 'Delete managed key "{name}"? Its {count} referencing hosts ({hosts}) keep their existing private-key paths and credentials; no host is deleted or rewritten.',
316
+ 'keys.deleteConfirmUnused': 'Delete managed key "{name}"? Only the managed record is removed; the private-key file is never deleted.',
264
317
  'terminal.selectHost': 'Select host',
265
318
  'terminal.connect': 'Connect',
266
319
  'terminal.disconnect': 'Disconnect',
@@ -1,12 +1,12 @@
1
1
  /**
2
2
  * Host form dialog: create/edit one stored host entry. A fixed backdrop with
3
- * a centered card; Escape and backdrop clicks close it. Secrets (key path,
4
- * passphrase, password) are never pre-filled when editing (the API only
5
- * exposes the secret-free summary).
3
+ * a centered card; Escape and backdrop clicks close it. Passwords and
4
+ * passphrases are never pre-filled. The browser-only panel summary includes
5
+ * the key path solely to match a managed key; passphrases resolve Host-side.
6
6
  */
7
- import { useEffect, useState } from 'react'
7
+ import { useEffect, useRef, useState } from 'react'
8
8
  import type { SshApi } from '../api.ts'
9
- import type { HostPayload, SshAuthKind, SshHostSummary } from '../../protocol.ts'
9
+ import type { HostPayload, SshAuthKind, SshKeySummary, SshPanelHostSummary } from '../../protocol.ts'
10
10
  import { errorMessage, tt } from './helpers.ts'
11
11
  import css from './panel.module.css'
12
12
 
@@ -14,9 +14,9 @@ import css from './panel.module.css'
14
14
  export interface HostFormDialogProps {
15
15
  api: SshApi
16
16
  /** The host being edited; null/undefined means create. */
17
- editing?: SshHostSummary | null
17
+ editing?: SshPanelHostSummary | null
18
18
  onClose: () => void
19
- onSaved: (host: SshHostSummary) => void
19
+ onSaved: (host: SshPanelHostSummary) => void
20
20
  }
21
21
 
22
22
  /** The staged form values (all strings; parsed on save). */
@@ -27,6 +27,7 @@ interface FormState {
27
27
  user: string
28
28
  authKind: SshAuthKind
29
29
  keyPath: string
30
+ managedKeyId: string
30
31
  passphrase: string
31
32
  password: string
32
33
  agentPath: string
@@ -45,14 +46,15 @@ function splitList(text: string): string[] {
45
46
  }
46
47
 
47
48
  /** Initial form state: the summary's public fields plus empty secrets. */
48
- function blankOf(editing: SshHostSummary | null | undefined): FormState {
49
+ function blankOf(editing: SshPanelHostSummary | null | undefined): FormState {
49
50
  return {
50
51
  alias: editing?.alias ?? '',
51
52
  host: editing?.host ?? '',
52
53
  port: String(editing?.port ?? 22),
53
54
  user: editing?.user ?? '',
54
55
  authKind: editing?.auth ?? 'key',
55
- keyPath: '',
56
+ keyPath: editing?.keyPath ?? '',
57
+ managedKeyId: '',
56
58
  passphrase: '',
57
59
  password: '',
58
60
  agentPath: '',
@@ -71,6 +73,9 @@ export function HostFormDialog({ api, editing, onClose, onSaved }: HostFormDialo
71
73
  const [form, setForm] = useState<FormState>(() => blankOf(editing))
72
74
  const [saving, setSaving] = useState(false)
73
75
  const [error, setError] = useState<string | null>(null)
76
+ const [keys, setKeys] = useState<SshKeySummary[] | null>(null)
77
+ const [keysError, setKeysError] = useState<string | null>(null)
78
+ const keySelectionTouched = useRef(false)
74
79
 
75
80
  // Escape closes the dialog.
76
81
  useEffect(() => {
@@ -81,10 +86,37 @@ export function HostFormDialog({ api, editing, onClose, onSaved }: HostFormDialo
81
86
  return () => { document.removeEventListener('keydown', onKey) }
82
87
  }, [onClose])
83
88
 
89
+ useEffect(() => {
90
+ let cancelled = false
91
+ void api.listKeys().then(list => {
92
+ if (cancelled) return
93
+ setKeys(list)
94
+ setForm(previous => {
95
+ if (keySelectionTouched.current || previous.authKind !== 'key' || previous.managedKeyId !== '' || previous.keyPath === '') return previous
96
+ const match = list.find(key => key.path === previous.keyPath)
97
+ return match === undefined ? previous : { ...previous, managedKeyId: match.id, keyPath: match.path }
98
+ })
99
+ }, cause => {
100
+ if (!cancelled) setKeysError(errorMessage(cause))
101
+ })
102
+ return () => { cancelled = true }
103
+ }, [api])
104
+
84
105
  const set = <K extends keyof FormState>(key: K, value: FormState[K]): void => {
85
106
  setForm(prev => ({ ...prev, [key]: value }))
86
107
  }
87
108
 
109
+ const chooseManagedKey = (id: string): void => {
110
+ keySelectionTouched.current = true
111
+ const selected = keys?.find(key => key.id === id)
112
+ setForm(previous => ({
113
+ ...previous,
114
+ managedKeyId: selected?.id ?? '',
115
+ keyPath: selected?.path ?? previous.keyPath,
116
+ passphrase: '',
117
+ }))
118
+ }
119
+
88
120
  const save = async (): Promise<void> => {
89
121
  const alias = form.alias.trim()
90
122
  const host = form.host.trim()
@@ -98,6 +130,10 @@ export function HostFormDialog({ api, editing, onClose, onSaved }: HostFormDialo
98
130
  setError(tt('form.portInvalid'))
99
131
  return
100
132
  }
133
+ if (form.authKind === 'key' && form.keyPath.trim() === '' && (editing == null || editing.auth !== 'key')) {
134
+ setError(tt('form.keyPathRequired'))
135
+ return
136
+ }
101
137
  // A password-auth host needs a password on create; when editing, a blank
102
138
  // secret field preserves the stored credential instead.
103
139
  if (editing == null && form.authKind === 'password' && form.password === '') {
@@ -120,13 +156,14 @@ export function HostFormDialog({ api, editing, onClose, onSaved }: HostFormDialo
120
156
  : form.authKind === 'password'
121
157
  ? { kind: 'password', password: form.password }
122
158
  : form.authKind === 'key'
123
- ? { kind: 'key', keyPath: form.keyPath.trim(), passphrase: form.passphrase === '' ? undefined : form.passphrase }
159
+ ? { kind: 'key', keyPath: form.keyPath.trim(), passphrase: form.managedKeyId !== '' || form.passphrase === '' ? undefined : form.passphrase }
124
160
  : { kind: 'agent', agentPath: form.agentPath.trim() === '' ? undefined : form.agentPath.trim() }
125
161
  const payload: HostPayload = {
126
162
  host,
127
163
  port,
128
164
  user,
129
165
  auth,
166
+ ...(form.authKind === 'key' && form.managedKeyId !== '' && (editing == null || keySelectionTouched.current) ? { managedKeyId: form.managedKeyId } : {}),
130
167
  proxyJump: splitList(form.proxyJump),
131
168
  // Always sent (never omitted): an empty value is the explicit clear,
132
169
  // because the API cannot express "remove this field" any other way.
@@ -135,10 +172,12 @@ export function HostFormDialog({ api, editing, onClose, onSaved }: HostFormDialo
135
172
  // form can both enable and clear forwarding (omitting it would keep the
136
173
  // stored value under PATCH semantics).
137
174
  forwardAgent: form.forwardAgent,
138
- description: form.description.trim() === '' ? undefined : form.description.trim(),
139
- environment: form.environment.trim() === '' ? undefined : form.environment.trim(),
175
+ // Always sent (never omitted): an empty string is the explicit PATCH
176
+ // clear, matching store.ts semantics.
177
+ description: form.description.trim(),
178
+ environment: form.environment.trim(),
140
179
  tags: splitList(form.tags),
141
- location: form.location.trim() === '' ? undefined : form.location.trim(),
180
+ location: form.location.trim(),
142
181
  }
143
182
  setSaving(true)
144
183
  setError(null)
@@ -197,17 +236,37 @@ export function HostFormDialog({ api, editing, onClose, onSaved }: HostFormDialo
197
236
  {editing != null && <span className={css.hint}>{tt('form.authKeepHint')}</span>}
198
237
  </div>
199
238
  {form.authKind === 'key' ? (
200
- <div className={css.formRow}>
239
+ <>
240
+ <div className={css.field}>
241
+ <span className={css.fieldLabel}>{tt('form.managedKey')}</span>
242
+ <select
243
+ className={css.input}
244
+ aria-label={tt('form.managedKey')}
245
+ value={form.managedKeyId}
246
+ disabled={keys === null}
247
+ onChange={event => { chooseManagedKey(event.target.value) }}
248
+ >
249
+ <option value="">{tt('form.key.custom')}</option>
250
+ {(keys ?? []).map(key => <option key={key.id} value={key.id}>{key.name} — {key.path}</option>)}
251
+ </select>
252
+ <span className={css.hint}>
253
+ {keysError !== null
254
+ ? tt('form.keyListError', { error: keysError })
255
+ : form.managedKeyId !== '' ? tt('form.key.managedHint') : tt('form.key.customHint')}
256
+ </span>
257
+ </div>
258
+ <div className={css.formRow}>
201
259
  <label className={css.field}>
202
260
  <span className={css.fieldLabel}>{tt('form.keyPath')}</span>
203
- <input className={css.input} value={form.keyPath} onChange={event => { set('keyPath', event.target.value) }} />
261
+ <input className={css.input} value={form.keyPath} readOnly={form.managedKeyId !== ''} onChange={event => { set('keyPath', event.target.value) }} />
204
262
  <span className={css.hint}>{tt('form.keyPathHint')}</span>
205
263
  </label>
206
264
  <label className={css.field}>
207
265
  <span className={css.fieldLabel}>{tt('form.passphrase')}</span>
208
- <input className={css.input} type="password" value={form.passphrase} onChange={event => { set('passphrase', event.target.value) }} />
266
+ <input className={css.input} type="password" value={form.passphrase} disabled={form.managedKeyId !== ''} onChange={event => { set('passphrase', event.target.value) }} />
209
267
  </label>
210
- </div>
268
+ </div>
269
+ </>
211
270
  ) : form.authKind === 'agent' ? (
212
271
  <label className={css.field}>
213
272
  <span className={css.fieldLabel}>{tt('form.agentPath')}</span>