@linxin666/dsh-ssh 0.4.20 → 0.4.22
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/README.i18n.yaml +2 -2
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/lib/client.js +261 -108
- package/lib/client.js.map +1 -1
- package/lib/index.js +648 -243
- package/lib/types/engine/cluster.d.ts +7 -2
- package/lib/types/engine/connection-pool.d.ts +11 -2
- package/lib/types/engine/sftp.d.ts +5 -0
- package/lib/types/engine/terminal-sessions.d.ts +5 -3
- package/lib/types/store.d.ts +0 -1
- package/package.json +20 -20
- package/src/client/api.ts +106 -52
- package/src/client/panel/HostFormDialog.tsx +5 -3
- package/src/client/panel/HostsTab.tsx +41 -16
- package/src/client/panel/TerminalTab.tsx +14 -9
- package/src/client/panel/TunnelsTab.tsx +24 -7
- package/src/client/panel/controller.ts +76 -11
- package/src/engine/cluster.ts +45 -13
- package/src/engine/connection-pool.ts +141 -15
- package/src/engine/proxy-command.ts +27 -10
- package/src/engine/sftp.ts +69 -35
- package/src/engine/terminal-sessions.ts +110 -35
- package/src/engine/tunnel.ts +20 -2
- package/src/engine.ts +4 -0
- package/src/index.ts +50 -42
- package/src/routes.ts +51 -13
- package/src/store.ts +227 -123
- package/src/tools.ts +3 -5
package/src/routes.ts
CHANGED
|
@@ -19,6 +19,7 @@ import type { WebRoute, WebUpgradeRoute } from '@deepseek-ai/dsh-host-webserver'
|
|
|
19
19
|
type AuthAwareWebRoute = WebRoute & { readonly auth: 'anonymous' }
|
|
20
20
|
type AuthAwareWebUpgradeRoute = WebUpgradeRoute & { readonly auth: 'anonymous' }
|
|
21
21
|
import type { SshEngine } from './engine.ts'
|
|
22
|
+
import { hasClusterSelector } from './engine/cluster.ts'
|
|
22
23
|
import { TerminalSessionRegistry } from './engine/terminal-sessions.ts'
|
|
23
24
|
import { readJsonBody, writeJson } from './http.ts'
|
|
24
25
|
import { isLoopbackRequest } from './loopback.ts'
|
|
@@ -42,6 +43,17 @@ function queryParam(url: URL, name: string): string | undefined {
|
|
|
42
43
|
return value === null ? undefined : value
|
|
43
44
|
}
|
|
44
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
|
+
|
|
45
57
|
/** Route family dependencies. */
|
|
46
58
|
export interface SshRoutesDeps {
|
|
47
59
|
/** The host store (CRUD). */
|
|
@@ -134,14 +146,14 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
|
|
|
134
146
|
return
|
|
135
147
|
}
|
|
136
148
|
try {
|
|
137
|
-
const
|
|
149
|
+
const resolved = store.resolveManagedKey(body as unknown as Partial<HostPayload>)
|
|
150
|
+
const entry = store.update(alias, resolved)
|
|
138
151
|
// Connection-relevant changes invalidate the pooled connection:
|
|
139
152
|
// without this the pool would keep running commands on the old
|
|
140
153
|
// host/credentials until the idle sweep (up to 30 min later).
|
|
141
|
-
//
|
|
142
|
-
//
|
|
143
|
-
|
|
144
|
-
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>
|
|
145
157
|
if (['host', 'port', 'user', 'auth', 'proxyJump', 'proxyCommand', 'forwardAgent'].some(key => patch[key] !== undefined)) {
|
|
146
158
|
engine.dropAlias(alias)
|
|
147
159
|
}
|
|
@@ -288,10 +300,7 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
|
|
|
288
300
|
const environment = typeof body?.environment === 'string' ? body.environment : undefined
|
|
289
301
|
const timeoutMs = typeof body?.timeoutMs === 'number' ? body.timeoutMs : undefined
|
|
290
302
|
const maxWorkers = typeof body?.maxWorkers === 'number' ? body.maxWorkers : undefined
|
|
291
|
-
|
|
292
|
-
const hasEnvironment = typeof environment === 'string' && environment.trim() !== ''
|
|
293
|
-
const hasTags = tags?.some(tag => tag.trim() !== '') === true
|
|
294
|
-
if (!hasAliases && !hasEnvironment && !hasTags) {
|
|
303
|
+
if (!hasClusterSelector({ aliases, environment, tags })) {
|
|
295
304
|
writeJson(res, 400, { error: 'ssh_cluster requires aliases, environment, or tags to limit the target set' })
|
|
296
305
|
return
|
|
297
306
|
}
|
|
@@ -396,6 +405,8 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
|
|
|
396
405
|
const emit = (line: unknown): void => {
|
|
397
406
|
try { res.write(JSON.stringify(line) + '\n') } catch { /* client gone */ }
|
|
398
407
|
}
|
|
408
|
+
// Ensure the private staging directory still exists (e.g. after a /tmp sweep).
|
|
409
|
+
mkdirSync(staging, { recursive: true, mode: 0o700 })
|
|
399
410
|
// Stage the uploaded bytes, then SFTP them out with progress frames.
|
|
400
411
|
const tmp = join(staging, `upload-${randomBytes(6).toString('hex')}`)
|
|
401
412
|
const sink = createWriteStream(tmp, { mode: 0o600 })
|
|
@@ -482,22 +493,49 @@ const maxUploadBytes = deps.maxUploadBytes ?? MAX_UPLOAD_BYTES
|
|
|
482
493
|
}
|
|
483
494
|
const tmp = join(staging, `download-${randomBytes(6).toString('hex')}`)
|
|
484
495
|
try {
|
|
496
|
+
mkdirSync(staging, { recursive: true, mode: 0o700 })
|
|
485
497
|
// Pre-create with 0600: ssh2's fastGet opens the destination with
|
|
486
498
|
// umask-default permissions and a pre-created file keeps the mode.
|
|
487
499
|
closeSync(openSync(tmp, 'w', 0o600))
|
|
488
500
|
const outcome = await engine.download(alias, remotePath, tmp)
|
|
501
|
+
if (req.destroyed || res.destroyed) return
|
|
489
502
|
res.writeHead(200, {
|
|
490
503
|
'content-type': 'application/octet-stream',
|
|
491
504
|
'content-length': String(outcome.bytes),
|
|
492
|
-
'content-disposition': `attachment; filename="${basename(remotePath)
|
|
505
|
+
'content-disposition': `attachment; filename="${safeAttachmentFilename(basename(remotePath))}"`,
|
|
493
506
|
'referrer-policy': 'no-referrer',
|
|
494
507
|
})
|
|
495
508
|
await new Promise<void>((resolve, reject) => {
|
|
496
509
|
const source = createReadStream(tmp)
|
|
497
|
-
|
|
498
|
-
|
|
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)
|
|
499
538
|
source.pipe(res)
|
|
500
|
-
source.on('end', resolve)
|
|
501
539
|
})
|
|
502
540
|
} catch (error) {
|
|
503
541
|
if (!res.headersSent) {
|
package/src/store.ts
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
* as ssh-skill's annotated ssh-config comments; document it, never log it.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
|
|
11
|
-
import { randomUUID } from 'node:crypto'
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
11
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
12
12
|
import { homedir } from 'node:os'
|
|
13
13
|
import { dirname, isAbsolute, join, resolve } from 'node:path'
|
|
14
14
|
import { dshHome } from './dsh-home.ts'
|
|
@@ -35,25 +35,33 @@ interface StoreFile {
|
|
|
35
35
|
keys?: SshKeyEntry[]
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
/** Validate an auth block shape; returns an error message or undefined. */
|
|
39
|
+
function validateAuth(auth: unknown): string | undefined {
|
|
40
|
+
if (typeof auth !== 'object' || auth === null) return 'auth must be an object'
|
|
41
|
+
const a = auth as Record<string, unknown>
|
|
42
|
+
if (a.kind !== 'key' && a.kind !== 'password' && a.kind !== 'agent') return 'auth.kind must be key, password or agent'
|
|
43
|
+
if (a.kind === 'key') {
|
|
44
|
+
if (typeof a.keyPath !== 'string' || a.keyPath.trim() === '') return 'auth.keyPath is required for key auth'
|
|
45
|
+
if (a.passphrase !== undefined && typeof a.passphrase !== 'string') return 'auth.passphrase must be a string when provided'
|
|
46
|
+
}
|
|
47
|
+
if (a.kind === 'password' && a.password !== undefined && typeof a.password !== 'string') {
|
|
48
|
+
return 'auth.password must be a string when provided'
|
|
49
|
+
}
|
|
50
|
+
if (a.kind === 'agent' && a.agentPath !== undefined && typeof a.agentPath !== 'string') {
|
|
51
|
+
return 'auth.agentPath must be a string when provided'
|
|
52
|
+
}
|
|
53
|
+
return undefined
|
|
54
|
+
}
|
|
55
|
+
|
|
38
56
|
/** Validate the wire shape of a host payload; returns a message or undefined. */
|
|
39
57
|
export function validateHostPayload(payload: unknown): string | undefined {
|
|
40
58
|
if (typeof payload !== 'object' || payload === null) return 'body must be a JSON object'
|
|
41
59
|
const p = payload as Record<string, unknown>
|
|
42
60
|
if (typeof p.host !== 'string' || p.host.trim() === '') return 'host is required'
|
|
43
61
|
if (typeof p.user !== 'string' || p.user.trim() === '') return 'user is required'
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
if (
|
|
47
|
-
if (auth.kind !== 'key' && auth.kind !== 'password' && auth.kind !== 'agent') return 'auth.kind must be key, password or agent'
|
|
48
|
-
if (auth.kind === 'key' && (typeof auth.keyPath !== 'string' || auth.keyPath.trim() === '')) {
|
|
49
|
-
return 'auth.keyPath is required for key auth'
|
|
50
|
-
}
|
|
51
|
-
if (auth.kind === 'password' && auth.password !== undefined && typeof auth.password !== 'string') {
|
|
52
|
-
return 'auth.password must be a string when provided'
|
|
53
|
-
}
|
|
54
|
-
if (auth.kind === 'agent' && auth.agentPath !== undefined && typeof auth.agentPath !== 'string') {
|
|
55
|
-
return 'auth.agentPath must be a string when provided'
|
|
56
|
-
}
|
|
62
|
+
if (p.auth !== undefined) {
|
|
63
|
+
const authError = validateAuth(p.auth)
|
|
64
|
+
if (authError !== undefined) return authError
|
|
57
65
|
}
|
|
58
66
|
if (p.port !== undefined && (typeof p.port !== 'number' || !Number.isInteger(p.port) || p.port < 1 || p.port > 65535)) {
|
|
59
67
|
return 'port must be an integer in 1..65535'
|
|
@@ -81,6 +89,41 @@ export function validateHostPayload(payload: unknown): string | undefined {
|
|
|
81
89
|
return undefined
|
|
82
90
|
}
|
|
83
91
|
|
|
92
|
+
/** Validate a full creation payload and build its normalized entry. */
|
|
93
|
+
function buildValidatedHostEntry(payload: HostPayload, now: number): SshHostEntry {
|
|
94
|
+
const alias = payload.alias?.trim()
|
|
95
|
+
if (!alias) throw new Error('alias is required')
|
|
96
|
+
const aliasError = validateAlias(alias)
|
|
97
|
+
if (aliasError !== undefined) throw new Error(aliasError)
|
|
98
|
+
const bodyError = validateHostPayload(payload)
|
|
99
|
+
if (bodyError !== undefined) throw new Error(bodyError)
|
|
100
|
+
if (payload.auth === undefined) throw new Error('auth is required')
|
|
101
|
+
return {
|
|
102
|
+
alias,
|
|
103
|
+
host: payload.host.trim(),
|
|
104
|
+
port: payload.port ?? 22,
|
|
105
|
+
user: payload.user.trim(),
|
|
106
|
+
auth: {
|
|
107
|
+
kind: payload.auth.kind,
|
|
108
|
+
keyPath: payload.auth.kind === 'key' ? expandHome(payload.auth.keyPath?.trim() ?? '') : undefined,
|
|
109
|
+
passphrase: payload.auth.kind === 'key' ? payload.auth.passphrase || undefined : undefined,
|
|
110
|
+
password: payload.auth.kind === 'password' ? payload.auth.password : undefined,
|
|
111
|
+
agentPath: payload.auth.kind === 'agent' ? normalizeAgentPath(payload.auth.agentPath) : undefined,
|
|
112
|
+
},
|
|
113
|
+
proxyJump: [...(payload.proxyJump ?? [])],
|
|
114
|
+
proxyCommand: normalizeProxyCommand(payload.proxyCommand),
|
|
115
|
+
description: payload.description?.trim() || undefined,
|
|
116
|
+
environment: payload.environment?.trim() || undefined,
|
|
117
|
+
tags: [...(payload.tags ?? [])].map(tag => tag.trim()).filter(tag => tag !== ''),
|
|
118
|
+
location: payload.location?.trim() || undefined,
|
|
119
|
+
// Stored only when enabled, so a store file written without agent
|
|
120
|
+
// forwarding stays byte-identical to the pre-feature format.
|
|
121
|
+
forwardAgent: payload.forwardAgent === true ? true : undefined,
|
|
122
|
+
createdAt: now,
|
|
123
|
+
updatedAt: now,
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
84
127
|
/** Alias grammar: letters/digits plus dots, hyphens, underscores (IP/domain aliases included). */
|
|
85
128
|
const ALIAS_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/
|
|
86
129
|
|
|
@@ -112,7 +155,7 @@ export class HostStore {
|
|
|
112
155
|
list(query?: string): SshHostEntry[] {
|
|
113
156
|
const file = this.load()
|
|
114
157
|
const needle = query?.trim().toLowerCase()
|
|
115
|
-
if (needle === undefined || needle === '') return file.hosts
|
|
158
|
+
if (needle === undefined || needle === '') return [...file.hosts]
|
|
116
159
|
return file.hosts.filter(entry => entry.alias.toLowerCase().includes(needle)
|
|
117
160
|
|| (entry.description ?? '').toLowerCase().includes(needle)
|
|
118
161
|
|| entry.host.toLowerCase().includes(needle)
|
|
@@ -121,14 +164,16 @@ export class HostStore {
|
|
|
121
164
|
|
|
122
165
|
/** Find one entry by alias. */
|
|
123
166
|
find(alias: string): SshHostEntry | undefined {
|
|
124
|
-
return this.
|
|
167
|
+
return this.load().hosts.find(entry => entry.alias === alias)
|
|
125
168
|
}
|
|
126
169
|
|
|
127
170
|
/** Secret-free projection for the browser and agent surfaces. */
|
|
128
171
|
summarize(entry: SshHostEntry): SshHostSummary {
|
|
129
172
|
let keyReady = true
|
|
130
|
-
if (entry.auth.kind === 'key'
|
|
131
|
-
keyReady =
|
|
173
|
+
if (entry.auth.kind === 'key') {
|
|
174
|
+
keyReady = entry.auth.keyPath !== undefined
|
|
175
|
+
&& entry.auth.keyPath !== ''
|
|
176
|
+
&& existsSync(expandHome(entry.auth.keyPath))
|
|
132
177
|
} else if (entry.auth.kind === 'agent') {
|
|
133
178
|
keyReady = false
|
|
134
179
|
}
|
|
@@ -167,52 +212,28 @@ export class HostStore {
|
|
|
167
212
|
|
|
168
213
|
/** Create one entry. Throws on alias collision or invalid payload. */
|
|
169
214
|
create(payload: HostPayload): SshHostEntry {
|
|
170
|
-
const
|
|
171
|
-
if (!alias) throw new Error('alias is required')
|
|
172
|
-
const aliasError = validateAlias(alias)
|
|
173
|
-
if (aliasError !== undefined) throw new Error(aliasError)
|
|
174
|
-
const bodyError = validateHostPayload(payload)
|
|
175
|
-
if (bodyError !== undefined) throw new Error(bodyError)
|
|
176
|
-
if (payload.auth === undefined) throw new Error('auth is required')
|
|
215
|
+
const entry = buildValidatedHostEntry(payload, Date.now())
|
|
177
216
|
const file = this.load()
|
|
178
|
-
if (file.hosts.some(
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
auth: {
|
|
186
|
-
kind: payload.auth.kind,
|
|
187
|
-
keyPath: payload.auth.kind === 'key' ? expandHome(payload.auth.keyPath?.trim() ?? '') : undefined,
|
|
188
|
-
passphrase: payload.auth.kind === 'key' ? payload.auth.passphrase || undefined : undefined,
|
|
189
|
-
password: payload.auth.kind === 'password' ? payload.auth.password : undefined,
|
|
190
|
-
agentPath: payload.auth.kind === 'agent' ? normalizeAgentPath(payload.auth.agentPath) : undefined,
|
|
191
|
-
},
|
|
192
|
-
proxyJump: [...(payload.proxyJump ?? [])],
|
|
193
|
-
proxyCommand: normalizeProxyCommand(payload.proxyCommand),
|
|
194
|
-
description: payload.description?.trim() || undefined,
|
|
195
|
-
environment: payload.environment?.trim() || undefined,
|
|
196
|
-
tags: [...(payload.tags ?? [])].map(tag => tag.trim()).filter(tag => tag !== ''),
|
|
197
|
-
location: payload.location?.trim() || undefined,
|
|
198
|
-
// Stored only when enabled, so a store file written without agent
|
|
199
|
-
// forwarding stays byte-identical to the pre-feature format.
|
|
200
|
-
forwardAgent: payload.forwardAgent === true ? true : undefined,
|
|
201
|
-
createdAt: now,
|
|
202
|
-
updatedAt: now,
|
|
217
|
+
if (file.hosts.some(existing => existing.alias === entry.alias)) {
|
|
218
|
+
throw new Error(`alias '${entry.alias}' already exists`)
|
|
219
|
+
}
|
|
220
|
+
const nextFile: StoreFile = {
|
|
221
|
+
version: file.version,
|
|
222
|
+
hosts: [...file.hosts, entry],
|
|
223
|
+
...(file.keys !== undefined ? { keys: file.keys } : {}),
|
|
203
224
|
}
|
|
204
|
-
|
|
205
|
-
this.save(file)
|
|
225
|
+
this.save(nextFile)
|
|
206
226
|
return entry
|
|
207
227
|
}
|
|
208
228
|
|
|
209
229
|
/** Update the fields present in `patch`; unknown aliases throw. */
|
|
210
230
|
update(alias: string, patch: Partial<HostPayload>): SshHostEntry {
|
|
211
231
|
const file = this.load()
|
|
212
|
-
const
|
|
213
|
-
if (
|
|
214
|
-
|
|
215
|
-
//
|
|
232
|
+
const index = file.hosts.findIndex(candidate => candidate.alias === alias)
|
|
233
|
+
if (index < 0) throw new Error(`alias '${alias}' not found`)
|
|
234
|
+
const entry = file.hosts[index]!
|
|
235
|
+
// Validate every present field before constructing the updated entry so a
|
|
236
|
+
// failed patch never partially mutates cached store state.
|
|
216
237
|
if (patch.host !== undefined && (typeof patch.host !== 'string' || patch.host.trim() === '')) {
|
|
217
238
|
throw new Error('host is required')
|
|
218
239
|
}
|
|
@@ -242,27 +263,29 @@ export class HostStore {
|
|
|
242
263
|
if (patch.tags !== undefined && (!Array.isArray(patch.tags) || patch.tags.some(x => typeof x !== 'string'))) {
|
|
243
264
|
throw new Error('tags must be an array of strings')
|
|
244
265
|
}
|
|
245
|
-
if (patch.
|
|
246
|
-
|
|
247
|
-
|
|
266
|
+
if (patch.description !== undefined && typeof patch.description !== 'string') {
|
|
267
|
+
throw new Error('description must be a string when provided')
|
|
268
|
+
}
|
|
269
|
+
if (patch.environment !== undefined && typeof patch.environment !== 'string') {
|
|
270
|
+
throw new Error('environment must be a string when provided')
|
|
271
|
+
}
|
|
272
|
+
if (patch.location !== undefined && typeof patch.location !== 'string') {
|
|
273
|
+
throw new Error('location must be a string when provided')
|
|
274
|
+
}
|
|
275
|
+
if (patch.auth !== undefined) {
|
|
276
|
+
const authError = validateAuth(patch.auth)
|
|
277
|
+
if (authError !== undefined) throw new Error(authError)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
let nextAuth = entry.auth
|
|
248
281
|
if (patch.auth !== undefined) {
|
|
249
282
|
const auth = patch.auth
|
|
250
|
-
if (auth.kind !== 'key' && auth.kind !== 'password' && auth.kind !== 'agent') throw new Error('auth.kind must be key, password or agent')
|
|
251
|
-
if (auth.kind === 'key' && (typeof auth.keyPath !== 'string' || auth.keyPath.trim() === '')) {
|
|
252
|
-
throw new Error('auth.keyPath is required for key auth')
|
|
253
|
-
}
|
|
254
|
-
if (auth.kind === 'password' && auth.password !== undefined && typeof auth.password !== 'string') {
|
|
255
|
-
throw new Error('auth.password must be a string when provided')
|
|
256
|
-
}
|
|
257
|
-
if (auth.kind === 'agent' && auth.agentPath !== undefined && typeof auth.agentPath !== 'string') {
|
|
258
|
-
throw new Error('auth.agentPath must be a string when provided')
|
|
259
|
-
}
|
|
260
283
|
// A changed key path with no passphrase means the new key has none;
|
|
261
284
|
// only keep the old passphrase when the key path is unchanged.
|
|
262
285
|
const keyChanged = auth.kind === 'key'
|
|
263
286
|
&& auth.keyPath !== undefined
|
|
264
287
|
&& expandHome(auth.keyPath.trim()) !== entry.auth.keyPath
|
|
265
|
-
|
|
288
|
+
nextAuth = {
|
|
266
289
|
kind: auth.kind,
|
|
267
290
|
keyPath: auth.kind === 'key' ? expandHome(auth.keyPath?.trim() ?? '') : undefined,
|
|
268
291
|
passphrase: auth.kind === 'key'
|
|
@@ -274,17 +297,34 @@ export class HostStore {
|
|
|
274
297
|
: undefined,
|
|
275
298
|
}
|
|
276
299
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
300
|
+
|
|
301
|
+
const nextEntry: SshHostEntry = {
|
|
302
|
+
...entry,
|
|
303
|
+
host: patch.host !== undefined ? patch.host.trim() : entry.host,
|
|
304
|
+
port: patch.port !== undefined ? patch.port : entry.port,
|
|
305
|
+
user: patch.user !== undefined ? patch.user.trim() : entry.user,
|
|
306
|
+
auth: nextAuth,
|
|
307
|
+
proxyJump: patch.proxyJump !== undefined ? [...patch.proxyJump] : entry.proxyJump,
|
|
308
|
+
proxyCommand: patch.proxyCommand !== undefined ? mergedProxyCommand : entry.proxyCommand,
|
|
309
|
+
description: patch.description !== undefined ? patch.description.trim() || undefined : entry.description,
|
|
310
|
+
environment: patch.environment !== undefined ? patch.environment.trim() || undefined : entry.environment,
|
|
311
|
+
tags: patch.tags !== undefined
|
|
312
|
+
? [...patch.tags].map(tag => tag.trim()).filter(tag => tag !== '')
|
|
313
|
+
: entry.tags,
|
|
314
|
+
location: patch.location !== undefined ? patch.location.trim() || undefined : entry.location,
|
|
315
|
+
// PATCH semantics: an omitted key keeps the stored value, false clears it.
|
|
316
|
+
forwardAgent: patch.forwardAgent !== undefined
|
|
317
|
+
? (patch.forwardAgent === true ? true : undefined)
|
|
318
|
+
: entry.forwardAgent,
|
|
319
|
+
updatedAt: Date.now(),
|
|
320
|
+
}
|
|
321
|
+
const nextFile: StoreFile = {
|
|
322
|
+
version: file.version,
|
|
323
|
+
hosts: file.hosts.map((candidate, candidateIndex) => (candidateIndex === index ? nextEntry : candidate)),
|
|
324
|
+
...(file.keys !== undefined ? { keys: file.keys } : {}),
|
|
325
|
+
}
|
|
326
|
+
this.save(nextFile)
|
|
327
|
+
return nextEntry
|
|
288
328
|
}
|
|
289
329
|
|
|
290
330
|
/** Remove one entry. */
|
|
@@ -292,14 +332,21 @@ export class HostStore {
|
|
|
292
332
|
const file = this.load()
|
|
293
333
|
const index = file.hosts.findIndex(candidate => candidate.alias === alias)
|
|
294
334
|
if (index < 0) throw new Error(`alias '${alias}' not found`)
|
|
295
|
-
|
|
296
|
-
|
|
335
|
+
const nextFile: StoreFile = {
|
|
336
|
+
version: file.version,
|
|
337
|
+
hosts: file.hosts.filter((_, candidateIndex) => candidateIndex !== index),
|
|
338
|
+
...(file.keys !== undefined ? { keys: file.keys } : {}),
|
|
339
|
+
}
|
|
340
|
+
this.save(nextFile)
|
|
297
341
|
}
|
|
298
342
|
|
|
299
343
|
/** List managed keys with file-existence and host-reference metadata. */
|
|
300
344
|
listKeys(): SshKeySummary[] {
|
|
301
345
|
const file = this.load()
|
|
302
|
-
|
|
346
|
+
const keys = file.keys ?? []
|
|
347
|
+
if (keys.length === 0) return []
|
|
348
|
+
const usedByPath = buildUsedByPathMap(file.hosts)
|
|
349
|
+
return keys.map(key => this.summarizeKey(key, file, usedByPath))
|
|
303
350
|
}
|
|
304
351
|
|
|
305
352
|
/** Create one managed key reference without reading its contents. */
|
|
@@ -313,39 +360,63 @@ export class HostStore {
|
|
|
313
360
|
name,
|
|
314
361
|
path,
|
|
315
362
|
passphrase: typeof payload.passphrase === 'string' && payload.passphrase !== '' ? payload.passphrase : undefined,
|
|
316
|
-
note: payload.note
|
|
363
|
+
note: typeof payload.note === 'string' ? payload.note.trim() || undefined : undefined,
|
|
317
364
|
createdAt: now,
|
|
318
365
|
updatedAt: now,
|
|
319
366
|
}
|
|
320
|
-
const
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
367
|
+
const nextFile: StoreFile = {
|
|
368
|
+
version: file.version,
|
|
369
|
+
hosts: file.hosts,
|
|
370
|
+
keys: [...(file.keys ?? []), entry],
|
|
371
|
+
}
|
|
372
|
+
this.save(nextFile)
|
|
373
|
+
return this.summarizeKey(entry, nextFile)
|
|
324
374
|
}
|
|
325
375
|
|
|
326
376
|
/** Update a managed key; omitted fields and a blank passphrase keep old values. */
|
|
327
377
|
updateKey(id: string, patch: SshKeyPayload): SshKeySummary {
|
|
328
378
|
const file = this.load()
|
|
329
|
-
const
|
|
330
|
-
|
|
331
|
-
if (
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
379
|
+
const keys = file.keys ?? []
|
|
380
|
+
const index = keys.findIndex(candidate => candidate.id === id)
|
|
381
|
+
if (index < 0) throw new Error(`managed key '${id}' not found`)
|
|
382
|
+
const entry = keys[index]!
|
|
383
|
+
const nextName = patch.name !== undefined ? requiredKeyName(patch.name) : entry.name
|
|
384
|
+
const nextPath = patch.path !== undefined ? requiredKeyPath(patch.path) : entry.path
|
|
385
|
+
const nextPassphrase = patch.passphrase !== undefined
|
|
386
|
+
? (patch.passphrase === null || patch.passphrase === '' ? undefined : patch.passphrase)
|
|
387
|
+
: entry.passphrase
|
|
388
|
+
const nextNote = patch.note !== undefined
|
|
389
|
+
? (typeof patch.note === 'string' ? patch.note.trim() || undefined : undefined)
|
|
390
|
+
: entry.note
|
|
391
|
+
const nextEntry: SshKeyEntry = {
|
|
392
|
+
...entry,
|
|
393
|
+
name: nextName,
|
|
394
|
+
path: nextPath,
|
|
395
|
+
passphrase: nextPassphrase,
|
|
396
|
+
note: nextNote,
|
|
397
|
+
updatedAt: Date.now(),
|
|
398
|
+
}
|
|
399
|
+
const nextFile: StoreFile = {
|
|
400
|
+
version: file.version,
|
|
401
|
+
hosts: file.hosts,
|
|
402
|
+
keys: keys.map((candidate, candidateIndex) => (candidateIndex === index ? nextEntry : candidate)),
|
|
403
|
+
}
|
|
404
|
+
this.save(nextFile)
|
|
405
|
+
return this.summarizeKey(nextEntry, nextFile)
|
|
340
406
|
}
|
|
341
407
|
|
|
342
408
|
/** Delete only the managed reference; stored host auth.keyPath values stay untouched. */
|
|
343
409
|
deleteKey(id: string): void {
|
|
344
410
|
const file = this.load()
|
|
345
|
-
const
|
|
411
|
+
const keys = file.keys ?? []
|
|
412
|
+
const index = keys.findIndex(candidate => candidate.id === id)
|
|
346
413
|
if (index < 0) throw new Error(`managed key '${id}' not found`)
|
|
347
|
-
|
|
348
|
-
|
|
414
|
+
const nextFile: StoreFile = {
|
|
415
|
+
version: file.version,
|
|
416
|
+
hosts: file.hosts,
|
|
417
|
+
keys: keys.filter((_, candidateIndex) => candidateIndex !== index),
|
|
418
|
+
}
|
|
419
|
+
this.save(nextFile)
|
|
349
420
|
}
|
|
350
421
|
|
|
351
422
|
/** Resolve a transient managedKeyId into the host's existing keyPath/passphrase shape. */
|
|
@@ -368,15 +439,21 @@ export class HostStore {
|
|
|
368
439
|
} as T
|
|
369
440
|
}
|
|
370
441
|
|
|
371
|
-
private summarizeKey(key: SshKeyEntry, file: StoreFile): SshKeySummary {
|
|
442
|
+
private summarizeKey(key: SshKeyEntry, file: StoreFile, usedByPath?: Map<string, string[]>): SshKeySummary {
|
|
443
|
+
const resolvedPath = expandHome(key.path)
|
|
444
|
+
const usedBy = usedByPath !== undefined
|
|
445
|
+
? [...(usedByPath.get(resolvedPath) ?? [])]
|
|
446
|
+
: file.hosts
|
|
447
|
+
.filter(host => host.auth.kind === 'key' && host.auth.keyPath !== undefined && host.auth.keyPath !== '' && expandHome(host.auth.keyPath) === resolvedPath)
|
|
448
|
+
.map(host => host.alias)
|
|
372
449
|
return {
|
|
373
450
|
id: key.id,
|
|
374
451
|
name: key.name,
|
|
375
452
|
path: key.path,
|
|
376
453
|
hasPassphrase: key.passphrase !== undefined && key.passphrase !== '',
|
|
377
454
|
note: key.note,
|
|
378
|
-
exists: existsSync(
|
|
379
|
-
usedBy
|
|
455
|
+
exists: existsSync(resolvedPath),
|
|
456
|
+
usedBy,
|
|
380
457
|
createdAt: key.createdAt,
|
|
381
458
|
updatedAt: key.updatedAt,
|
|
382
459
|
}
|
|
@@ -392,25 +469,27 @@ export class HostStore {
|
|
|
392
469
|
* @returns import statistics.
|
|
393
470
|
*/
|
|
394
471
|
importFromSshConfig(): ImportResult {
|
|
395
|
-
// Per-run statistics: a later import must not report earlier runs' skips.
|
|
396
|
-
this.skippedBlocks = []
|
|
397
472
|
const configPath = this.sshConfigOverride ?? sshConfigPath()
|
|
398
473
|
if (!existsSync(configPath)) return { parsed: 0, added: 0, skipped: 0, skippedBlocks: [] }
|
|
399
474
|
const { blocks, skipped } = readSshConfigBlocks(configPath)
|
|
400
|
-
|
|
475
|
+
const skippedBlocks: ImportSkipBlock[] = [...skipped]
|
|
476
|
+
const skippedNames = new Set(skipped.map(block => block.name))
|
|
401
477
|
const skip = (name: string, reason: ImportSkipReason): void => {
|
|
402
|
-
if (name === '') return
|
|
403
|
-
|
|
404
|
-
|
|
478
|
+
if (name === '' || skippedNames.has(name)) return
|
|
479
|
+
skippedNames.add(name)
|
|
480
|
+
skippedBlocks.push({ name, reason })
|
|
405
481
|
}
|
|
406
|
-
|
|
482
|
+
const file = this.load()
|
|
483
|
+
const existingAliases = new Set(file.hosts.map(entry => entry.alias))
|
|
484
|
+
const addedEntries: SshHostEntry[] = []
|
|
485
|
+
const now = Date.now()
|
|
407
486
|
for (const block of blocks) {
|
|
408
487
|
const pattern = block.pattern.split(/\s+/)[0]
|
|
409
488
|
if (pattern.includes('*') || pattern.includes('?')) {
|
|
410
489
|
skip(pattern, 'wildcard')
|
|
411
490
|
continue
|
|
412
491
|
}
|
|
413
|
-
if (
|
|
492
|
+
if (existingAliases.has(pattern)) {
|
|
414
493
|
skip(pattern, 'existing')
|
|
415
494
|
continue
|
|
416
495
|
}
|
|
@@ -447,18 +526,25 @@ export class HostStore {
|
|
|
447
526
|
forwardAgent: parseForwardAgentValue(block.props.forwardagent),
|
|
448
527
|
}
|
|
449
528
|
try {
|
|
450
|
-
|
|
451
|
-
|
|
529
|
+
const entry = buildValidatedHostEntry(payload, now)
|
|
530
|
+
existingAliases.add(entry.alias)
|
|
531
|
+
addedEntries.push(entry)
|
|
452
532
|
} catch {
|
|
453
533
|
// Unusable entry (bad alias grammar, conflicting transports, ...).
|
|
454
534
|
skip(pattern, 'invalid')
|
|
455
535
|
}
|
|
456
536
|
}
|
|
457
|
-
|
|
537
|
+
if (addedEntries.length > 0) {
|
|
538
|
+
const nextFile: StoreFile = {
|
|
539
|
+
version: file.version,
|
|
540
|
+
hosts: [...file.hosts, ...addedEntries],
|
|
541
|
+
...(file.keys !== undefined ? { keys: file.keys } : {}),
|
|
542
|
+
}
|
|
543
|
+
this.save(nextFile)
|
|
544
|
+
}
|
|
545
|
+
return { parsed: blocks.length, added: addedEntries.length, skipped: skippedBlocks.length, skippedBlocks }
|
|
458
546
|
}
|
|
459
547
|
|
|
460
|
-
private skippedBlocks: ImportSkipBlock[] = []
|
|
461
|
-
|
|
462
548
|
/**
|
|
463
549
|
* Last parsed store keyed by file identity. list/find ride every acquire
|
|
464
550
|
* and GUI refresh; re-reading and re-parsing the whole file each call is
|
|
@@ -499,15 +585,33 @@ export class HostStore {
|
|
|
499
585
|
private save(file: StoreFile): void {
|
|
500
586
|
const dir = dirname(this.path)
|
|
501
587
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
502
|
-
const tmp = this.path
|
|
588
|
+
const tmp = `${this.path}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`
|
|
503
589
|
// Secrets live in this file: keep it readable by the owner only. The
|
|
504
590
|
// tmp file carries the 0600 mode through the rename.
|
|
505
|
-
|
|
506
|
-
|
|
591
|
+
try {
|
|
592
|
+
writeFileSync(tmp, JSON.stringify(file, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
|
|
593
|
+
renameSync(tmp, this.path)
|
|
594
|
+
} catch (error) {
|
|
595
|
+
try { unlinkSync(tmp) } catch { /* best effort */ }
|
|
596
|
+
throw error
|
|
597
|
+
}
|
|
507
598
|
this.cache = undefined
|
|
508
599
|
}
|
|
509
600
|
}
|
|
510
601
|
|
|
602
|
+
/** Group aliases by expanded private-key path in a single pass. */
|
|
603
|
+
function buildUsedByPathMap(hosts: readonly SshHostEntry[]): Map<string, string[]> {
|
|
604
|
+
const usedByPath = new Map<string, string[]>()
|
|
605
|
+
for (const host of hosts) {
|
|
606
|
+
if (host.auth.kind !== 'key' || !host.auth.keyPath) continue
|
|
607
|
+
const resolvedPath = expandHome(host.auth.keyPath)
|
|
608
|
+
const existing = usedByPath.get(resolvedPath)
|
|
609
|
+
if (existing === undefined) usedByPath.set(resolvedPath, [host.alias])
|
|
610
|
+
else existing.push(host.alias)
|
|
611
|
+
}
|
|
612
|
+
return usedByPath
|
|
613
|
+
}
|
|
614
|
+
|
|
511
615
|
/** Normalize an agent endpoint for storage: trim, expand `~`, and resolve the SSH_AUTH_SOCK token. */
|
|
512
616
|
export function normalizeAgentPath(agentPath: string | undefined): string | undefined {
|
|
513
617
|
const trimmed = agentPath?.trim()
|