dsh-remote 0.8.92 → 0.8.93

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 (56) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +369 -369
  3. package/README.md +354 -354
  4. package/cordis.patch.yml +9 -9
  5. package/lib/audit.js +45 -45
  6. package/lib/binding.js +172 -172
  7. package/lib/client.js +4647 -4647
  8. package/lib/credential.js +270 -270
  9. package/lib/errors.js +141 -141
  10. package/lib/exec-job.js +242 -242
  11. package/lib/file-reference.js +457 -457
  12. package/lib/forwards.js +258 -258
  13. package/lib/host-api.js +822 -822
  14. package/lib/hostkey.js +108 -108
  15. package/lib/http-transport.js +201 -201
  16. package/lib/ignore.js +202 -202
  17. package/lib/index.js +4488 -4488
  18. package/lib/instructions-dynamic.js +415 -415
  19. package/lib/instructions.js +288 -288
  20. package/lib/open-folder.js +56 -56
  21. package/lib/openssh.js +940 -940
  22. package/lib/paths.js +292 -292
  23. package/lib/pool.js +1029 -1029
  24. package/lib/posix-shell.cjs +34 -34
  25. package/lib/registry.js +296 -296
  26. package/lib/remote-fs.js +173 -173
  27. package/lib/remote-sandbox.js +183 -183
  28. package/lib/remote-shell-child.cjs +397 -397
  29. package/lib/remote-shell.js +697 -697
  30. package/lib/remote-skills.js +312 -312
  31. package/lib/routes-audit.js +58 -58
  32. package/lib/routes-forwards.js +72 -72
  33. package/lib/routes-fs.js +251 -251
  34. package/lib/routes-machines.js +186 -186
  35. package/lib/routes-misc.js +187 -187
  36. package/lib/routes-term.js +169 -169
  37. package/lib/routes-update.js +143 -143
  38. package/lib/routes-web-attach.js +112 -112
  39. package/lib/routes-workspace.js +312 -312
  40. package/lib/search.js +235 -235
  41. package/lib/sftp-surface.js +119 -119
  42. package/lib/sshconfig.js +779 -779
  43. package/lib/sync.js +350 -350
  44. package/lib/tasks.js +95 -95
  45. package/lib/telemetry.js +247 -247
  46. package/lib/terminal.js +205 -205
  47. package/lib/tui/flow.js +130 -130
  48. package/lib/tui/format.js +380 -380
  49. package/lib/tui/i18n.js +350 -350
  50. package/lib/tui/index.js +531 -531
  51. package/lib/tui/provider.js +344 -344
  52. package/lib/tui/scene.js +986 -986
  53. package/lib/update.js +490 -472
  54. package/lib/web-attach.js +860 -860
  55. package/lib/workspace-cleanup.js +337 -337
  56. package/package.json +103 -103
package/lib/credential.js CHANGED
@@ -1,270 +1,270 @@
1
- // dsh-remote — optional OS-keychain password storage.
2
- // Machines keep their password in the OS credential store instead of the
3
- // plaintext machines.json when the user enables "加密保存密码" per machine.
4
- // Every backend is best-effort: any failure resolves to {ok:false} and the
5
- // caller (persistPassword) falls back to plaintext + a user-visible warning
6
- // (the feature must never block connecting, and must never silently drop the
7
- // credential — issue #30).
8
- //
9
- // Backends:
10
- // darwin → `security` (login keychain, generic password)
11
- // win32 → DPAPI via PowerShell (CurrentUser scope), files under
12
- // $DSH_HOME/remote-workspaces/.secrets/
13
- // linux → `secret-tool` (libsecret / gnome-keyring), optional
14
- // else → unsupported (plain)
15
- import { spawn } from 'node:child_process'
16
- import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from 'node:fs'
17
- import { join as joinPath } from 'node:path'
18
-
19
- const SERVICE = 'dsh-remote'
20
- const TIMEOUT = 8000
21
-
22
- // Windows PowerShell 5.1 does not preload System.Security, so
23
- // [System.Security.Cryptography.ProtectedData] is "not found" until the assembly
24
- // is added (issue #30: without this the whole DPAPI call failed and the caller
25
- // silently lost the password). `-ErrorAction SilentlyContinue` keeps the line
26
- // harmless on PowerShell 7, where the type is already available.
27
- const PS_SECURITY_ASSEMBLY = 'Add-Type -AssemblyName System.Security -ErrorAction SilentlyContinue;'
28
-
29
- /**
30
- * Run a helper and resolve with its trimmed stdout.
31
- *
32
- * WHY `spawn` and not `execFile(..., { input })`: measured on a real Ubuntu box
33
- * with a real gnome-keyring, `secret-tool store` given its password through
34
- * `execFile`'s `input` option **never saw EOF**, blocked on the read, and was
35
- * killed by this timeout — so on Linux "encrypt the password" always failed after
36
- * 8 seconds with the useless message "Command failed: secret-tool store …" (empty
37
- * stderr) and the credential was dropped. The same command with an explicitly
38
- * ended stdin (`spawn` + `stdin.end()`, or `sh -c '… < file'`) finishes in ~20ms.
39
- * Nothing in this module needs the extra `execFile` machinery, so stdin is now
40
- * always closed explicitly and the child's stderr is carried on the error (the old
41
- * path dropped it, which is why the failure had no reason attached).
42
- */
43
- function run(bin, args, input) {
44
- return new Promise((resolve, reject) => {
45
- let child
46
- try {
47
- child = spawn(bin, args, { stdio: ['pipe', 'pipe', 'pipe'] })
48
- } catch (err) {
49
- reject(err)
50
- return
51
- }
52
- let out = ''
53
- let errOut = ''
54
- let settled = false
55
- const timer = setTimeout(() => {
56
- if (settled) return
57
- settled = true
58
- try { child.kill('SIGTERM') } catch { /* already gone */ }
59
- const err = new Error(`${bin} timed out after ${TIMEOUT}ms`)
60
- err.stderr = errOut
61
- err.code = 'ETIMEDOUT'
62
- reject(err)
63
- }, TIMEOUT)
64
- const done = (err, value) => {
65
- if (settled) return
66
- settled = true
67
- clearTimeout(timer)
68
- if (err) reject(err); else resolve(value)
69
- }
70
- child.on('error', (err) => done(err))
71
- child.on('close', (code) => {
72
- if (code === 0) return done(null, out.trim())
73
- const err = new Error(`${bin} exited with ${code}${errOut.trim() ? ': ' + errOut.trim().slice(0, 300) : ''}`)
74
- err.code = code
75
- err.stderr = errOut
76
- done(err)
77
- })
78
- child.stdout.on('data', (d) => { out += d })
79
- child.stderr.on('data', (d) => { errOut += d })
80
- // A helper may close its read end before stdin.end() flushes. EPIPE is an
81
- // ASYNC Writable error, so the synchronous try/catch below cannot see it;
82
- // without this listener it becomes an uncaughtException and kills the host.
83
- child.stdin.on('error', (err) => {
84
- try { child.kill('SIGTERM') } catch { /* already gone */ }
85
- done(err)
86
- })
87
- // Always end stdin: a helper that reads a secret from stdin needs EOF, and one
88
- // that does not must not inherit an open pipe.
89
- try { child.stdin.end(input == null ? '' : String(input)) } catch { /* closed early */ }
90
- })
91
- }
92
-
93
- export function platformBackend() {
94
- if (process.platform === 'darwin') return 'keychain'
95
- if (process.platform === 'win32') return 'windows'
96
- return 'secret' // linux (secret-tool may be absent → falls back)
97
- }
98
-
99
- function account(machineId) {
100
- // Only machine ids are stored; sanitize just in case.
101
- return String(machineId || '').replace(/[^a-zA-Z0-9._-]/g, '_')
102
- }
103
-
104
- /** Redact a failed command's diagnostics: execFile puts the FULL command line
105
- * (which carries the password as an argv) into `err.message`, and this string is
106
- * shown in the settings UI — so the secret must never survive it. */
107
- function safeReason(err, password) {
108
- const raw = [err && err.stderr, err && err.message, err && err.code]
109
- .filter(Boolean).map(String).join(' ')
110
- const secret = String(password == null ? '' : password)
111
- const scrubbed = secret ? raw.split(secret).join('***') : raw
112
- return scrubbed.replace(/\s+/g, ' ').trim().slice(0, 300)
113
- }
114
-
115
- /** PowerShell one-liner that DPAPI-protects a password (CurrentUser scope).
116
- * Exported because the issue #30 fix (the mandatory Add-Type preamble) is only
117
- * observable here — a Windows host cannot be exercised from the test suite. */
118
- export function dpapiProtectScript(password) {
119
- return PS_SECURITY_ASSEMBLY +
120
- `$p='${String(password).replace(/'/g, "''")}';` +
121
- `$s=[System.Security.Cryptography.ProtectedData]::Protect([Text.Encoding]::UTF8.GetBytes($p),$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser);` +
122
- `[Convert]::ToBase64String($s)`
123
- }
124
-
125
- /** PowerShell one-liner that reverses dpapiProtectScript(). */
126
- export function dpapiUnprotectScript(b64) {
127
- return PS_SECURITY_ASSEMBLY +
128
- `$s=[Convert]::FromBase64String('${String(b64).replace(/'/g, "''")}');` +
129
- `[Text.Encoding]::UTF8.GetString([System.Security.Cryptography.ProtectedData]::Unprotect($s,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser))`
130
- }
131
-
132
- /** Save a password to the OS store. Resolves {ok, backend, error} — ok:false on
133
- * any failure (caller falls back to plaintext). `error` is a password-free
134
- * diagnostic for the UI. */
135
- export async function saveSecret(machineId, password, secretsDir) {
136
- const acc = account(machineId)
137
- try {
138
- if (process.platform === 'darwin') {
139
- await run('security', ['add-generic-password', '-U', '-s', SERVICE, '-a', acc, '-w', String(password)])
140
- return { ok: true, backend: 'keychain', error: '' }
141
- }
142
- if (process.platform === 'win32') {
143
- // DPAPI-encrypt and store under the harness home.
144
- const script = dpapiProtectScript(password)
145
- const b64 = await run('powershell', ['-NoProfile', '-STA', '-Command', script])
146
- if (!b64) return { ok: false, backend: 'windows', error: 'DPAPI returned no ciphertext' }
147
- mkdirSync(secretsDir || '.', { recursive: true })
148
- writeFileSync(joinPath(secretsDir || '.', acc + '.bin'), b64, 'utf8')
149
- return { ok: true, backend: 'windows', error: '' }
150
- }
151
- if (process.platform === 'linux') {
152
- await run('secret-tool', ['store', '--label=' + SERVICE, 'service', SERVICE, 'account', acc], String(password) + '\n')
153
- return { ok: true, backend: 'secret', error: '' }
154
- }
155
- } catch (err) {
156
- return { ok: false, backend: platformBackend(), error: safeReason(err, password) || 'secret store write failed' }
157
- }
158
- return { ok: false, backend: platformBackend(), error: `unsupported platform: ${process.platform}` }
159
- }
160
-
161
- /** Decide where a machine password is persisted (issue #30).
162
- *
163
- * The contract the settings UI relies on: a password is NEVER silently dropped.
164
- * Historically that guarantee was upheld by falling back to PLAINTEXT in
165
- * machines.json, which is a bad trade in one specific way: the user asked for
166
- * encryption, the store failed, and the secret ended up less protected than if
167
- * they had never asked. Worse, a locked keychain / missing secret-tool is
168
- * exactly the moment when quietly writing a password to a world-readable file
169
- * on disk is most likely to go unnoticed.
170
- *
171
- * So the fallback is a POLICY, not a fixed behaviour (`onStoreFailure`):
172
- *
173
- * `refuse` (default) — do not store the password at all. The machine is
174
- * saved WITHOUT a credential and the caller reports how to fix the
175
- * store; the user retypes (or connects) and nothing lands in
176
- * plaintext by accident. `stored: 'none'` makes that explicit.
177
- * `plain` — the legacy behaviour: write it to machines.json and raise
178
- * `warning: 'secret-store-failed'`. Opt-in only, for users who
179
- * genuinely prefer a working machine over the storage guarantee.
180
- *
181
- * An explicit `backend: 'plain'` still means plain by REQUEST (the user turned
182
- * encryption off), and is unaffected by this policy.
183
- *
184
- * `save` is injectable so both paths are unit-testable on any platform.
185
- *
186
- * @param {object} arg
187
- * @param {string} arg.backend - the platform backend name ('keychain'|'windows'|'secret'|'plain').
188
- * @param {string} arg.machineId
189
- * @param {string} arg.password
190
- * @param {string} [arg.secretsDir]
191
- * @param {'refuse'|'plain'} [arg.onStoreFailure] - see above.
192
- * @param {Function} [arg.save] - injectable secure-store writer.
193
- * @returns {Promise<{stored:'secret'|'plain'|'none', credentialBackend:string, password:string, warning:string, error:string}>}
194
- */
195
- export async function persistPassword({
196
- backend, machineId, password, secretsDir,
197
- onStoreFailure = 'refuse',
198
- save = saveSecret,
199
- }) {
200
- const pw = password == null ? '' : String(password)
201
- const want = backend && backend !== 'plain' ? backend : 'plain'
202
- if (!pw) return { stored: 'none', credentialBackend: want, password: '', warning: '', error: '' }
203
- if (want === 'plain') return { stored: 'plain', credentialBackend: 'plain', password: pw, warning: '', error: '' }
204
- let res
205
- try {
206
- res = await save(machineId, pw, secretsDir)
207
- } catch (err) {
208
- res = { ok: false, error: safeReason(err, pw) }
209
- }
210
- if (res && res.ok) {
211
- return { stored: 'secret', credentialBackend: res.backend || want, password: '', warning: '', error: '' }
212
- }
213
- const error = String((res && res.error) || '') || 'secret store write failed'
214
- if (onStoreFailure === 'plain') {
215
- return {
216
- stored: 'plain',
217
- credentialBackend: 'plain',
218
- password: pw,
219
- warning: 'secret-store-failed',
220
- error,
221
- }
222
- }
223
- // Default: refuse. Nothing is written, and the caller surfaces the store
224
- // failure plus the platform-specific repair hint instead of a silent downgrade.
225
- return {
226
- stored: 'none',
227
- credentialBackend: want,
228
- password: '',
229
- warning: 'secret-store-refused',
230
- error,
231
- }
232
- }
233
-
234
- /** Fetch a stored password. Resolves string|null. */
235
- export async function getSecret(machineId, secretsDir) {
236
- const acc = account(machineId)
237
- try {
238
- if (process.platform === 'darwin') {
239
- return await run('security', ['find-generic-password', '-s', SERVICE, '-a', acc, '-w'])
240
- }
241
- if (process.platform === 'win32') {
242
- const b64 = readFileSync(joinPath(secretsDir || '.', acc + '.bin'), 'utf8').trim()
243
- if (!b64) return null
244
- const script = dpapiUnprotectScript(b64)
245
- return await run('powershell', ['-NoProfile', '-STA', '-Command', script])
246
- }
247
- if (process.platform === 'linux') {
248
- return await run('secret-tool', ['lookup', 'service', SERVICE, 'account', acc])
249
- }
250
- } catch { /* fall through */ }
251
- return null
252
- }
253
-
254
- /** Delete a stored password (idempotent). */
255
- export async function deleteSecret(machineId, secretsDir) {
256
- const acc = account(machineId)
257
- try {
258
- if (process.platform === 'darwin') {
259
- await run('security', ['delete-generic-password', '-s', SERVICE, '-a', acc]).catch(() => {})
260
- return
261
- }
262
- if (process.platform === 'win32') {
263
- try { unlinkSync(joinPath(secretsDir || '.', acc + '.bin')) } catch { /* absent */ }
264
- return
265
- }
266
- if (process.platform === 'linux') {
267
- await run('secret-tool', ['clear', 'service', SERVICE, 'account', acc]).catch(() => {})
268
- }
269
- } catch { /* best effort */ }
270
- }
1
+ // dsh-remote — optional OS-keychain password storage.
2
+ // Machines keep their password in the OS credential store instead of the
3
+ // plaintext machines.json when the user enables "加密保存密码" per machine.
4
+ // Every backend is best-effort: any failure resolves to {ok:false} and the
5
+ // caller (persistPassword) falls back to plaintext + a user-visible warning
6
+ // (the feature must never block connecting, and must never silently drop the
7
+ // credential — issue #30).
8
+ //
9
+ // Backends:
10
+ // darwin → `security` (login keychain, generic password)
11
+ // win32 → DPAPI via PowerShell (CurrentUser scope), files under
12
+ // $DSH_HOME/remote-workspaces/.secrets/
13
+ // linux → `secret-tool` (libsecret / gnome-keyring), optional
14
+ // else → unsupported (plain)
15
+ import { spawn } from 'node:child_process'
16
+ import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from 'node:fs'
17
+ import { join as joinPath } from 'node:path'
18
+
19
+ const SERVICE = 'dsh-remote'
20
+ const TIMEOUT = 8000
21
+
22
+ // Windows PowerShell 5.1 does not preload System.Security, so
23
+ // [System.Security.Cryptography.ProtectedData] is "not found" until the assembly
24
+ // is added (issue #30: without this the whole DPAPI call failed and the caller
25
+ // silently lost the password). `-ErrorAction SilentlyContinue` keeps the line
26
+ // harmless on PowerShell 7, where the type is already available.
27
+ const PS_SECURITY_ASSEMBLY = 'Add-Type -AssemblyName System.Security -ErrorAction SilentlyContinue;'
28
+
29
+ /**
30
+ * Run a helper and resolve with its trimmed stdout.
31
+ *
32
+ * WHY `spawn` and not `execFile(..., { input })`: measured on a real Ubuntu box
33
+ * with a real gnome-keyring, `secret-tool store` given its password through
34
+ * `execFile`'s `input` option **never saw EOF**, blocked on the read, and was
35
+ * killed by this timeout — so on Linux "encrypt the password" always failed after
36
+ * 8 seconds with the useless message "Command failed: secret-tool store …" (empty
37
+ * stderr) and the credential was dropped. The same command with an explicitly
38
+ * ended stdin (`spawn` + `stdin.end()`, or `sh -c '… < file'`) finishes in ~20ms.
39
+ * Nothing in this module needs the extra `execFile` machinery, so stdin is now
40
+ * always closed explicitly and the child's stderr is carried on the error (the old
41
+ * path dropped it, which is why the failure had no reason attached).
42
+ */
43
+ function run(bin, args, input) {
44
+ return new Promise((resolve, reject) => {
45
+ let child
46
+ try {
47
+ child = spawn(bin, args, { stdio: ['pipe', 'pipe', 'pipe'] })
48
+ } catch (err) {
49
+ reject(err)
50
+ return
51
+ }
52
+ let out = ''
53
+ let errOut = ''
54
+ let settled = false
55
+ const timer = setTimeout(() => {
56
+ if (settled) return
57
+ settled = true
58
+ try { child.kill('SIGTERM') } catch { /* already gone */ }
59
+ const err = new Error(`${bin} timed out after ${TIMEOUT}ms`)
60
+ err.stderr = errOut
61
+ err.code = 'ETIMEDOUT'
62
+ reject(err)
63
+ }, TIMEOUT)
64
+ const done = (err, value) => {
65
+ if (settled) return
66
+ settled = true
67
+ clearTimeout(timer)
68
+ if (err) reject(err); else resolve(value)
69
+ }
70
+ child.on('error', (err) => done(err))
71
+ child.on('close', (code) => {
72
+ if (code === 0) return done(null, out.trim())
73
+ const err = new Error(`${bin} exited with ${code}${errOut.trim() ? ': ' + errOut.trim().slice(0, 300) : ''}`)
74
+ err.code = code
75
+ err.stderr = errOut
76
+ done(err)
77
+ })
78
+ child.stdout.on('data', (d) => { out += d })
79
+ child.stderr.on('data', (d) => { errOut += d })
80
+ // A helper may close its read end before stdin.end() flushes. EPIPE is an
81
+ // ASYNC Writable error, so the synchronous try/catch below cannot see it;
82
+ // without this listener it becomes an uncaughtException and kills the host.
83
+ child.stdin.on('error', (err) => {
84
+ try { child.kill('SIGTERM') } catch { /* already gone */ }
85
+ done(err)
86
+ })
87
+ // Always end stdin: a helper that reads a secret from stdin needs EOF, and one
88
+ // that does not must not inherit an open pipe.
89
+ try { child.stdin.end(input == null ? '' : String(input)) } catch { /* closed early */ }
90
+ })
91
+ }
92
+
93
+ export function platformBackend() {
94
+ if (process.platform === 'darwin') return 'keychain'
95
+ if (process.platform === 'win32') return 'windows'
96
+ return 'secret' // linux (secret-tool may be absent → falls back)
97
+ }
98
+
99
+ function account(machineId) {
100
+ // Only machine ids are stored; sanitize just in case.
101
+ return String(machineId || '').replace(/[^a-zA-Z0-9._-]/g, '_')
102
+ }
103
+
104
+ /** Redact a failed command's diagnostics: execFile puts the FULL command line
105
+ * (which carries the password as an argv) into `err.message`, and this string is
106
+ * shown in the settings UI — so the secret must never survive it. */
107
+ function safeReason(err, password) {
108
+ const raw = [err && err.stderr, err && err.message, err && err.code]
109
+ .filter(Boolean).map(String).join(' ')
110
+ const secret = String(password == null ? '' : password)
111
+ const scrubbed = secret ? raw.split(secret).join('***') : raw
112
+ return scrubbed.replace(/\s+/g, ' ').trim().slice(0, 300)
113
+ }
114
+
115
+ /** PowerShell one-liner that DPAPI-protects a password (CurrentUser scope).
116
+ * Exported because the issue #30 fix (the mandatory Add-Type preamble) is only
117
+ * observable here — a Windows host cannot be exercised from the test suite. */
118
+ export function dpapiProtectScript(password) {
119
+ return PS_SECURITY_ASSEMBLY +
120
+ `$p='${String(password).replace(/'/g, "''")}';` +
121
+ `$s=[System.Security.Cryptography.ProtectedData]::Protect([Text.Encoding]::UTF8.GetBytes($p),$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser);` +
122
+ `[Convert]::ToBase64String($s)`
123
+ }
124
+
125
+ /** PowerShell one-liner that reverses dpapiProtectScript(). */
126
+ export function dpapiUnprotectScript(b64) {
127
+ return PS_SECURITY_ASSEMBLY +
128
+ `$s=[Convert]::FromBase64String('${String(b64).replace(/'/g, "''")}');` +
129
+ `[Text.Encoding]::UTF8.GetString([System.Security.Cryptography.ProtectedData]::Unprotect($s,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser))`
130
+ }
131
+
132
+ /** Save a password to the OS store. Resolves {ok, backend, error} — ok:false on
133
+ * any failure (caller falls back to plaintext). `error` is a password-free
134
+ * diagnostic for the UI. */
135
+ export async function saveSecret(machineId, password, secretsDir) {
136
+ const acc = account(machineId)
137
+ try {
138
+ if (process.platform === 'darwin') {
139
+ await run('security', ['add-generic-password', '-U', '-s', SERVICE, '-a', acc, '-w', String(password)])
140
+ return { ok: true, backend: 'keychain', error: '' }
141
+ }
142
+ if (process.platform === 'win32') {
143
+ // DPAPI-encrypt and store under the harness home.
144
+ const script = dpapiProtectScript(password)
145
+ const b64 = await run('powershell', ['-NoProfile', '-STA', '-Command', script])
146
+ if (!b64) return { ok: false, backend: 'windows', error: 'DPAPI returned no ciphertext' }
147
+ mkdirSync(secretsDir || '.', { recursive: true })
148
+ writeFileSync(joinPath(secretsDir || '.', acc + '.bin'), b64, 'utf8')
149
+ return { ok: true, backend: 'windows', error: '' }
150
+ }
151
+ if (process.platform === 'linux') {
152
+ await run('secret-tool', ['store', '--label=' + SERVICE, 'service', SERVICE, 'account', acc], String(password) + '\n')
153
+ return { ok: true, backend: 'secret', error: '' }
154
+ }
155
+ } catch (err) {
156
+ return { ok: false, backend: platformBackend(), error: safeReason(err, password) || 'secret store write failed' }
157
+ }
158
+ return { ok: false, backend: platformBackend(), error: `unsupported platform: ${process.platform}` }
159
+ }
160
+
161
+ /** Decide where a machine password is persisted (issue #30).
162
+ *
163
+ * The contract the settings UI relies on: a password is NEVER silently dropped.
164
+ * Historically that guarantee was upheld by falling back to PLAINTEXT in
165
+ * machines.json, which is a bad trade in one specific way: the user asked for
166
+ * encryption, the store failed, and the secret ended up less protected than if
167
+ * they had never asked. Worse, a locked keychain / missing secret-tool is
168
+ * exactly the moment when quietly writing a password to a world-readable file
169
+ * on disk is most likely to go unnoticed.
170
+ *
171
+ * So the fallback is a POLICY, not a fixed behaviour (`onStoreFailure`):
172
+ *
173
+ * `refuse` (default) — do not store the password at all. The machine is
174
+ * saved WITHOUT a credential and the caller reports how to fix the
175
+ * store; the user retypes (or connects) and nothing lands in
176
+ * plaintext by accident. `stored: 'none'` makes that explicit.
177
+ * `plain` — the legacy behaviour: write it to machines.json and raise
178
+ * `warning: 'secret-store-failed'`. Opt-in only, for users who
179
+ * genuinely prefer a working machine over the storage guarantee.
180
+ *
181
+ * An explicit `backend: 'plain'` still means plain by REQUEST (the user turned
182
+ * encryption off), and is unaffected by this policy.
183
+ *
184
+ * `save` is injectable so both paths are unit-testable on any platform.
185
+ *
186
+ * @param {object} arg
187
+ * @param {string} arg.backend - the platform backend name ('keychain'|'windows'|'secret'|'plain').
188
+ * @param {string} arg.machineId
189
+ * @param {string} arg.password
190
+ * @param {string} [arg.secretsDir]
191
+ * @param {'refuse'|'plain'} [arg.onStoreFailure] - see above.
192
+ * @param {Function} [arg.save] - injectable secure-store writer.
193
+ * @returns {Promise<{stored:'secret'|'plain'|'none', credentialBackend:string, password:string, warning:string, error:string}>}
194
+ */
195
+ export async function persistPassword({
196
+ backend, machineId, password, secretsDir,
197
+ onStoreFailure = 'refuse',
198
+ save = saveSecret,
199
+ }) {
200
+ const pw = password == null ? '' : String(password)
201
+ const want = backend && backend !== 'plain' ? backend : 'plain'
202
+ if (!pw) return { stored: 'none', credentialBackend: want, password: '', warning: '', error: '' }
203
+ if (want === 'plain') return { stored: 'plain', credentialBackend: 'plain', password: pw, warning: '', error: '' }
204
+ let res
205
+ try {
206
+ res = await save(machineId, pw, secretsDir)
207
+ } catch (err) {
208
+ res = { ok: false, error: safeReason(err, pw) }
209
+ }
210
+ if (res && res.ok) {
211
+ return { stored: 'secret', credentialBackend: res.backend || want, password: '', warning: '', error: '' }
212
+ }
213
+ const error = String((res && res.error) || '') || 'secret store write failed'
214
+ if (onStoreFailure === 'plain') {
215
+ return {
216
+ stored: 'plain',
217
+ credentialBackend: 'plain',
218
+ password: pw,
219
+ warning: 'secret-store-failed',
220
+ error,
221
+ }
222
+ }
223
+ // Default: refuse. Nothing is written, and the caller surfaces the store
224
+ // failure plus the platform-specific repair hint instead of a silent downgrade.
225
+ return {
226
+ stored: 'none',
227
+ credentialBackend: want,
228
+ password: '',
229
+ warning: 'secret-store-refused',
230
+ error,
231
+ }
232
+ }
233
+
234
+ /** Fetch a stored password. Resolves string|null. */
235
+ export async function getSecret(machineId, secretsDir) {
236
+ const acc = account(machineId)
237
+ try {
238
+ if (process.platform === 'darwin') {
239
+ return await run('security', ['find-generic-password', '-s', SERVICE, '-a', acc, '-w'])
240
+ }
241
+ if (process.platform === 'win32') {
242
+ const b64 = readFileSync(joinPath(secretsDir || '.', acc + '.bin'), 'utf8').trim()
243
+ if (!b64) return null
244
+ const script = dpapiUnprotectScript(b64)
245
+ return await run('powershell', ['-NoProfile', '-STA', '-Command', script])
246
+ }
247
+ if (process.platform === 'linux') {
248
+ return await run('secret-tool', ['lookup', 'service', SERVICE, 'account', acc])
249
+ }
250
+ } catch { /* fall through */ }
251
+ return null
252
+ }
253
+
254
+ /** Delete a stored password (idempotent). */
255
+ export async function deleteSecret(machineId, secretsDir) {
256
+ const acc = account(machineId)
257
+ try {
258
+ if (process.platform === 'darwin') {
259
+ await run('security', ['delete-generic-password', '-s', SERVICE, '-a', acc]).catch(() => {})
260
+ return
261
+ }
262
+ if (process.platform === 'win32') {
263
+ try { unlinkSync(joinPath(secretsDir || '.', acc + '.bin')) } catch { /* absent */ }
264
+ return
265
+ }
266
+ if (process.platform === 'linux') {
267
+ await run('secret-tool', ['clear', 'service', SERVICE, 'account', acc]).catch(() => {})
268
+ }
269
+ } catch { /* best effort */ }
270
+ }