dsh-ssh-hub 0.0.0-stage → 0.1.9

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 (129) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +255 -2
  3. package/cordis.patch.yml +16 -0
  4. package/icon.svg +3 -0
  5. package/lib/client.js +13766 -0
  6. package/lib/index.js +6727 -0
  7. package/lib/types/activity/history.d.ts +50 -0
  8. package/lib/types/alerting/notify.d.ts +89 -0
  9. package/lib/types/alerting/prompt-summary.d.ts +28 -0
  10. package/lib/types/alerting/rules.d.ts +135 -0
  11. package/lib/types/alerting/tools.d.ts +30 -0
  12. package/lib/types/audit/audit-log.d.ts +84 -0
  13. package/lib/types/audit/recorder.d.ts +50 -0
  14. package/lib/types/client/api.d.ts +199 -0
  15. package/lib/types/client/index.d.ts +45 -0
  16. package/lib/types/client/locales.d.ts +309 -0
  17. package/lib/types/client/native-panel.d.ts +70 -0
  18. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  19. package/lib/types/client/panel/DeployTab.d.ts +10 -0
  20. package/lib/types/client/panel/FleetTab.d.ts +10 -0
  21. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  22. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  23. package/lib/types/client/panel/LogsTab.d.ts +10 -0
  24. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  25. package/lib/types/client/panel/TerminalTab.d.ts +27 -0
  26. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  27. package/lib/types/client/panel/TunnelsTab.d.ts +27 -0
  28. package/lib/types/client/panel/controller.d.ts +253 -0
  29. package/lib/types/client/panel/helpers.d.ts +45 -0
  30. package/lib/types/client/panel/tabs.d.ts +62 -0
  31. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  32. package/lib/types/client/settings-binding.d.ts +71 -0
  33. package/lib/types/deploy/orchestrator.d.ts +158 -0
  34. package/lib/types/deploy/tools.d.ts +14 -0
  35. package/lib/types/dsh-home.d.ts +16 -0
  36. package/lib/types/engine/cluster.d.ts +19 -0
  37. package/lib/types/engine/connection-pool.d.ts +183 -0
  38. package/lib/types/engine/proxy-command.d.ts +36 -0
  39. package/lib/types/engine/pty.d.ts +32 -0
  40. package/lib/types/engine/sftp.d.ts +20 -0
  41. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  42. package/lib/types/engine/tunnel-discovery.d.ts +89 -0
  43. package/lib/types/engine/tunnel.d.ts +38 -0
  44. package/lib/types/engine.d.ts +98 -0
  45. package/lib/types/http.d.ts +59 -0
  46. package/lib/types/index.d.ts +128 -0
  47. package/lib/types/inspect/checks.d.ts +118 -0
  48. package/lib/types/inspect/inspection.d.ts +111 -0
  49. package/lib/types/inspect/tools.d.ts +50 -0
  50. package/lib/types/logs/search.d.ts +131 -0
  51. package/lib/types/logs/tools.d.ts +6 -0
  52. package/lib/types/loopback.d.ts +64 -0
  53. package/lib/types/monitor/loop.d.ts +133 -0
  54. package/lib/types/monitor/metrics.d.ts +151 -0
  55. package/lib/types/mount-once.d.ts +55 -0
  56. package/lib/types/protocol.d.ts +518 -0
  57. package/lib/types/routes.d.ts +82 -0
  58. package/lib/types/security/known-hosts.d.ts +153 -0
  59. package/lib/types/security/master-secret.d.ts +157 -0
  60. package/lib/types/security/redact.d.ts +44 -0
  61. package/lib/types/security/secrets.d.ts +70 -0
  62. package/lib/types/ssh-config.d.ts +42 -0
  63. package/lib/types/store.d.ts +183 -0
  64. package/lib/types/tool-surface.d.ts +72 -0
  65. package/lib/types/tools.d.ts +56 -0
  66. package/locale/en.json +6 -0
  67. package/locale/zh.json +6 -0
  68. package/package.json +126 -6
  69. package/src/activity/history.ts +117 -0
  70. package/src/alerting/notify.ts +212 -0
  71. package/src/alerting/prompt-summary.ts +71 -0
  72. package/src/alerting/rules.ts +281 -0
  73. package/src/alerting/tools.ts +263 -0
  74. package/src/audit/audit-log.ts +198 -0
  75. package/src/audit/recorder.ts +73 -0
  76. package/src/client/api.ts +752 -0
  77. package/src/client/css-modules.d.ts +5 -0
  78. package/src/client/index.ts +150 -0
  79. package/src/client/locales.ts +634 -0
  80. package/src/client/native-panel.tsx +141 -0
  81. package/src/client/panel/ClusterTab.tsx +141 -0
  82. package/src/client/panel/DeployTab.tsx +314 -0
  83. package/src/client/panel/FleetTab.tsx +494 -0
  84. package/src/client/panel/HostFormDialog.tsx +289 -0
  85. package/src/client/panel/HostsTab.tsx +395 -0
  86. package/src/client/panel/LogsTab.tsx +208 -0
  87. package/src/client/panel/SshPanel.tsx +105 -0
  88. package/src/client/panel/TerminalTab.tsx +550 -0
  89. package/src/client/panel/TransferTab.tsx +238 -0
  90. package/src/client/panel/TunnelsTab.tsx +306 -0
  91. package/src/client/panel/controller.ts +507 -0
  92. package/src/client/panel/helpers.ts +84 -0
  93. package/src/client/panel/panel.module.css +1712 -0
  94. package/src/client/panel/tabs.ts +52 -0
  95. package/src/client/panel/xterm.css.ts +2 -0
  96. package/src/client/settings-binding.ts +184 -0
  97. package/src/deploy/orchestrator.ts +326 -0
  98. package/src/deploy/tools.ts +225 -0
  99. package/src/dsh-home.ts +42 -0
  100. package/src/engine/cluster.ts +60 -0
  101. package/src/engine/connection-pool.ts +721 -0
  102. package/src/engine/proxy-command.ts +248 -0
  103. package/src/engine/pty.ts +78 -0
  104. package/src/engine/sftp.ts +229 -0
  105. package/src/engine/terminal-sessions.ts +280 -0
  106. package/src/engine/tunnel-discovery.ts +352 -0
  107. package/src/engine/tunnel.ts +205 -0
  108. package/src/engine.ts +187 -0
  109. package/src/http.ts +127 -0
  110. package/src/index.ts +690 -0
  111. package/src/inspect/checks.ts +251 -0
  112. package/src/inspect/inspection.ts +321 -0
  113. package/src/inspect/tools.ts +366 -0
  114. package/src/logs/search.ts +251 -0
  115. package/src/logs/tools.ts +160 -0
  116. package/src/loopback.ts +119 -0
  117. package/src/monitor/loop.ts +265 -0
  118. package/src/monitor/metrics.ts +333 -0
  119. package/src/mount-once.ts +142 -0
  120. package/src/protocol.ts +528 -0
  121. package/src/routes.ts +953 -0
  122. package/src/security/known-hosts.ts +342 -0
  123. package/src/security/master-secret.ts +334 -0
  124. package/src/security/redact.ts +119 -0
  125. package/src/security/secrets.ts +152 -0
  126. package/src/ssh-config.ts +182 -0
  127. package/src/store.ts +757 -0
  128. package/src/tool-surface.ts +96 -0
  129. package/src/tools.ts +517 -0
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Host-key verification against the user's OpenSSH `known_hosts` file.
3
+ *
4
+ * The base plugin never set ssh2's `hostVerifier`, so every connection
5
+ * accepted whatever key the server presented — a real MITM surface on a
6
+ * fleet where one forged connection reaches every host.
7
+ *
8
+ * This module parses `known_hosts` the way OpenSSH does (plain, bracket,
9
+ * wildcard and `@revoked` entries; SHA256 fingerprints) and turns that into
10
+ * the verifier ssh2 calls for each connection.
11
+ *
12
+ * Three policies, selected by configuration:
13
+ * - `off` — no verification (the base plugin's behaviour; the default so
14
+ * an upgrade never locks an existing user out)
15
+ * - `tofu` — trust on first use: an unknown host is recorded and the
16
+ * connection proceeds; a CHANGED key is always refused
17
+ * - `strict` — an unknown host is refused; the user must accept it first
18
+ *
19
+ * A refused connection must explain itself: the message carries the expected
20
+ * fingerprint, the presented one, and the file path, so the user can decide
21
+ * without reading source.
22
+ */
23
+
24
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
25
+ import { homedir } from 'node:os'
26
+ import { dirname, join } from 'node:path'
27
+ import { createHash } from 'node:crypto'
28
+
29
+ /** How a host key is treated when it is not (or is no longer) trusted. */
30
+ export type HostKeyPolicy = 'off' | 'tofu' | 'strict'
31
+
32
+ /** One known_hosts entry, after parsing. */
33
+ interface KnownHostEntry {
34
+ /** Host patterns this entry covers (unhashed). */
35
+ patterns: string[]
36
+ /** True when the original entry used a hashed host name. */
37
+ hashed: boolean
38
+ /** The key type, e.g. `ssh-ed25519`. */
39
+ keyType: string
40
+ /** The base64 key blob — the whole blob, exactly as OpenSSH stores it. */
41
+ key: string
42
+ /** True when the entry was marked `@revoked`. */
43
+ revoked: boolean
44
+ }
45
+
46
+ /** A parsed known_hosts file plus the path it came from. */
47
+ export interface KnownHostsFile {
48
+ path: string
49
+ entries: KnownHostEntry[]
50
+ /** True when the file exists and was read. */
51
+ present: boolean
52
+ }
53
+
54
+ /** The default known_hosts path: `~/.ssh/known_hosts`. */
55
+ export function defaultKnownHostsPath(): string {
56
+ return join(homedir(), '.ssh', 'known_hosts')
57
+ }
58
+
59
+ /**
60
+ * Parse a known_hosts file.
61
+ *
62
+ * Supported forms:
63
+ * - `host-patterns key-type base64 [comment]`
64
+ * - `[host]:port key-type base64 [comment]` (bracket form for non-22 ports)
65
+ * - `@revoked host-patterns key-type base64 [comment]`
66
+ * - hashed host names (`|1|base64|base64`)
67
+ *
68
+ * Lines that do not parse are skipped: OpenSSH itself ignores them, and a
69
+ * single malformed line must not make every other entry unusable.
70
+ *
71
+ * @param path - the file to read.
72
+ * @returns the parsed entries and whether the file was present.
73
+ */
74
+ export function parseKnownHosts(path: string): KnownHostsFile {
75
+ if (!existsSync(path)) return { path, entries: [], present: false }
76
+ let text: string
77
+ try {
78
+ text = readFileSync(path, 'utf8')
79
+ } catch {
80
+ return { path, entries: [], present: false }
81
+ }
82
+ const entries: KnownHostEntry[] = []
83
+ for (const rawLine of text.split(/\r?\n/)) {
84
+ const line = rawLine.trim()
85
+ if (line === '' || line.startsWith('#')) continue
86
+ let rest = line
87
+ let revoked = false
88
+ if (rest.startsWith('@')) {
89
+ const marker = rest.slice(1).split(/\s+/)[0]
90
+ if (marker === 'revoked') {
91
+ revoked = true
92
+ rest = rest.slice(marker.length + 1).trim()
93
+ } else {
94
+ // @cert-authority and other markers are not plain host-key entries.
95
+ continue
96
+ }
97
+ }
98
+ const parts = rest.split(/\s+/)
99
+ if (parts.length < 3) continue
100
+ const [patternsField, keyType, key] = parts
101
+ if (keyType === undefined || key === undefined) continue
102
+ if (keyType.includes('@')) {
103
+ // Certificate authorities: not a plain host key entry.
104
+ continue
105
+ }
106
+ const hashed = patternsField.startsWith('|1|')
107
+ entries.push({
108
+ patterns: patternsField.split(',').map(pattern => pattern.trim()).filter(pattern => pattern !== ''),
109
+ hashed,
110
+ keyType,
111
+ key,
112
+ revoked,
113
+ })
114
+ }
115
+ return { path, entries, present: true }
116
+ }
117
+
118
+ /**
119
+ * The SHA256 fingerprint OpenSSH and ssh2 display for a key.
120
+ *
121
+ * OpenSSH hashes the **whole key blob** — the same bytes base64-encoded in
122
+ * a known_hosts line — so this hashes the decoded blob directly.
123
+ *
124
+ * @param key - the base64 key blob.
125
+ * @returns the `SHA256:...` fingerprint, base64 without padding.
126
+ */
127
+ export function fingerprint(key: string): string {
128
+ const digest = createHash('sha256').update(decodeBase64(key)).digest('base64')
129
+ return 'SHA256:' + digest.replace(/=+$/, '')
130
+ }
131
+
132
+ /** Decode base64, tolerating whitespace. */
133
+ function decodeBase64(value: string): Buffer {
134
+ return Buffer.from(value.replace(/\s+/g, ''), 'base64')
135
+ }
136
+
137
+ /**
138
+ * Does one pattern match one host?
139
+ *
140
+ * Supports the exact form, the `*` / `?` wildcards OpenSSH accepts, and the
141
+ * bracketed `[host]:port` form.
142
+ */
143
+ function patternMatches(pattern: string, host: string, port: number): boolean {
144
+ // The pattern's host part — the part a wildcard can apply to.
145
+ let candidate: string
146
+ if (pattern.startsWith('[')) {
147
+ // The bracketed form is port-specific: `[host]:port`. It ends with the
148
+ // port, not with `]`, so the closing bracket is followed by `:port`.
149
+ const closing = pattern.indexOf(']')
150
+ if (closing === -1) return false
151
+ const inner = pattern.slice(1, closing)
152
+ const remainder = pattern.slice(closing + 1)
153
+ if (remainder !== '') {
154
+ if (!remainder.startsWith(':')) return false
155
+ const portText = remainder.slice(1)
156
+ if (Number.parseInt(portText, 10) !== port) return false
157
+ }
158
+ candidate = inner
159
+ } else if (pattern.includes(':')) {
160
+ // The plain `host:port` form.
161
+ const separator = pattern.lastIndexOf(':')
162
+ const portText = pattern.slice(separator + 1)
163
+ if (Number.parseInt(portText, 10) !== port) return false
164
+ candidate = pattern.slice(0, separator)
165
+ } else {
166
+ candidate = pattern
167
+ }
168
+ if (candidate === host) return true
169
+ if (!candidate.includes('*') && !candidate.includes('?')) return false
170
+ const escaped = candidate.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
171
+ return new RegExp('^' + escaped + '$').test(host)
172
+ }
173
+
174
+ /**
175
+ * Find the known_hosts entries that cover one host:port.
176
+ *
177
+ * @param file - the parsed file.
178
+ * @param host - the hostname or address.
179
+ * @param port - the SSH port.
180
+ * @returns every covering entry, revoked ones included.
181
+ */
182
+ export function entriesFor(file: KnownHostsFile, host: string, port: number): KnownHostEntry[] {
183
+ return file.entries.filter(entry => entry.patterns.some(pattern => {
184
+ if (entry.hashed) {
185
+ // A hashed host name is HMAC-SHA1 over the host name; verifying it
186
+ // would need the salt and the same key OpenSSH uses. Such an entry is
187
+ // therefore not consulted here, and the host reads as unknown.
188
+ return false
189
+ }
190
+ return patternMatches(pattern, host, port)
191
+ }))
192
+ }
193
+
194
+ /** The outcome of a host-key check. */
195
+ export type HostKeyDecision =
196
+ /** The key matches a trusted entry. */
197
+ | { action: 'accept' }
198
+ /** The key is unknown; `fingerprint` is the one the server presented. */
199
+ | { action: 'unknown'; fingerprint: string }
200
+ /** The key differs from the trusted one — a possible MITM. */
201
+ | { action: 'mismatch'; expected: string; received: string; path: string }
202
+ /** The trusted entry is marked `@revoked`. */
203
+ | { action: 'revoked'; fingerprint: string; path: string }
204
+
205
+ /**
206
+ * Decide what to do with a presented host key.
207
+ *
208
+ * @param file - the parsed known_hosts file.
209
+ * @param host - the hostname or address.
210
+ * @param port - the SSH port.
211
+ * @param keyType - the presented key type.
212
+ * @param presentedKey - the presented key blob (base64).
213
+ * @returns the decision.
214
+ */
215
+ export function decide(
216
+ file: KnownHostsFile,
217
+ host: string,
218
+ port: number,
219
+ keyType: string,
220
+ presentedKey: string,
221
+ ): HostKeyDecision {
222
+ const presented = fingerprint(presentedKey)
223
+ const covering = entriesFor(file, host, port)
224
+ if (covering.length === 0) return { action: 'unknown', fingerprint: presented }
225
+ // A revoked entry for this key is refused outright, whatever else is
226
+ // registered for the host.
227
+ const revoked = covering.find(entry => entry.revoked && entry.keyType === keyType && entry.key === presentedKey)
228
+ if (revoked !== undefined) return { action: 'revoked', fingerprint: presented, path: file.path }
229
+ const trusted = covering.find(entry => !entry.revoked && entry.keyType === keyType && entry.key === presentedKey)
230
+ if (trusted !== undefined) return { action: 'accept' }
231
+ // The host is known but with a different key of the same type — the case
232
+ // that matters for MITM. Report the fingerprint the file expects.
233
+ const sameType = covering.find(entry => !entry.revoked && entry.keyType === keyType)
234
+ if (sameType !== undefined) {
235
+ return {
236
+ action: 'mismatch',
237
+ expected: fingerprint(sameType.key),
238
+ received: presented,
239
+ path: file.path,
240
+ }
241
+ }
242
+ return { action: 'unknown', fingerprint: presented }
243
+ }
244
+
245
+ /** The host-key verification state handed to ssh2. */
246
+ export interface HostKeyVerifierOptions {
247
+ /** The policy in force. */
248
+ policy: HostKeyPolicy
249
+ /** The known_hosts file path. */
250
+ path: string
251
+ /** The host this verifier is bound to (ssh2 passes only the key). */
252
+ host: string
253
+ /** The port this verifier is bound to. */
254
+ port: number
255
+ /** Called when an unknown host must be recorded (TOFU). */
256
+ onRecord?: (host: string, port: number, keyType: string, key: string) => void
257
+ }
258
+
259
+ /**
260
+ * Build the ssh2 `hostVerifier` callback for one connection.
261
+ *
262
+ * ssh2 calls it with the server's key blob; returning a boolean accepts or
263
+ * denies the key (ssh2 also accepts the callback form, but a synchronous
264
+ * verdict cannot half-apply). The verifier reads the file on every call so
265
+ * an edit made outside this plugin — a manual `ssh` session, another tool —
266
+ * takes effect on the next connection.
267
+ *
268
+ * @param options - the policy, file path and the connection's host/port.
269
+ * @returns the verifier callback.
270
+ */
271
+ export function createHostVerifier(options: HostKeyVerifierOptions): (key: Buffer) => boolean {
272
+ return (key: Buffer): boolean => {
273
+ try {
274
+ const file = parseKnownHosts(options.path)
275
+ const { keyType, key: material } = decodeServerKey(key)
276
+ const decision = decide(file, options.host, options.port, keyType, material)
277
+ switch (decision.action) {
278
+ case 'accept':
279
+ return true
280
+ case 'unknown':
281
+ if (options.policy === 'strict') return false
282
+ if (options.policy === 'tofu') {
283
+ options.onRecord?.(options.host, options.port, keyType, material)
284
+ }
285
+ return true
286
+ case 'revoked':
287
+ case 'mismatch':
288
+ // A changed or revoked key is refused under EVERY policy: even
289
+ // `off` must not accept a key the user explicitly revoked.
290
+ return false
291
+ }
292
+ } catch {
293
+ // A broken verifier must not become a licence to accept anything:
294
+ // fail closed when the check itself fails.
295
+ return false
296
+ }
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Split an ssh2 host-key blob into its type and the known_hosts key form.
302
+ *
303
+ * ssh2 hands the verifier the blob exactly as the KEX reply carried it
304
+ * (see `kex.js`: `hostPubKey = bufferParser.readString()`), whose wire form is
305
+ *
306
+ * uint32 len | keyType | uint32 len | keyMaterial
307
+ *
308
+ * A known_hosts line stores the very same bytes — the SSH public-key blob
309
+ * `string(keyType) || string(keyMaterial)` — base64-encoded. So the known_hosts
310
+ * form is the KEX blob verbatim; no re-prefixing happens here.
311
+ */
312
+ function decodeServerKey(blob: Buffer): { keyType: string; key: string } {
313
+ let offset = 0
314
+ const readString = (): string => {
315
+ const length = blob.readUInt32BE(offset)
316
+ offset += 4
317
+ const value = blob.subarray(offset, offset + length).toString('utf8')
318
+ offset += length
319
+ return value
320
+ }
321
+ const keyType = readString()
322
+ return { keyType, key: blob.toString('base64') }
323
+ }
324
+
325
+ /**
326
+ * Record a trusted host key in the known_hosts file.
327
+ *
328
+ * @param path - the file to append to.
329
+ * @param host - the hostname or address.
330
+ * @param port - the SSH port.
331
+ * @param keyType - the key type.
332
+ * @param key - the base64 key blob.
333
+ */
334
+ export function recordKnownHost(path: string, host: string, port: number, keyType: string, key: string): void {
335
+ const label = port === 22 ? host : `[${host}]:${port}`
336
+ const line = `${label} ${keyType} ${key}\n`
337
+ const dir = dirname(path)
338
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
339
+ // The file holds public keys only, but it is still the user's SSH trust
340
+ // store: keep it owner-readable.
341
+ writeFileSync(path, line, { encoding: 'utf8', mode: 0o600, flag: 'a' })
342
+ }
@@ -0,0 +1,334 @@
1
+ /**
2
+ * Master-secret management for the credential envelope.
3
+ *
4
+ * The secret itself lives outside the store on purpose: `DSH_SSH_HUB_SECRET`
5
+ * (environment) or a key file, never inside `dsh-ssh.json`. That means the
6
+ * panel cannot "just set" it — it has to write a file with the right
7
+ * permissions and then re-encrypt every stored entry that was sealed with the
8
+ * previous secret, because a secret change without rotation silently locks
9
+ * the operator out of their own credentials.
10
+ *
11
+ * Three operations, each with the failure mode it refuses:
12
+ *
13
+ * - `status()` — where the secret comes from, if at all.
14
+ * - `setKey()` — write the key file. Refuses to overwrite an existing file
15
+ * that this plugin did not create (a foreign file may be the
16
+ * operator's own keystore), and refuses a weak secret.
17
+ * - `rotate()` — re-seal every entry with the new secret. Runs as one
18
+ * rewrite: entries are re-sealed in memory and written
19
+ * together, so a failure never leaves a half-rotated store.
20
+ *
21
+ * The plaintext side of the tradeoff is explicit: encryption activates only
22
+ * when a secret exists. There is no default, because a default key is a
23
+ * backdoor and every installation would share it.
24
+ */
25
+
26
+ import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'
27
+ import { randomBytes } from 'node:crypto'
28
+ import { dirname, resolve } from 'node:path'
29
+ import type { HostStore } from '../store.ts'
30
+ import { open as openSecret } from './secrets.ts'
31
+
32
+ /** Environment variable that carries the master secret directly. */
33
+ export const SECRET_ENV = 'DSH_SSH_HUB_SECRET'
34
+
35
+ /** Environment variable naming a file that carries the master secret. */
36
+ export const SECRET_FILE_ENV = 'DSH_SSH_HUB_SECRET_FILE'
37
+
38
+ /** Minimum master-secret length. Short secrets are the whole weakness. */
39
+ export const MIN_SECRET_LENGTH = 16
40
+
41
+ /** Where the secret came from. */
42
+ export type SecretSource = 'env' | 'file' | 'none'
43
+
44
+ /** The key-file location this plugin owns. */
45
+ export function defaultKeyPath(dshHome: string): string {
46
+ return resolve(dshHome, 'dsh-ssh-master.key')
47
+ }
48
+
49
+ /**
50
+ * Read the master secret.
51
+ *
52
+ * A file-provided value is trimmed of exactly one trailing newline (a file
53
+ * written by `echo` would otherwise carry an invisible `\n` into the derived
54
+ * key, producing a secret nobody can reproduce by typing it).
55
+ *
56
+ * @param keyPath - the key file to read when the env vars are absent.
57
+ * @returns the secret, or undefined when none is configured.
58
+ */
59
+ export function readMasterSecret(keyPath: string): string | undefined {
60
+ const direct = process.env[SECRET_ENV]
61
+ if (typeof direct === 'string' && direct.length > 0) return direct
62
+ const named = process.env[SECRET_FILE_ENV]
63
+ const path = typeof named === 'string' && named.length > 0 ? named : keyPath
64
+ if (!existsSync(path)) return undefined
65
+ try {
66
+ const text = readFileSync(path, 'utf8').replace(/\r?\n$/, '')
67
+ return text.length > 0 ? text : undefined
68
+ } catch {
69
+ return undefined
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Report where the secret comes from.
75
+ * @param keyPath - the key file to check.
76
+ * @returns the source label.
77
+ */
78
+ export function masterSecretSource(keyPath: string): SecretSource {
79
+ const direct = process.env[SECRET_ENV]
80
+ if (typeof direct === 'string' && direct.length > 0) return 'env'
81
+ const named = process.env[SECRET_FILE_ENV]
82
+ const path = typeof named === 'string' && named.length > 0 ? named : keyPath
83
+ return existsSync(path) ? 'file' : 'none'
84
+ }
85
+
86
+ /** One entry whose stored secrets are still plaintext. */
87
+ export interface PlaintextReport {
88
+ /** Aliases holding a readable plaintext password or passphrase. */
89
+ aliases: string[]
90
+ }
91
+
92
+ /**
93
+ * Does this value look like a sealed envelope rather than a plaintext secret?
94
+ * Mirrors `isSealed` from secrets.ts but stays local so this module has no
95
+ * dependency on the protector's internals.
96
+ */
97
+ function looksSealed(value: unknown): boolean {
98
+ return typeof value === 'object' && value !== null
99
+ && typeof (value as { v?: unknown }).v === 'number'
100
+ && typeof (value as { data?: unknown }).data === 'string'
101
+ }
102
+
103
+ /**
104
+ * Find entries whose secrets would still be readable without the master key.
105
+ *
106
+ * This reads the store file directly, because `HostStore.list()` returns
107
+ * decrypted entries and therefore cannot tell plaintext from ciphertext. The
108
+ * distinction is the whole point: an operator enabling encryption needs to
109
+ * know whether anything is still exposed on disk.
110
+ *
111
+ * @param storePath - the store file path.
112
+ * @returns the aliases whose stored secrets are plaintext.
113
+ */
114
+ export function findPlaintextEntries(storePath: string): PlaintextReport {
115
+ if (!existsSync(storePath)) return { aliases: [] }
116
+ let parsed: unknown
117
+ try {
118
+ parsed = JSON.parse(readFileSync(storePath, 'utf8'))
119
+ } catch {
120
+ return { aliases: [] }
121
+ }
122
+ const hosts = (parsed as { hosts?: unknown }).hosts
123
+ if (!Array.isArray(hosts)) return { aliases: [] }
124
+ const aliases: string[] = []
125
+ for (const host of hosts) {
126
+ const entry = host as { alias?: unknown; auth?: { password?: unknown; passphrase?: unknown } }
127
+ if (typeof entry.alias !== 'string') continue
128
+ const hasPlaintext = [entry.auth?.password, entry.auth?.passphrase]
129
+ .some(value => typeof value === 'string' && value.length > 0)
130
+ if (hasPlaintext) aliases.push(entry.alias)
131
+ }
132
+ return { aliases }
133
+ }
134
+
135
+ /** What a key-file write did. */
136
+ export interface KeyWriteResult {
137
+ ok: boolean
138
+ path: string
139
+ /** Set when the write was refused or failed. */
140
+ error?: string
141
+ }
142
+
143
+ /**
144
+ * Write the master secret to the key file with owner-only permissions.
145
+ *
146
+ * Refusals are deliberate:
147
+ * - a secret shorter than MIN_SECRET_LENGTH is rejected (it would be the only
148
+ * thing standing between a file copy and every credential in it),
149
+ * - an existing file the caller did not create is never overwritten, because
150
+ * it may hold a key the operator is still using,
151
+ * - a file is never left behind half-written.
152
+ *
153
+ * @param keyPath - destination path.
154
+ * @param secret - the new secret.
155
+ * @param overwrite - replace an existing key file (the panel's "rotate").
156
+ * @returns the outcome.
157
+ */
158
+ export function writeMasterKey(keyPath: string, secret: string, overwrite: boolean): KeyWriteResult {
159
+ if (secret.length < MIN_SECRET_LENGTH) {
160
+ return { ok: false, path: keyPath, error: `master secret must be at least ${String(MIN_SECRET_LENGTH)} characters` }
161
+ }
162
+ if (!overwrite && existsSync(keyPath)) {
163
+ return { ok: false, path: keyPath, error: 'a key file already exists at this path; pass overwrite to replace it' }
164
+ }
165
+ try {
166
+ mkdirSync(dirname(keyPath), { recursive: true })
167
+ // 0600: the secret is the only thing protecting every stored credential.
168
+ writeFileSync(keyPath, secret, { encoding: 'utf8', mode: 0o600 })
169
+ // mode on write is subject to the process umask on some platforms.
170
+ chmodSync(keyPath, 0o600)
171
+ return { ok: true, path: keyPath }
172
+ } catch (error) {
173
+ return { ok: false, path: keyPath, error: error instanceof Error ? error.message : String(error) }
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Generate a secret strong enough to be worth using.
179
+ * @returns 32 random bytes, base64url-encoded.
180
+ */
181
+ export function generateSecret(): string {
182
+ return randomBytes(32).toString('base64url')
183
+ }
184
+
185
+ /** Outcome of a rotation. */
186
+ export interface RotateResult {
187
+ ok: boolean
188
+ /** Entries whose secrets were re-sealed. */
189
+ rotated: number
190
+ /** Entries that could not be re-sealed with the previous secret. */
191
+ unreadable: string[]
192
+ error?: string
193
+ }
194
+
195
+ /**
196
+ * Re-encrypt every stored entry under a new master secret.
197
+ *
198
+ * Rotation is the step that makes a secret change safe: entries sealed with
199
+ * the old secret become unreadable the moment the key file changes, so the
200
+ * new key must be in place before the entries are re-sealed, and the entries
201
+ * must have been read while the old key was still live.
202
+ *
203
+ * The order is therefore: read and verify with the old secret → commit the new
204
+ * secret → re-seal in one pass. On a failed re-seal the old key is restored,
205
+ * so the store never ends up sealed under a key that is not on disk.
206
+ *
207
+ * This deliberately does NOT install a protector of its own. The store's
208
+ * protector resolves the secret from disk on every call, so a rotation that
209
+ * handed it a captured secret would pin the store to that secret for the life
210
+ * of the process — after which deleting or rotating the key file would change
211
+ * nothing, and new credentials would be sealed with a key nothing on disk can
212
+ * reproduce.
213
+ *
214
+ * An entry that cannot be decrypted with the old secret is reported, not
215
+ * dropped: it is evidence of a wrong key or a tampered file, and silently
216
+ * deleting it would destroy the operator's only record of that host.
217
+ *
218
+ * @param store - the host store (its protector reads the live secret).
219
+ * @param oldSecret - the secret currently protecting the store.
220
+ * @param newSecret - the secret to protect it with from now on.
221
+ * @param commit - writes the new secret to wherever the protector reads it.
222
+ * @returns the rotation outcome.
223
+ */
224
+ export function rotateSecrets(
225
+ store: HostStore,
226
+ oldSecret: string,
227
+ newSecret: string,
228
+ commit: (secret: string) => KeyWriteResult,
229
+ ): RotateResult {
230
+ if (newSecret.length < MIN_SECRET_LENGTH) {
231
+ return { ok: false, rotated: 0, unreadable: [], error: `master secret must be at least ${String(MIN_SECRET_LENGTH)} characters` }
232
+ }
233
+ // Read while the old secret is still the live one: after the commit below,
234
+ // `store.list()` would return the envelope objects instead of passwords.
235
+ const entries = store.list()
236
+ const unreadable: string[] = []
237
+ for (const entry of entries) {
238
+ const stored = readStoredAuth(store.path, entry.alias)
239
+ if (stored === undefined) continue
240
+ for (const value of [stored.password, stored.passphrase]) {
241
+ if (!looksSealed(value)) continue
242
+ try {
243
+ openSecret(value as never, oldSecret)
244
+ } catch {
245
+ if (!unreadable.includes(entry.alias)) unreadable.push(entry.alias)
246
+ }
247
+ }
248
+ }
249
+ if (unreadable.length > 0) {
250
+ // Nothing has been written: the old key still opens everything, which is
251
+ // the state to leave behind when the requested rotation cannot be proven
252
+ // safe.
253
+ return {
254
+ ok: false,
255
+ rotated: 0,
256
+ unreadable,
257
+ error: `some entries could not be decrypted with the previous secret: ${unreadable.join(', ')}`,
258
+ }
259
+ }
260
+ const committed = commit(newSecret)
261
+ if (!committed.ok) {
262
+ return {
263
+ ok: false,
264
+ rotated: 0,
265
+ unreadable: [],
266
+ error: committed.error ?? 'the new master secret could not be stored',
267
+ }
268
+ }
269
+ try {
270
+ // The protector now reads the new secret, so this seals with it.
271
+ store.resealAll(entries)
272
+ } catch (error) {
273
+ // Put the old key back: the file on disk is still sealed with it, so
274
+ // leaving the new key in place would lock the operator out of every
275
+ // credential at once.
276
+ commit(oldSecret)
277
+ return {
278
+ ok: false,
279
+ rotated: 0,
280
+ unreadable: [],
281
+ error: `re-encrypting the stored credentials failed and the previous key was restored: ${error instanceof Error ? error.message : String(error)}`,
282
+ }
283
+ }
284
+ return { ok: true, rotated: entries.length, unreadable }
285
+ }
286
+
287
+ /**
288
+ * Read one entry's stored (still encrypted or plaintext) auth block.
289
+ * @param storePath - the store file.
290
+ * @param alias - the entry to read.
291
+ * @returns the stored auth block, or undefined when absent.
292
+ */
293
+ export function readStoredAuth(
294
+ storePath: string,
295
+ alias: string,
296
+ ): { password?: unknown; passphrase?: unknown } | undefined {
297
+ if (!existsSync(storePath)) return undefined
298
+ try {
299
+ const parsed = JSON.parse(readFileSync(storePath, 'utf8')) as {
300
+ hosts?: Array<{ alias?: unknown; auth?: { password?: unknown; passphrase?: unknown } }>
301
+ }
302
+ const host = parsed.hosts?.find(entry => entry.alias === alias)
303
+ return host?.auth
304
+ } catch {
305
+ return undefined
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Remove the key file this plugin manages.
311
+ *
312
+ * Refuses when the active secret comes from the environment: deleting a file
313
+ * the environment only *names* would not change the active secret, so the
314
+ * caller would believe encryption was off while it stayed on.
315
+ *
316
+ * @param keyPath - the key file.
317
+ * @returns the outcome.
318
+ */
319
+ export function removeMasterKey(keyPath: string): KeyWriteResult {
320
+ if (typeof process.env[SECRET_ENV] === 'string' && process.env[SECRET_ENV].length > 0) {
321
+ return {
322
+ ok: false,
323
+ path: keyPath,
324
+ error: `${SECRET_ENV} provides the active secret; unset it instead of deleting a file`,
325
+ }
326
+ }
327
+ if (!existsSync(keyPath)) return { ok: true, path: keyPath }
328
+ try {
329
+ unlinkSync(keyPath)
330
+ return { ok: true, path: keyPath }
331
+ } catch (error) {
332
+ return { ok: false, path: keyPath, error: error instanceof Error ? error.message : String(error) }
333
+ }
334
+ }