@linxin666/dsh-ssh 0.4.19 → 0.4.20

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.
@@ -486,6 +486,11 @@ export function sweepPool(engine: PoolEngine): void {
486
486
  }
487
487
  }
488
488
 
489
+ /** Read live abort state through a function call so TypeScript does not narrow across `await`. */
490
+ function isAborted(signal?: AbortSignal): boolean {
491
+ return signal?.aborted === true
492
+ }
493
+
489
494
  /**
490
495
  * Run `fn` with a live client for `alias`, reconnecting (up to the
491
496
  * attempt budget) when the connection broke mid-flight.
@@ -493,6 +498,9 @@ export function sweepPool(engine: PoolEngine): void {
493
498
  export async function withClient<T>(engine: PoolEngine, alias: string, fn: (client: Client) => Promise<T>, attempts = 3, signal?: AbortSignal): Promise<T> {
494
499
  let lastError: unknown
495
500
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
501
+ if (isAborted(signal)) {
502
+ throw new Error('command cancelled by the caller')
503
+ }
496
504
  let record = engine.pool.get(alias)
497
505
  if (record === undefined || record.broken) {
498
506
  if (record !== undefined) disposeRecord(engine, alias, record)
@@ -508,7 +516,7 @@ export async function withClient<T>(engine: PoolEngine, alias: string, fn: (clie
508
516
  lastError = error
509
517
  // A cancelled call is never replayed: the caller asked for it to stop,
510
518
  // and a retry would re-run a command that may not be idempotent.
511
- if (signal?.aborted === true) throw error
519
+ if (isAborted(signal)) throw error
512
520
  // Retry only when the connection actually broke mid-flight: drop the
513
521
  // corpse and let the next attempt reconnect (a reconnect may replay a
514
522
  // non-idempotent command — the documented trade-off). A failure on a
@@ -525,36 +533,31 @@ export async function withClient<T>(engine: PoolEngine, alias: string, fn: (clie
525
533
  /** Run one command on `alias` (reusing the pooled connection). */
526
534
  export async function execCommand(engine: PoolEngine, alias: string, command: string, timeoutMs?: number, signal?: AbortSignal): Promise<ExecResult> {
527
535
  const started = Date.now()
536
+ if (isAborted(signal)) {
537
+ return {
538
+ success: false,
539
+ exitCode: null,
540
+ timedOut: false,
541
+ stdout: '',
542
+ stderr: '',
543
+ durationMs: Date.now() - started,
544
+ error: 'command cancelled by the caller',
545
+ }
546
+ }
528
547
  const budget = timeoutMs !== undefined && timeoutMs > 0 ? timeoutMs : engine.opts.defaultExecTimeoutMs
529
- return withClient(engine, alias, async (client) => {
530
- return await new Promise<ExecResult>((resolve, reject) => {
531
- // Caller cancellation is cooperative and quiescent: aborting closes the
532
- // remote channel and settles this call like a timeout does, so the
533
- // command stops without the pool replaying it. The channel is captured
534
- // in a mutable slot because abort may fire before client.exec calls back.
535
- let aborted = signal !== undefined && signal.aborted
536
- let kill = (): void => { /* channel not open yet */ }
537
- const onAbort = (): void => {
538
- aborted = true
539
- kill()
540
- }
541
- if (signal !== undefined && !signal.aborted) signal.addEventListener('abort', onAbort, { once: true })
542
- client.exec(command, (error, stream) => {
543
- if (error !== undefined) {
544
- signal?.removeEventListener('abort', onAbort)
545
- reject(error)
546
- return
547
- }
548
- kill = (): void => {
549
- try { stream.signal('KILL') } catch { /* channel gone */ }
550
- try { stream.close() } catch { /* channel gone */ }
551
- }
552
- // The abort may already have arrived while this channel opened.
553
- if (aborted) kill()
548
+ try {
549
+ return await withClient(engine, alias, async (client) => {
550
+ return await new Promise<ExecResult>((resolve, reject) => {
551
+ // Caller cancellation is cooperative and quiescent: aborting closes the
552
+ // remote channel and settles this call like a timeout does, so the
553
+ // command stops without the pool replaying it. The channel is captured
554
+ // in a mutable slot because abort may fire before client.exec calls back.
555
+ let aborted = signal !== undefined && signal.aborted
556
+ let settled = false
554
557
  const stdout = { text: '', truncated: false }
555
558
  const stderr = { text: '', truncated: false }
556
- let timedOut = false
557
- let settled = false
559
+ let timer: ReturnType<typeof setTimeout> | undefined
560
+ let kill = (): void => { /* channel not open yet */ }
558
561
  /** One cancelled outcome: the remote channel was killed on caller request. */
559
562
  const cancelledResult = (): ExecResult => ({
560
563
  success: false,
@@ -565,71 +568,125 @@ export async function execCommand(engine: PoolEngine, alias: string, command: st
565
568
  durationMs: Date.now() - started,
566
569
  error: 'command cancelled by the caller',
567
570
  })
568
- const finish = (): void => {
571
+ const settleCancelled = (): void => {
569
572
  if (settled) return
570
573
  settled = true
571
- clearTimeout(timer)
574
+ if (timer !== undefined) clearTimeout(timer)
572
575
  signal?.removeEventListener('abort', onAbort)
573
- resolve({
574
- success: false,
575
- exitCode: null,
576
- timedOut,
577
- stdout: stdout.text,
578
- stderr: stderr.text,
579
- durationMs: Date.now() - started,
580
- error: timedOut ? 'command timed out after ' + budget + ' ms' : undefined,
581
- })
576
+ resolve(cancelledResult())
582
577
  }
583
- const timer = setTimeout(() => {
584
- timedOut = true
585
- try { stream.signal('KILL') } catch { /* channel gone */ }
586
- try { stream.close() } catch { /* channel gone */ }
587
- // Hard deadline: settle now even if the peer never acks the
588
- // channel close (the stream 'close' handler is then a no-op).
589
- finish()
590
- }, budget)
591
- stream.on('data', (chunk: Buffer) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes))
592
- stream.stderr.on('data', (chunk: Buffer) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes))
593
- stream.on('close', (code: number | null) => {
594
- if (settled) return
595
- settled = true
596
- clearTimeout(timer)
597
- signal?.removeEventListener('abort', onAbort)
598
- // A caller cancellation settles as cancelled, never as a broken
599
- // connection: the latter would send withClient into a retry that
600
- // re-runs a command the caller asked to stop.
601
- if (aborted) {
602
- resolve(cancelledResult())
578
+ const onAbort = (): void => {
579
+ aborted = true
580
+ kill()
581
+ // Hard cancellation deadline: settle immediately even if the peer is
582
+ // half-open and never acks the channel close, matching timeout behavior.
583
+ settleCancelled()
584
+ }
585
+ if (aborted) {
586
+ settleCancelled()
587
+ return
588
+ }
589
+ if (signal !== undefined) signal.addEventListener('abort', onAbort, { once: true })
590
+ client.exec(command, (error, stream) => {
591
+ if (error !== undefined) {
592
+ signal?.removeEventListener('abort', onAbort)
593
+ if (aborted) {
594
+ settleCancelled()
595
+ return
596
+ }
597
+ reject(error)
603
598
  return
604
599
  }
605
- if (typeof code !== 'number' && !timedOut) {
606
- // The channel closed without an exit status: the connection
607
- // dropped mid-flight. Reject so withClient can reconnect and
608
- // retry within the attempt budget.
609
- reject(new Error('ssh: connection lost mid-flight (channel closed without an exit status)'))
610
- return
600
+ kill = (): void => {
601
+ try { stream.signal('KILL') } catch { /* channel gone */ }
602
+ try { stream.close() } catch { /* channel gone */ }
611
603
  }
612
- resolve({
613
- success: code === 0,
614
- exitCode: code,
615
- timedOut,
616
- stdout: stdout.text,
617
- stderr: stderr.text,
618
- durationMs: Date.now() - started,
619
- })
620
- })
621
- stream.on('error', (streamError: Error) => {
622
- if (settled) return
623
- settled = true
624
- clearTimeout(timer)
625
- signal?.removeEventListener('abort', onAbort)
604
+ // The abort may already have arrived while this channel opened.
626
605
  if (aborted) {
627
- resolve(cancelledResult())
606
+ kill()
607
+ settleCancelled()
628
608
  return
629
609
  }
630
- reject(streamError)
610
+ let timedOut = false
611
+ const finish = (): void => {
612
+ if (settled) return
613
+ settled = true
614
+ if (timer !== undefined) clearTimeout(timer)
615
+ signal?.removeEventListener('abort', onAbort)
616
+ resolve({
617
+ success: false,
618
+ exitCode: null,
619
+ timedOut,
620
+ stdout: stdout.text,
621
+ stderr: stderr.text,
622
+ durationMs: Date.now() - started,
623
+ error: timedOut ? 'command timed out after ' + budget + ' ms' : undefined,
624
+ })
625
+ }
626
+ timer = setTimeout(() => {
627
+ timedOut = true
628
+ try { stream.signal('KILL') } catch { /* channel gone */ }
629
+ try { stream.close() } catch { /* channel gone */ }
630
+ // Hard deadline: settle now even if the peer never acks the
631
+ // channel close (the stream 'close' handler is then a no-op).
632
+ finish()
633
+ }, budget)
634
+ stream.on('data', (chunk: Buffer) => appendOutput(stdout, chunk, engine.opts.maxOutputBytes))
635
+ stream.stderr.on('data', (chunk: Buffer) => appendOutput(stderr, chunk, engine.opts.maxOutputBytes))
636
+ stream.on('close', (code: number | null) => {
637
+ if (settled) return
638
+ settled = true
639
+ if (timer !== undefined) clearTimeout(timer)
640
+ signal?.removeEventListener('abort', onAbort)
641
+ // A caller cancellation settles as cancelled, never as a broken
642
+ // connection: the latter would send withClient into a retry that
643
+ // re-runs a command the caller asked to stop.
644
+ if (aborted) {
645
+ resolve(cancelledResult())
646
+ return
647
+ }
648
+ if (typeof code !== 'number' && !timedOut) {
649
+ // The channel closed without an exit status: the connection
650
+ // dropped mid-flight. Reject so withClient can reconnect and
651
+ // retry within the attempt budget.
652
+ reject(new Error('ssh: connection lost mid-flight (channel closed without an exit status)'))
653
+ return
654
+ }
655
+ resolve({
656
+ success: code === 0,
657
+ exitCode: code,
658
+ timedOut,
659
+ stdout: stdout.text,
660
+ stderr: stderr.text,
661
+ durationMs: Date.now() - started,
662
+ })
663
+ })
664
+ stream.on('error', (streamError: Error) => {
665
+ if (settled) return
666
+ settled = true
667
+ if (timer !== undefined) clearTimeout(timer)
668
+ signal?.removeEventListener('abort', onAbort)
669
+ if (aborted) {
670
+ resolve(cancelledResult())
671
+ return
672
+ }
673
+ reject(streamError)
674
+ })
631
675
  })
632
676
  })
633
- })
634
- })
635
- }
677
+ }, undefined, signal)
678
+ } catch (error) {
679
+ if (isAborted(signal)) {
680
+ return {
681
+ success: false,
682
+ exitCode: null,
683
+ timedOut: false,
684
+ stdout: '',
685
+ stderr: '',
686
+ durationMs: Date.now() - started,
687
+ error: 'command cancelled by the caller',
688
+ }
689
+ }
690
+ throw error
691
+ }
692
+ }
package/src/engine.ts CHANGED
@@ -65,14 +65,7 @@ export class SshEngine {
65
65
 
66
66
  /** Secret-free host list (filtered by the optional query). */
67
67
  list(query?: string): SshHostSummary[] {
68
- const needle = query?.trim().toLowerCase()
69
- return this.store.list()
70
- .filter(entry => needle === undefined || needle === ''
71
- || entry.alias.toLowerCase().includes(needle)
72
- || (entry.description ?? '').toLowerCase().includes(needle)
73
- || entry.host.toLowerCase().includes(needle)
74
- || entry.tags.some(tag => tag.toLowerCase().includes(needle)))
75
- .map(entry => this.store.summarize(entry))
68
+ return this.store.list(query).map(entry => this.store.summarize(entry))
76
69
  }
77
70
 
78
71
  /** One host summary by alias. */
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,6 +232,11 @@ 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
241
  // is kept under one disposer: re-registering first tears the old one down
188
242
  // so duplicate-name registrations never throw.
@@ -204,6 +258,15 @@ function applyImpl(ctx: Context, config?: ResolvedConfig): void {
204
258
  disposeTools()
205
259
  disposeTools = undefined
206
260
  }
261
+ // The service follows the master switch only: a settings edit that keeps
262
+ // the plugin on leaves the provision — and every dependent's inject scope —
263
+ // alone, so an unrelated field does not reboot consumers.
264
+ if (disposeService !== undefined && !value.enabled) {
265
+ // Unproviding releases every dependent fiber that injected the service;
266
+ // each of those scopes unloads with it.
267
+ disposeService()
268
+ disposeService = undefined
269
+ }
207
270
  if (!value.enabled) return
208
271
  if (value.announceToAgent) {
209
272
  disposeSection = ctx.systemPrompt.section({
@@ -237,6 +300,9 @@ function applyImpl(ctx: Context, config?: ResolvedConfig): void {
237
300
  },
238
301
  'dsh-ssh: tools',
239
302
  )
303
+ if (disposeService === undefined && typeof (ctx as { provide?: unknown }).provide === 'function') {
304
+ disposeService = ctx.provide(DSH_SSH_SERVICE, createService(engine))
305
+ }
240
306
  }
241
307
 
242
308
  // 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,15 @@ 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'
19
22
  import { TerminalSessionRegistry } from './engine/terminal-sessions.ts'
20
23
  import { readJsonBody, writeJson } from './http.ts'
21
24
  import { isLoopbackRequest } from './loopback.ts'
22
- import { SSH_API, type HostPayload, type TerminalServerFrame } from './protocol.ts'
25
+ import { connectionAdmits, type HostConnectionReader } from './connection-trust.ts'
26
+ import { SSH_API, type HostPayload, type SshKeyPayload, type TerminalServerFrame } from './protocol.ts'
23
27
  import type { HostStore } from './store.ts'
24
28
 
25
29
  /** Cap on declared upload bodies (staged to disk before SFTP). */
@@ -44,6 +48,8 @@ export interface SshRoutesDeps {
44
48
  store: HostStore
45
49
  /** The engine (ops). */
46
50
  engine: SshEngine
51
+ /** Optional Host connection trust decision, read afresh for each request. */
52
+ connection?: HostConnectionReader
47
53
  /** Temp dir for upload/download staging (tests inject a sandbox). */
48
54
  stagingDir?: string
49
55
  /** Upload byte cap override (tests); defaults to MAX_UPLOAD_BYTES. */
@@ -65,9 +71,11 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
65
71
  // staged files below are 0600; downloads are pre-created 0600 as well).
66
72
  mkdirSync(staging, { recursive: true, mode: 0o700 })
67
73
 
68
- /** Guard helper: fence + method check. */
74
+ const allowed = (req: IncomingMessage): boolean => connectionAdmits(deps.connection?.(), req) || isLoopbackRequest(req)
75
+
76
+ /** Guard helper: Host connection trust or loopback fence + method check. */
69
77
  const guard = (req: IncomingMessage, res: ServerResponse, method: string): boolean => {
70
- if (!isLoopbackRequest(req)) {
78
+ if (!allowed(req)) {
71
79
  writeJson(res, 403, { error: 'forbidden: loopback-only' })
72
80
  return false
73
81
  }
@@ -87,13 +95,13 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
87
95
  // One handler per path (the webserver keyed route registry rejects
88
96
  // duplicate (kind, path)); dispatch by HTTP method here.
89
97
  const method = req.method ?? 'GET'
90
- if (!isLoopbackRequest(req)) {
98
+ if (!allowed(req)) {
91
99
  writeJson(res, 403, { error: 'forbidden: loopback-only' })
92
100
  return
93
101
  }
94
102
  const url = new URL(req.url ?? '/', 'http://localhost')
95
103
  if (method === 'GET') {
96
- writeJson(res, 200, { hosts: engine.list(queryParam(url, 'query')) })
104
+ writeJson(res, 200, { hosts: store.list(queryParam(url, 'query')).map(entry => store.summarizePanel(entry)) })
97
105
  return
98
106
  }
99
107
  if (method === 'POST') {
@@ -103,8 +111,8 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
103
111
  return
104
112
  }
105
113
  try {
106
- const entry = store.create(body as unknown as HostPayload)
107
- writeJson(res, 201, { host: store.summarize(entry) })
114
+ const entry = store.create(store.resolveManagedKey(body as unknown as HostPayload))
115
+ writeJson(res, 201, { host: store.summarizePanel(entry) })
108
116
  } catch (error) {
109
117
  writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
110
118
  }
@@ -126,7 +134,7 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
126
134
  return
127
135
  }
128
136
  try {
129
- const entry = store.update(alias, body as unknown as Partial<HostPayload>)
137
+ const entry = store.update(alias, store.resolveManagedKey(body as unknown as Partial<HostPayload>))
130
138
  // Connection-relevant changes invalidate the pooled connection:
131
139
  // without this the pool would keep running commands on the old
132
140
  // host/credentials until the idle sweep (up to 30 min later).
@@ -137,7 +145,7 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
137
145
  if (['host', 'port', 'user', 'auth', 'proxyJump', 'proxyCommand', 'forwardAgent'].some(key => patch[key] !== undefined)) {
138
146
  engine.dropAlias(alias)
139
147
  }
140
- writeJson(res, 200, { host: store.summarize(entry) })
148
+ writeJson(res, 200, { host: store.summarizePanel(entry) })
141
149
  } catch (error) {
142
150
  writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
143
151
  }
@@ -156,6 +164,63 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
156
164
  writeJson(res, 405, { error: `method not allowed: ${method}` })
157
165
  },
158
166
  },
167
+ {
168
+ kind: 'exact',
169
+ path: SSH_API.keys,
170
+ handler: async (req, res) => {
171
+ const method = req.method ?? 'GET'
172
+ if (!allowed(req)) {
173
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
174
+ return
175
+ }
176
+ if (method === 'GET') {
177
+ writeJson(res, 200, { keys: store.listKeys() })
178
+ return
179
+ }
180
+ const url = new URL(req.url ?? '/', 'http://localhost')
181
+ if (method === 'POST') {
182
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
183
+ if (body === null) {
184
+ writeJson(res, 400, { error: 'invalid JSON body' })
185
+ return
186
+ }
187
+ try {
188
+ writeJson(res, 201, { key: store.createKey(body as SshKeyPayload) })
189
+ } catch (error) {
190
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
191
+ }
192
+ return
193
+ }
194
+ if (method !== 'PATCH' && method !== 'DELETE') {
195
+ writeJson(res, 405, { error: `method not allowed: ${method}` })
196
+ return
197
+ }
198
+ const id = queryParam(url, 'id')
199
+ if (id === undefined || id === '') {
200
+ writeJson(res, 400, { error: 'id query parameter is required' })
201
+ return
202
+ }
203
+ if (method === 'DELETE') {
204
+ try {
205
+ store.deleteKey(id)
206
+ writeJson(res, 200, { ok: true })
207
+ } catch (error) {
208
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
209
+ }
210
+ return
211
+ }
212
+ const body = (await readJsonBody(req)) as Record<string, unknown> | null
213
+ if (body === null) {
214
+ writeJson(res, 400, { error: 'invalid JSON body' })
215
+ return
216
+ }
217
+ try {
218
+ writeJson(res, 200, { key: store.updateKey(id, body as SshKeyPayload) })
219
+ } catch (error) {
220
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) })
221
+ }
222
+ },
223
+ },
159
224
  {
160
225
  kind: 'exact',
161
226
  path: SSH_API.importSshConfig,
@@ -459,7 +524,7 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
459
524
  const upgrade: WebUpgradeRoute = {
460
525
  path: SSH_API.terminal,
461
526
  handler: (req, socket, head) => {
462
- if (!isLoopbackRequest(req)) {
527
+ if (!allowed(req)) {
463
528
  socket.write('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n')
464
529
  socket.destroy()
465
530
  return
@@ -493,5 +558,9 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
493
558
  },
494
559
  }
495
560
 
496
- return { routes, upgrade, terminalSessions }
561
+ return {
562
+ routes: routes.map((route): AuthAwareWebRoute => ({ ...route, auth: 'anonymous' })),
563
+ upgrade: { ...upgrade, auth: 'anonymous' } as AuthAwareWebUpgradeRoute,
564
+ terminalSessions,
565
+ }
497
566
  }