@linxin666/dsh-ssh 0.4.18 → 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.
package/src/service.ts ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The cordis service `dsh-ssh` publishes to sibling plugins.
3
+ *
4
+ * A plugin that needs the host inventory or the shared connection pool injects
5
+ * this service (`ctx.inject(['dshSsh'], ...)`) instead of importing this
6
+ * package. The face is a thin forwarder over the same `SshEngine` instance the
7
+ * routes, the agent tools and the panel drive, so a consumer shares one host
8
+ * store and one connection pool with the surfaces the user already operates.
9
+ *
10
+ * This module is the published contract and is deliberately import-free: a
11
+ * consuming package restates these declarations verbatim and resolves the
12
+ * service by {@link DSH_SSH_SERVICE} at runtime, so the two packages share a
13
+ * shape without sharing a module. Only the members named here exist — the web
14
+ * terminal, tunnels, cluster runs, directory listing and any streaming log
15
+ * stay behind the plugin's own surfaces.
16
+ *
17
+ * @module @linxin666/dsh-ssh/service
18
+ */
19
+
20
+ /** Cordis service name the host half publishes the face under. */
21
+ export const DSH_SSH_SERVICE = 'dshSsh'
22
+
23
+ /** Version of this contract; a consumer restates the number it was built against. */
24
+ export const DSH_SSH_API_VERSION = 1
25
+
26
+ /** Authentication flavors a host entry may carry. */
27
+ export type DshSshAuthKind = 'key' | 'password' | 'agent'
28
+
29
+ /**
30
+ * One host as the service reports it: the fields the plugin's own
31
+ * `SshHostSummary` already publishes, minus the `proxyCommand` text.
32
+ *
33
+ * The omission is the trust boundary, not an oversight. A ProxyCommand is a
34
+ * shell line the host process executes with its own privileges, so no consumer
35
+ * receives it — the agent tools project it to a boolean for the same reason.
36
+ * Passwords, key passphrases and private-key paths are absent as well: this
37
+ * face describes a host, it never hands out credentials.
38
+ */
39
+ export interface DshSshHost {
40
+ /** Stable, user-chosen identifier every operation addresses. */
41
+ alias: string
42
+ /** Hostname or IP of the target. */
43
+ host: string
44
+ /** SSH port. */
45
+ port: number
46
+ /** Login user. */
47
+ user: string
48
+ /** Authentication flavor the stored entry uses. */
49
+ auth: DshSshAuthKind
50
+ /** Whether the configured private-key file exists on this machine (key auth only). */
51
+ keyReady: boolean
52
+ /** Jump chain: local aliases connected through in order. */
53
+ proxyJump: string[]
54
+ /** Free-form note. */
55
+ description?: string
56
+ /** Deployment environment label. */
57
+ environment?: string
58
+ /** Free-form tags. */
59
+ tags: string[]
60
+ /** Physical location note. */
61
+ location?: string
62
+ /** Whether this host's sessions forward the local ssh-agent. */
63
+ forwardAgent: boolean
64
+ /** Creation timestamp (ms). */
65
+ createdAt: number
66
+ /** Last-change timestamp (ms). */
67
+ updatedAt: number
68
+ }
69
+
70
+ /** Ceiling and cancellation for one remote command. */
71
+ export interface DshSshExecOptions {
72
+ /** Wall-clock ceiling for the remote command; the engine default applies when absent. */
73
+ timeoutMs?: number
74
+ /** Aborting closes the remote channel and settles the call as a cancelled command. */
75
+ signal?: AbortSignal
76
+ }
77
+
78
+ /** One finished remote command. */
79
+ export interface DshSshExecResult {
80
+ /** Whether the command exited zero. */
81
+ success: boolean
82
+ /** Remote exit code, or null when the channel died without one. */
83
+ exitCode: number | null
84
+ /** Whether the ceiling stopped the run. */
85
+ timedOut: boolean
86
+ /** Captured standard output, verbatim. */
87
+ stdout: string
88
+ /** Captured standard error, verbatim. */
89
+ stderr: string
90
+ /** Round trip in milliseconds. */
91
+ durationMs: number
92
+ /** Connection error message when the command never ran. */
93
+ error?: string
94
+ }
95
+
96
+ /** Outcome of one upload. */
97
+ export interface DshSshUploadResult {
98
+ /** Bytes written. */
99
+ bytes: number
100
+ /** Files written (one for a single-file upload). */
101
+ files: number
102
+ }
103
+
104
+ /** Outcome of one download. */
105
+ export interface DshSshDownloadResult {
106
+ /** Bytes written locally. */
107
+ bytes: number
108
+ }
109
+
110
+ /**
111
+ * The face a sibling plugin receives under the `dshSsh` service name.
112
+ *
113
+ * Every member is a forward: no gate, no cache and no state of its own lives
114
+ * here, so a consumer is refused by exactly what refuses the GUI and the agent
115
+ * tools, and a settings change to the plugin reaches all of them at once.
116
+ */
117
+ export interface DshSshService {
118
+ /** Contract version this face implements. */
119
+ readonly apiVersion: typeof DSH_SSH_API_VERSION
120
+ /** The host inventory the plugin's own surfaces read. */
121
+ readonly hosts: {
122
+ /** Every configured host, secret-free, in store order. */
123
+ list(): DshSshHost[]
124
+ /** One host by alias, or undefined when the alias is not configured. */
125
+ find(alias: string): DshSshHost | undefined
126
+ }
127
+ /**
128
+ * Run one command on a host through the shared pool.
129
+ * @param alias - configured host alias.
130
+ * @param command - command line handed to the remote shell.
131
+ * @param options - ceiling and cancellation.
132
+ * @returns the finished command.
133
+ */
134
+ exec(alias: string, command: string, options?: DshSshExecOptions): Promise<DshSshExecResult>
135
+ /**
136
+ * Upload one local file to an absolute remote path.
137
+ * @param alias - configured host alias.
138
+ * @param localPath - file on this machine (a directory is not part of this face).
139
+ * @param remotePath - absolute destination path on the host.
140
+ * @returns bytes and files written.
141
+ */
142
+ upload(alias: string, localPath: string, remotePath: string): Promise<DshSshUploadResult>
143
+ /**
144
+ * Download one remote file to a local path.
145
+ * @param alias - configured host alias.
146
+ * @param remotePath - file on the host.
147
+ * @param localPath - destination path on this machine.
148
+ * @returns bytes written.
149
+ */
150
+ download(alias: string, remotePath: string, localPath: string): Promise<DshSshDownloadResult>
151
+ }
152
+
153
+ declare module '@deepseek-ai/cordis' {
154
+ interface Context {
155
+ /** The dsh-ssh face, published while the plugin's master switch is on. */
156
+ dshSsh: DshSshService
157
+ }
158
+ }
package/src/store.ts CHANGED
@@ -8,10 +8,11 @@
8
8
  */
9
9
 
10
10
  import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
11
+ import { randomUUID } from 'node:crypto'
11
12
  import { homedir } from 'node:os'
12
- import { dirname, join, resolve } from 'node:path'
13
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
13
14
  import { dshHome } from './dsh-home.ts'
14
- import type { HostPayload, ImportResult, ImportSkipBlock, ImportSkipReason, SshHostEntry, SshHostSummary } from './protocol.ts'
15
+ import type { HostPayload, ImportResult, ImportSkipBlock, ImportSkipReason, SshHostEntry, SshHostSummary, SshKeyEntry, SshKeyPayload, SshKeySummary, SshPanelHostSummary } from './protocol.ts'
15
16
  import { readSshConfigBlocks } from './ssh-config.ts'
16
17
 
17
18
  /** File format version. */
@@ -30,6 +31,8 @@ export function sshConfigPath(): string {
30
31
  interface StoreFile {
31
32
  version: number
32
33
  hosts: SshHostEntry[]
34
+ /** Incremental managed-key collection; absent in every pre-feature store. */
35
+ keys?: SshKeyEntry[]
33
36
  }
34
37
 
35
38
  /** Validate the wire shape of a host payload; returns a message or undefined. */
@@ -105,10 +108,15 @@ export class HostStore {
105
108
  this.sshConfigOverride = sshConfigOverride
106
109
  }
107
110
 
108
- /** Load all entries (empty store when the file is absent). */
109
- list(): SshHostEntry[] {
111
+ /** Load host entries, optionally filtered by the panel's search text. */
112
+ list(query?: string): SshHostEntry[] {
110
113
  const file = this.load()
111
- return file.hosts
114
+ const needle = query?.trim().toLowerCase()
115
+ if (needle === undefined || needle === '') return file.hosts
116
+ return file.hosts.filter(entry => entry.alias.toLowerCase().includes(needle)
117
+ || (entry.description ?? '').toLowerCase().includes(needle)
118
+ || entry.host.toLowerCase().includes(needle)
119
+ || entry.tags.some(tag => tag.toLowerCase().includes(needle)))
112
120
  }
113
121
 
114
122
  /** Find one entry by alias. */
@@ -147,6 +155,16 @@ export class HostStore {
147
155
  }
148
156
  }
149
157
 
158
+ /** Browser-only projection that can match a stored path to a managed key. */
159
+ summarizePanel(entry: SshHostEntry): SshPanelHostSummary {
160
+ return {
161
+ ...this.summarize(entry),
162
+ ...(entry.auth.kind === 'key' && entry.auth.keyPath !== undefined && entry.auth.keyPath !== ''
163
+ ? { keyPath: entry.auth.keyPath }
164
+ : {}),
165
+ }
166
+ }
167
+
150
168
  /** Create one entry. Throws on alias collision or invalid payload. */
151
169
  create(payload: HostPayload): SshHostEntry {
152
170
  const alias = payload.alias?.trim()
@@ -167,7 +185,7 @@ export class HostStore {
167
185
  auth: {
168
186
  kind: payload.auth.kind,
169
187
  keyPath: payload.auth.kind === 'key' ? expandHome(payload.auth.keyPath?.trim() ?? '') : undefined,
170
- passphrase: payload.auth.kind === 'key' ? payload.auth.passphrase ?? undefined : undefined,
188
+ passphrase: payload.auth.kind === 'key' ? payload.auth.passphrase || undefined : undefined,
171
189
  password: payload.auth.kind === 'password' ? payload.auth.password : undefined,
172
190
  agentPath: payload.auth.kind === 'agent' ? normalizeAgentPath(payload.auth.agentPath) : undefined,
173
191
  },
@@ -248,7 +266,7 @@ export class HostStore {
248
266
  kind: auth.kind,
249
267
  keyPath: auth.kind === 'key' ? expandHome(auth.keyPath?.trim() ?? '') : undefined,
250
268
  passphrase: auth.kind === 'key'
251
- ? (auth.passphrase !== undefined ? auth.passphrase : (keyChanged ? undefined : entry.auth.passphrase))
269
+ ? (auth.passphrase !== undefined ? auth.passphrase || undefined : (keyChanged ? undefined : entry.auth.passphrase))
252
270
  : undefined,
253
271
  password: auth.kind === 'password' ? auth.password : undefined,
254
272
  agentPath: auth.kind === 'agent'
@@ -278,6 +296,92 @@ export class HostStore {
278
296
  this.save(file)
279
297
  }
280
298
 
299
+ /** List managed keys with file-existence and host-reference metadata. */
300
+ listKeys(): SshKeySummary[] {
301
+ const file = this.load()
302
+ return (file.keys ?? []).map(key => this.summarizeKey(key, file))
303
+ }
304
+
305
+ /** Create one managed key reference without reading its contents. */
306
+ createKey(payload: SshKeyPayload): SshKeySummary {
307
+ const name = requiredKeyName(payload.name)
308
+ const path = requiredKeyPath(payload.path)
309
+ const file = this.load()
310
+ const now = Date.now()
311
+ const entry: SshKeyEntry = {
312
+ id: randomUUID(),
313
+ name,
314
+ path,
315
+ passphrase: typeof payload.passphrase === 'string' && payload.passphrase !== '' ? payload.passphrase : undefined,
316
+ note: payload.note?.trim() || undefined,
317
+ createdAt: now,
318
+ updatedAt: now,
319
+ }
320
+ const keys = file.keys ??= []
321
+ keys.push(entry)
322
+ this.save(file)
323
+ return this.summarizeKey(entry, file)
324
+ }
325
+
326
+ /** Update a managed key; omitted fields and a blank passphrase keep old values. */
327
+ updateKey(id: string, patch: SshKeyPayload): SshKeySummary {
328
+ const file = this.load()
329
+ const entry = file.keys?.find(candidate => candidate.id === id)
330
+ if (entry === undefined) throw new Error(`managed key '${id}' not found`)
331
+ if (patch.name !== undefined) entry.name = requiredKeyName(patch.name)
332
+ if (patch.path !== undefined) entry.path = requiredKeyPath(patch.path)
333
+ if (patch.passphrase !== undefined) {
334
+ entry.passphrase = patch.passphrase === null || patch.passphrase === '' ? undefined : patch.passphrase
335
+ }
336
+ if (patch.note !== undefined) entry.note = patch.note.trim() || undefined
337
+ entry.updatedAt = Date.now()
338
+ this.save(file)
339
+ return this.summarizeKey(entry, file)
340
+ }
341
+
342
+ /** Delete only the managed reference; stored host auth.keyPath values stay untouched. */
343
+ deleteKey(id: string): void {
344
+ const file = this.load()
345
+ const index = file.keys?.findIndex(candidate => candidate.id === id) ?? -1
346
+ if (index < 0) throw new Error(`managed key '${id}' not found`)
347
+ file.keys!.splice(index, 1)
348
+ this.save(file)
349
+ }
350
+
351
+ /** Resolve a transient managedKeyId into the host's existing keyPath/passphrase shape. */
352
+ resolveManagedKey<T extends HostPayload | Partial<HostPayload>>(payload: T): T {
353
+ if (payload.managedKeyId === undefined) return payload
354
+ if (typeof payload.managedKeyId !== 'string' || payload.managedKeyId === '') throw new Error('managedKeyId must be a non-empty string')
355
+ if (payload.auth !== undefined && payload.auth.kind !== 'key') throw new Error('managedKeyId requires key auth')
356
+ const key = this.load().keys?.find(candidate => candidate.id === payload.managedKeyId)
357
+ if (key === undefined) throw new Error(`managed key '${payload.managedKeyId}' not found`)
358
+ const { managedKeyId: _managedKeyId, ...rest } = payload
359
+ return {
360
+ ...rest,
361
+ auth: {
362
+ ...payload.auth,
363
+ kind: 'key',
364
+ keyPath: key.path,
365
+ // An explicit empty value clears an old host passphrase when the managed key has none.
366
+ passphrase: key.passphrase ?? '',
367
+ },
368
+ } as T
369
+ }
370
+
371
+ private summarizeKey(key: SshKeyEntry, file: StoreFile): SshKeySummary {
372
+ return {
373
+ id: key.id,
374
+ name: key.name,
375
+ path: key.path,
376
+ hasPassphrase: key.passphrase !== undefined && key.passphrase !== '',
377
+ note: key.note,
378
+ exists: existsSync(expandHome(key.path)),
379
+ usedBy: file.hosts.filter(host => host.auth.kind === 'key' && host.auth.keyPath === expandHome(key.path)).map(host => host.alias),
380
+ createdAt: key.createdAt,
381
+ updatedAt: key.updatedAt,
382
+ }
383
+ }
384
+
281
385
  /**
282
386
  * Import hosts from `~/.ssh/config`: Host blocks with a single non-wildcard
283
387
  * pattern become entries (a missing HostName falls back to the pattern
@@ -437,6 +541,18 @@ export function parseForwardAgentValue(raw: string | undefined): boolean {
437
541
  return value === 'yes' || value === 'true' || value === 'on'
438
542
  }
439
543
 
544
+ function requiredKeyName(value: string | undefined): string {
545
+ if (typeof value !== 'string' || value.trim() === '') throw new Error('key name is required')
546
+ return value.trim()
547
+ }
548
+
549
+ function requiredKeyPath(value: string | undefined): string {
550
+ if (typeof value !== 'string' || value.trim() === '') throw new Error('key path is required')
551
+ const path = expandHome(value.trim())
552
+ if (!isAbsolute(path)) throw new Error('key path must be absolute')
553
+ return path
554
+ }
555
+
440
556
  /** Expand a leading `~` in a filesystem path. */
441
557
  export function expandHome(path: string): string {
442
558
  if (path === '~') return homedir()