dsh-remote 0.8.91 → 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 (181) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +369 -368
  3. package/README.md +354 -353
  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 -4550
  8. package/lib/credential.js +270 -263
  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 -4394
  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 -881
  22. package/lib/paths.js +292 -292
  23. package/lib/pool.js +1029 -970
  24. package/lib/posix-shell.cjs +34 -0
  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 -400
  29. package/lib/remote-shell.js +697 -697
  30. package/lib/remote-skills.js +312 -0
  31. package/lib/routes-audit.js +58 -58
  32. package/lib/routes-forwards.js +72 -72
  33. package/lib/routes-fs.js +251 -245
  34. package/lib/routes-machines.js +186 -186
  35. package/lib/routes-misc.js +187 -150
  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 -850
  55. package/lib/workspace-cleanup.js +337 -337
  56. package/package.json +103 -100
  57. package/node_modules/buildcheck/.eslintrc.js +0 -5
  58. package/node_modules/buildcheck/.github/workflows/ci.yml +0 -88
  59. package/node_modules/buildcheck/.github/workflows/lint.yml +0 -27
  60. package/node_modules/buildcheck/.npmignore +0 -3
  61. package/node_modules/buildcheck/LICENSE +0 -19
  62. package/node_modules/buildcheck/README.md +0 -106
  63. package/node_modules/buildcheck/deps/Find-VisualStudio.cs +0 -250
  64. package/node_modules/buildcheck/lib/findvs.js +0 -361
  65. package/node_modules/buildcheck/lib/index.js +0 -738
  66. package/node_modules/buildcheck/package.json +0 -36
  67. package/node_modules/buildcheck/test/test.js +0 -8
  68. package/node_modules/cpu-features/.eslintrc.js +0 -5
  69. package/node_modules/cpu-features/.github/workflows/ci.yml +0 -74
  70. package/node_modules/cpu-features/.github/workflows/lint.yml +0 -27
  71. package/node_modules/cpu-features/LICENSE +0 -19
  72. package/node_modules/cpu-features/README.md +0 -59
  73. package/node_modules/cpu-features/binding.gyp +0 -16
  74. package/node_modules/cpu-features/buildcheck.js +0 -32
  75. package/node_modules/cpu-features/deps/cpu_features/.clang-format +0 -4
  76. package/node_modules/cpu-features/deps/cpu_features/.dockerignore +0 -31
  77. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile +0 -5
  78. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/aarch64_linux_cmake.yml +0 -30
  79. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_freebsd_cmake.yml +0 -22
  80. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_bazel.yml +0 -26
  81. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_cmake.yml +0 -31
  82. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_macos_cmake.yml +0 -43
  83. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_windows_cmake.yml +0 -25
  84. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/arm_linux_cmake.yml +0 -31
  85. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml +0 -24
  86. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/mips_linux_cmake.yml +0 -30
  87. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/power_linux_cmake.yml +0 -29
  88. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/riscv_linux_cmake.yml +0 -28
  89. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/s390x_linux_cmake.yml +0 -27
  90. package/node_modules/cpu-features/deps/cpu_features/.grenrc.yml +0 -21
  91. package/node_modules/cpu-features/deps/cpu_features/BUILD.bazel +0 -329
  92. package/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt +0 -261
  93. package/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md +0 -23
  94. package/node_modules/cpu-features/deps/cpu_features/LICENSE +0 -230
  95. package/node_modules/cpu-features/deps/cpu_features/README.md +0 -272
  96. package/node_modules/cpu-features/deps/cpu_features/WORKSPACE +0 -19
  97. package/node_modules/cpu-features/deps/cpu_features/bazel/ci/README.md +0 -5
  98. package/node_modules/cpu-features/deps/cpu_features/bazel/platforms.bzl +0 -11
  99. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in +0 -3
  100. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in +0 -3
  101. package/node_modules/cpu-features/deps/cpu_features/cmake/README.md +0 -30
  102. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/Makefile +0 -252
  103. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/README.md +0 -40
  104. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.dot +0 -64
  105. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.svg +0 -312
  106. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/generate_image.sh +0 -7
  107. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/amd64/Dockerfile +0 -48
  108. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/toolchain/Dockerfile +0 -34
  109. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/CMakeLists.txt +0 -22
  110. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/main.cpp +0 -11
  111. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/vagrant/freebsd/Vagrantfile +0 -107
  112. package/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in +0 -15
  113. package/node_modules/cpu-features/deps/cpu_features/cpu_features.gyp +0 -105
  114. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h +0 -54
  115. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h +0 -384
  116. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h +0 -259
  117. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h +0 -121
  118. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h +0 -74
  119. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h +0 -149
  120. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_riscv.h +0 -72
  121. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_s390x.h +0 -108
  122. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h +0 -288
  123. package/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h +0 -40
  124. package/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h +0 -37
  125. package/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h +0 -39
  126. package/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h +0 -240
  127. package/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h +0 -49
  128. package/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h +0 -110
  129. package/node_modules/cpu-features/deps/cpu_features/include/internal/windows_utils.h +0 -70
  130. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt +0 -60
  131. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md +0 -4
  132. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c +0 -205
  133. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h +0 -320
  134. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c +0 -12
  135. package/node_modules/cpu-features/deps/cpu_features/patches/0001-Add-Apple-Silicon-Support.patch +0 -456
  136. package/node_modules/cpu-features/deps/cpu_features/scripts/generate_badges.d +0 -165
  137. package/node_modules/cpu-features/deps/cpu_features/scripts/make_release.sh +0 -75
  138. package/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh +0 -490
  139. package/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh +0 -79
  140. package/node_modules/cpu-features/deps/cpu_features/src/copy.inl +0 -19
  141. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection.inl +0 -86
  142. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection_and_hwcaps.inl +0 -26
  143. package/node_modules/cpu-features/deps/cpu_features/src/equals.inl +0 -22
  144. package/node_modules/cpu-features/deps/cpu_features/src/filesystem.c +0 -62
  145. package/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c +0 -169
  146. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64__base_implementation.inl +0 -88
  147. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_linux_or_android.c +0 -79
  148. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_macos_or_iphone.c +0 -82
  149. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_windows.c +0 -138
  150. package/node_modules/cpu-features/deps/cpu_features/src/impl_arm_linux_or_android.c +0 -212
  151. package/node_modules/cpu-features/deps/cpu_features/src/impl_mips_linux_or_android.c +0 -93
  152. package/node_modules/cpu-features/deps/cpu_features/src/impl_ppc_linux.c +0 -163
  153. package/node_modules/cpu-features/deps/cpu_features/src/impl_riscv_linux.c +0 -111
  154. package/node_modules/cpu-features/deps/cpu_features/src/impl_s390x_linux.c +0 -120
  155. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86__base_implementation.inl +0 -2055
  156. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_freebsd.c +0 -68
  157. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_linux_or_android.c +0 -58
  158. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_macos.c +0 -57
  159. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_windows.c +0 -58
  160. package/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c +0 -132
  161. package/node_modules/cpu-features/deps/cpu_features/src/string_view.c +0 -192
  162. package/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c +0 -461
  163. package/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt +0 -114
  164. package/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc +0 -53
  165. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc +0 -396
  166. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc +0 -384
  167. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc +0 -176
  168. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc +0 -131
  169. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_riscv_test.cc +0 -180
  170. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_s390x_test.cc +0 -82
  171. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc +0 -1729
  172. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc +0 -103
  173. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h +0 -61
  174. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc +0 -52
  175. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h +0 -31
  176. package/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc +0 -132
  177. package/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc +0 -202
  178. package/node_modules/cpu-features/lib/index.js +0 -5
  179. package/node_modules/cpu-features/package.json +0 -40
  180. package/node_modules/cpu-features/src/binding.cc +0 -151
  181. package/node_modules/cpu-features/test/test.js +0 -12
package/lib/credential.js CHANGED
@@ -1,263 +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
- // Always end stdin: a helper that reads a secret from stdin needs EOF, and one
81
- // that does not must not inherit an open pipe.
82
- try { child.stdin.end(input == null ? '' : String(input)) } catch { /* closed early */ }
83
- })
84
- }
85
-
86
- export function platformBackend() {
87
- if (process.platform === 'darwin') return 'keychain'
88
- if (process.platform === 'win32') return 'windows'
89
- return 'secret' // linux (secret-tool may be absent → falls back)
90
- }
91
-
92
- function account(machineId) {
93
- // Only machine ids are stored; sanitize just in case.
94
- return String(machineId || '').replace(/[^a-zA-Z0-9._-]/g, '_')
95
- }
96
-
97
- /** Redact a failed command's diagnostics: execFile puts the FULL command line
98
- * (which carries the password as an argv) into `err.message`, and this string is
99
- * shown in the settings UI — so the secret must never survive it. */
100
- function safeReason(err, password) {
101
- const raw = [err && err.stderr, err && err.message, err && err.code]
102
- .filter(Boolean).map(String).join(' ')
103
- const secret = String(password == null ? '' : password)
104
- const scrubbed = secret ? raw.split(secret).join('***') : raw
105
- return scrubbed.replace(/\s+/g, ' ').trim().slice(0, 300)
106
- }
107
-
108
- /** PowerShell one-liner that DPAPI-protects a password (CurrentUser scope).
109
- * Exported because the issue #30 fix (the mandatory Add-Type preamble) is only
110
- * observable here — a Windows host cannot be exercised from the test suite. */
111
- export function dpapiProtectScript(password) {
112
- return PS_SECURITY_ASSEMBLY +
113
- `$p='${String(password).replace(/'/g, "''")}';` +
114
- `$s=[System.Security.Cryptography.ProtectedData]::Protect([Text.Encoding]::UTF8.GetBytes($p),$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser);` +
115
- `[Convert]::ToBase64String($s)`
116
- }
117
-
118
- /** PowerShell one-liner that reverses dpapiProtectScript(). */
119
- export function dpapiUnprotectScript(b64) {
120
- return PS_SECURITY_ASSEMBLY +
121
- `$s=[Convert]::FromBase64String('${String(b64).replace(/'/g, "''")}');` +
122
- `[Text.Encoding]::UTF8.GetString([System.Security.Cryptography.ProtectedData]::Unprotect($s,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser))`
123
- }
124
-
125
- /** Save a password to the OS store. Resolves {ok, backend, error} — ok:false on
126
- * any failure (caller falls back to plaintext). `error` is a password-free
127
- * diagnostic for the UI. */
128
- export async function saveSecret(machineId, password, secretsDir) {
129
- const acc = account(machineId)
130
- try {
131
- if (process.platform === 'darwin') {
132
- await run('security', ['add-generic-password', '-U', '-s', SERVICE, '-a', acc, '-w', String(password)])
133
- return { ok: true, backend: 'keychain', error: '' }
134
- }
135
- if (process.platform === 'win32') {
136
- // DPAPI-encrypt and store under the harness home.
137
- const script = dpapiProtectScript(password)
138
- const b64 = await run('powershell', ['-NoProfile', '-STA', '-Command', script])
139
- if (!b64) return { ok: false, backend: 'windows', error: 'DPAPI returned no ciphertext' }
140
- mkdirSync(secretsDir || '.', { recursive: true })
141
- writeFileSync(joinPath(secretsDir || '.', acc + '.bin'), b64, 'utf8')
142
- return { ok: true, backend: 'windows', error: '' }
143
- }
144
- if (process.platform === 'linux') {
145
- await run('secret-tool', ['store', '--label=' + SERVICE, 'service', SERVICE, 'account', acc], String(password) + '\n')
146
- return { ok: true, backend: 'secret', error: '' }
147
- }
148
- } catch (err) {
149
- return { ok: false, backend: platformBackend(), error: safeReason(err, password) || 'secret store write failed' }
150
- }
151
- return { ok: false, backend: platformBackend(), error: `unsupported platform: ${process.platform}` }
152
- }
153
-
154
- /** Decide where a machine password is persisted (issue #30).
155
- *
156
- * The contract the settings UI relies on: a password is NEVER silently dropped.
157
- * Historically that guarantee was upheld by falling back to PLAINTEXT in
158
- * machines.json, which is a bad trade in one specific way: the user asked for
159
- * encryption, the store failed, and the secret ended up less protected than if
160
- * they had never asked. Worse, a locked keychain / missing secret-tool is
161
- * exactly the moment when quietly writing a password to a world-readable file
162
- * on disk is most likely to go unnoticed.
163
- *
164
- * So the fallback is a POLICY, not a fixed behaviour (`onStoreFailure`):
165
- *
166
- * `refuse` (default) — do not store the password at all. The machine is
167
- * saved WITHOUT a credential and the caller reports how to fix the
168
- * store; the user retypes (or connects) and nothing lands in
169
- * plaintext by accident. `stored: 'none'` makes that explicit.
170
- * `plain` — the legacy behaviour: write it to machines.json and raise
171
- * `warning: 'secret-store-failed'`. Opt-in only, for users who
172
- * genuinely prefer a working machine over the storage guarantee.
173
- *
174
- * An explicit `backend: 'plain'` still means plain by REQUEST (the user turned
175
- * encryption off), and is unaffected by this policy.
176
- *
177
- * `save` is injectable so both paths are unit-testable on any platform.
178
- *
179
- * @param {object} arg
180
- * @param {string} arg.backend - the platform backend name ('keychain'|'windows'|'secret'|'plain').
181
- * @param {string} arg.machineId
182
- * @param {string} arg.password
183
- * @param {string} [arg.secretsDir]
184
- * @param {'refuse'|'plain'} [arg.onStoreFailure] - see above.
185
- * @param {Function} [arg.save] - injectable secure-store writer.
186
- * @returns {Promise<{stored:'secret'|'plain'|'none', credentialBackend:string, password:string, warning:string, error:string}>}
187
- */
188
- export async function persistPassword({
189
- backend, machineId, password, secretsDir,
190
- onStoreFailure = 'refuse',
191
- save = saveSecret,
192
- }) {
193
- const pw = password == null ? '' : String(password)
194
- const want = backend && backend !== 'plain' ? backend : 'plain'
195
- if (!pw) return { stored: 'none', credentialBackend: want, password: '', warning: '', error: '' }
196
- if (want === 'plain') return { stored: 'plain', credentialBackend: 'plain', password: pw, warning: '', error: '' }
197
- let res
198
- try {
199
- res = await save(machineId, pw, secretsDir)
200
- } catch (err) {
201
- res = { ok: false, error: safeReason(err, pw) }
202
- }
203
- if (res && res.ok) {
204
- return { stored: 'secret', credentialBackend: res.backend || want, password: '', warning: '', error: '' }
205
- }
206
- const error = String((res && res.error) || '') || 'secret store write failed'
207
- if (onStoreFailure === 'plain') {
208
- return {
209
- stored: 'plain',
210
- credentialBackend: 'plain',
211
- password: pw,
212
- warning: 'secret-store-failed',
213
- error,
214
- }
215
- }
216
- // Default: refuse. Nothing is written, and the caller surfaces the store
217
- // failure plus the platform-specific repair hint instead of a silent downgrade.
218
- return {
219
- stored: 'none',
220
- credentialBackend: want,
221
- password: '',
222
- warning: 'secret-store-refused',
223
- error,
224
- }
225
- }
226
-
227
- /** Fetch a stored password. Resolves string|null. */
228
- export async function getSecret(machineId, secretsDir) {
229
- const acc = account(machineId)
230
- try {
231
- if (process.platform === 'darwin') {
232
- return await run('security', ['find-generic-password', '-s', SERVICE, '-a', acc, '-w'])
233
- }
234
- if (process.platform === 'win32') {
235
- const b64 = readFileSync(joinPath(secretsDir || '.', acc + '.bin'), 'utf8').trim()
236
- if (!b64) return null
237
- const script = dpapiUnprotectScript(b64)
238
- return await run('powershell', ['-NoProfile', '-STA', '-Command', script])
239
- }
240
- if (process.platform === 'linux') {
241
- return await run('secret-tool', ['lookup', 'service', SERVICE, 'account', acc])
242
- }
243
- } catch { /* fall through */ }
244
- return null
245
- }
246
-
247
- /** Delete a stored password (idempotent). */
248
- export async function deleteSecret(machineId, secretsDir) {
249
- const acc = account(machineId)
250
- try {
251
- if (process.platform === 'darwin') {
252
- await run('security', ['delete-generic-password', '-s', SERVICE, '-a', acc]).catch(() => {})
253
- return
254
- }
255
- if (process.platform === 'win32') {
256
- try { unlinkSync(joinPath(secretsDir || '.', acc + '.bin')) } catch { /* absent */ }
257
- return
258
- }
259
- if (process.platform === 'linux') {
260
- await run('secret-tool', ['clear', 'service', SERVICE, 'account', acc]).catch(() => {})
261
- }
262
- } catch { /* best effort */ }
263
- }
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
+ }