dsh-remote 0.8.94 → 1.1.1

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 (196) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +128 -370
  3. package/README.md +129 -355
  4. package/cordis.patch.yml +9 -9
  5. package/lib/audit.js +45 -45
  6. package/lib/auto-update.js +70 -0
  7. package/lib/binding.js +174 -172
  8. package/lib/boot.js +42 -42
  9. package/lib/client.js +6381 -4662
  10. package/lib/credential.js +277 -270
  11. package/lib/errors.js +141 -141
  12. package/lib/exec-job.js +245 -242
  13. package/lib/file-changes.js +57 -0
  14. package/lib/file-reference.js +457 -457
  15. package/lib/forwards.js +258 -258
  16. package/lib/host-api.js +822 -822
  17. package/lib/hostkey.js +108 -108
  18. package/lib/http-transport.js +201 -201
  19. package/lib/ignore.js +202 -202
  20. package/lib/index.js +4555 -4488
  21. package/lib/instructions-dynamic.js +415 -415
  22. package/lib/instructions.js +288 -288
  23. package/lib/open-folder.js +56 -56
  24. package/lib/openssh.js +950 -940
  25. package/lib/paths.js +292 -292
  26. package/lib/pool.js +1029 -1029
  27. package/lib/posix-shell.cjs +34 -34
  28. package/lib/registry.js +296 -296
  29. package/lib/remote-fs.js +179 -173
  30. package/lib/remote-git.js +127 -0
  31. package/lib/remote-sandbox.js +183 -183
  32. package/lib/remote-shell-child.cjs +460 -397
  33. package/lib/remote-shell.js +697 -697
  34. package/lib/remote-skills.js +312 -312
  35. package/lib/remote-write.js +51 -0
  36. package/lib/routes-audit.js +58 -58
  37. package/lib/routes-forwards.js +72 -72
  38. package/lib/routes-fs.js +299 -251
  39. package/lib/routes-machines.js +217 -186
  40. package/lib/routes-misc.js +187 -187
  41. package/lib/routes-term.js +169 -169
  42. package/lib/routes-update.js +147 -143
  43. package/lib/routes-web-attach.js +121 -112
  44. package/lib/routes-workspace.js +325 -312
  45. package/lib/search.js +235 -235
  46. package/lib/self-heal.js +130 -130
  47. package/lib/sftp-surface.js +119 -119
  48. package/lib/sshconfig.js +779 -779
  49. package/lib/sync-status.js +31 -0
  50. package/lib/sync.js +350 -350
  51. package/lib/tasks.js +95 -95
  52. package/lib/telemetry.js +247 -247
  53. package/lib/terminal.js +205 -205
  54. package/lib/tui/flow.js +130 -130
  55. package/lib/tui/format.js +380 -380
  56. package/lib/tui/i18n.js +350 -350
  57. package/lib/tui/index.js +531 -531
  58. package/lib/tui/provider.js +344 -344
  59. package/lib/tui/scene.js +986 -986
  60. package/lib/update.js +497 -490
  61. package/lib/vendor/jsdiff/LICENSE +29 -0
  62. package/lib/vendor/jsdiff/SOURCE.md +4 -0
  63. package/lib/vendor/jsdiff/diff/base.js +254 -0
  64. package/lib/vendor/jsdiff/diff/line.js +66 -0
  65. package/lib/vendor/jsdiff/patch/create.js +229 -0
  66. package/lib/vendor/jsdiff/util/params.js +15 -0
  67. package/lib/web-attach.js +1081 -860
  68. package/lib/workspace-cleanup.js +337 -337
  69. package/lib/workspace-search.js +219 -0
  70. package/node_modules/buildcheck/.eslintrc.js +5 -0
  71. package/node_modules/buildcheck/.github/workflows/ci.yml +88 -0
  72. package/node_modules/buildcheck/.github/workflows/lint.yml +27 -0
  73. package/node_modules/buildcheck/.npmignore +3 -0
  74. package/node_modules/buildcheck/LICENSE +19 -0
  75. package/node_modules/buildcheck/README.md +106 -0
  76. package/node_modules/buildcheck/deps/Find-VisualStudio.cs +250 -0
  77. package/node_modules/buildcheck/lib/findvs.js +361 -0
  78. package/node_modules/buildcheck/lib/index.js +738 -0
  79. package/node_modules/buildcheck/package.json +36 -0
  80. package/node_modules/buildcheck/test/test.js +8 -0
  81. package/node_modules/cpu-features/.eslintrc.js +5 -0
  82. package/node_modules/cpu-features/.github/workflows/ci.yml +74 -0
  83. package/node_modules/cpu-features/.github/workflows/lint.yml +27 -0
  84. package/node_modules/cpu-features/LICENSE +19 -0
  85. package/node_modules/cpu-features/README.md +59 -0
  86. package/node_modules/cpu-features/binding.gyp +16 -0
  87. package/node_modules/cpu-features/buildcheck.js +32 -0
  88. package/node_modules/cpu-features/deps/cpu_features/.clang-format +4 -0
  89. package/node_modules/cpu-features/deps/cpu_features/.dockerignore +31 -0
  90. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile +5 -0
  91. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/aarch64_linux_cmake.yml +30 -0
  92. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_freebsd_cmake.yml +22 -0
  93. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_bazel.yml +26 -0
  94. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_cmake.yml +31 -0
  95. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_macos_cmake.yml +43 -0
  96. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_windows_cmake.yml +25 -0
  97. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/arm_linux_cmake.yml +31 -0
  98. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml +24 -0
  99. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/mips_linux_cmake.yml +30 -0
  100. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/power_linux_cmake.yml +29 -0
  101. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/riscv_linux_cmake.yml +28 -0
  102. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/s390x_linux_cmake.yml +27 -0
  103. package/node_modules/cpu-features/deps/cpu_features/.grenrc.yml +21 -0
  104. package/node_modules/cpu-features/deps/cpu_features/BUILD.bazel +329 -0
  105. package/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt +261 -0
  106. package/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md +23 -0
  107. package/node_modules/cpu-features/deps/cpu_features/LICENSE +230 -0
  108. package/node_modules/cpu-features/deps/cpu_features/README.md +272 -0
  109. package/node_modules/cpu-features/deps/cpu_features/WORKSPACE +19 -0
  110. package/node_modules/cpu-features/deps/cpu_features/bazel/ci/README.md +5 -0
  111. package/node_modules/cpu-features/deps/cpu_features/bazel/platforms.bzl +11 -0
  112. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in +3 -0
  113. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in +3 -0
  114. package/node_modules/cpu-features/deps/cpu_features/cmake/README.md +30 -0
  115. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/Makefile +252 -0
  116. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/README.md +40 -0
  117. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.dot +64 -0
  118. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.svg +312 -0
  119. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/generate_image.sh +7 -0
  120. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/amd64/Dockerfile +48 -0
  121. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/toolchain/Dockerfile +34 -0
  122. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/CMakeLists.txt +22 -0
  123. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/main.cpp +11 -0
  124. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/vagrant/freebsd/Vagrantfile +107 -0
  125. package/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in +15 -0
  126. package/node_modules/cpu-features/deps/cpu_features/cpu_features.gyp +105 -0
  127. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h +54 -0
  128. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h +384 -0
  129. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h +259 -0
  130. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h +121 -0
  131. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h +74 -0
  132. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h +149 -0
  133. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_riscv.h +72 -0
  134. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_s390x.h +108 -0
  135. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h +288 -0
  136. package/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h +40 -0
  137. package/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h +37 -0
  138. package/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h +39 -0
  139. package/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h +240 -0
  140. package/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h +49 -0
  141. package/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h +110 -0
  142. package/node_modules/cpu-features/deps/cpu_features/include/internal/windows_utils.h +70 -0
  143. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt +60 -0
  144. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md +4 -0
  145. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c +205 -0
  146. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h +320 -0
  147. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c +12 -0
  148. package/node_modules/cpu-features/deps/cpu_features/patches/0001-Add-Apple-Silicon-Support.patch +456 -0
  149. package/node_modules/cpu-features/deps/cpu_features/scripts/generate_badges.d +165 -0
  150. package/node_modules/cpu-features/deps/cpu_features/scripts/make_release.sh +75 -0
  151. package/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh +490 -0
  152. package/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh +79 -0
  153. package/node_modules/cpu-features/deps/cpu_features/src/copy.inl +19 -0
  154. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection.inl +86 -0
  155. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection_and_hwcaps.inl +26 -0
  156. package/node_modules/cpu-features/deps/cpu_features/src/equals.inl +22 -0
  157. package/node_modules/cpu-features/deps/cpu_features/src/filesystem.c +62 -0
  158. package/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c +169 -0
  159. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64__base_implementation.inl +88 -0
  160. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_linux_or_android.c +79 -0
  161. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_macos_or_iphone.c +82 -0
  162. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_windows.c +138 -0
  163. package/node_modules/cpu-features/deps/cpu_features/src/impl_arm_linux_or_android.c +212 -0
  164. package/node_modules/cpu-features/deps/cpu_features/src/impl_mips_linux_or_android.c +93 -0
  165. package/node_modules/cpu-features/deps/cpu_features/src/impl_ppc_linux.c +163 -0
  166. package/node_modules/cpu-features/deps/cpu_features/src/impl_riscv_linux.c +111 -0
  167. package/node_modules/cpu-features/deps/cpu_features/src/impl_s390x_linux.c +120 -0
  168. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86__base_implementation.inl +2055 -0
  169. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_freebsd.c +68 -0
  170. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_linux_or_android.c +58 -0
  171. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_macos.c +57 -0
  172. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_windows.c +58 -0
  173. package/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c +132 -0
  174. package/node_modules/cpu-features/deps/cpu_features/src/string_view.c +192 -0
  175. package/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c +461 -0
  176. package/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt +114 -0
  177. package/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc +53 -0
  178. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc +396 -0
  179. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc +384 -0
  180. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc +176 -0
  181. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc +131 -0
  182. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_riscv_test.cc +180 -0
  183. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_s390x_test.cc +82 -0
  184. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc +1729 -0
  185. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc +103 -0
  186. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h +61 -0
  187. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc +52 -0
  188. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h +31 -0
  189. package/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc +132 -0
  190. package/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc +202 -0
  191. package/node_modules/cpu-features/lib/index.js +5 -0
  192. package/node_modules/cpu-features/package.json +40 -0
  193. package/node_modules/cpu-features/src/binding.cc +151 -0
  194. package/node_modules/cpu-features/test/test.js +12 -0
  195. package/node_modules/nan/tools/1to2.js +0 -0
  196. package/package.json +107 -103
package/lib/credential.js CHANGED
@@ -1,270 +1,277 @@
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
+ // Failed stores are reported to persistPassword, whose default policy refuses
5
+ // plaintext fallback. An explicitly requested fallback remains visible.
6
+ //
7
+ // Backends:
8
+ // darwin → `security` (login keychain, generic password)
9
+ // win32 → DPAPI via PowerShell (CurrentUser scope), files under
10
+ // $DSH_HOME/remote-workspaces/.secrets/
11
+ // linux → `secret-tool` (libsecret / gnome-keyring), optional
12
+ // else → unsupported (plain)
13
+ import { spawn } from 'node:child_process'
14
+ import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from 'node:fs'
15
+ import { join as joinPath } from 'node:path'
16
+
17
+ const SERVICE = 'dsh-remote'
18
+ const TIMEOUT = 8000
19
+
20
+ // Windows PowerShell 5.1 does not preload System.Security, so
21
+ // [System.Security.Cryptography.ProtectedData] is "not found" until the assembly
22
+ // is added (issue #30: without this the whole DPAPI call failed and the caller
23
+ // silently lost the password). `-ErrorAction SilentlyContinue` keeps the line
24
+ // harmless on PowerShell 7, where the type is already available.
25
+ const PS_SECURITY_ASSEMBLY = 'Add-Type -AssemblyName System.Security -ErrorAction SilentlyContinue;'
26
+
27
+ /**
28
+ * Run a helper and resolve with its trimmed stdout.
29
+ *
30
+ * WHY `spawn` and not `execFile(..., { input })`: measured on a real Ubuntu box
31
+ * with a real gnome-keyring, `secret-tool store` given its password through
32
+ * `execFile`'s `input` option **never saw EOF**, blocked on the read, and was
33
+ * killed by this timeout — so on Linux "encrypt the password" always failed after
34
+ * 8 seconds with the useless message "Command failed: secret-tool store …" (empty
35
+ * stderr) and the credential was dropped. The same command with an explicitly
36
+ * ended stdin (`spawn` + `stdin.end()`, or `sh -c '… < file'`) finishes in ~20ms.
37
+ * Nothing in this module needs the extra `execFile` machinery, so stdin is now
38
+ * always closed explicitly and the child's stderr is carried on the error (the old
39
+ * path dropped it, which is why the failure had no reason attached).
40
+ */
41
+ function run(bin, args, input) {
42
+ return new Promise((resolve, reject) => {
43
+ let child
44
+ const hasInput = input !== undefined && input !== null
45
+ try {
46
+ // security/PowerShell receive arguments, not stdin. An unused pipe can
47
+ // EPIPE after a fast helper has already committed its keychain write.
48
+ child = spawn(bin, args, { stdio: [hasInput ? 'pipe' : 'ignore', 'pipe', 'pipe'] })
49
+ } catch (err) {
50
+ reject(err)
51
+ return
52
+ }
53
+ let out = ''
54
+ let errOut = ''
55
+ let settled = false
56
+ const timer = setTimeout(() => {
57
+ if (settled) return
58
+ settled = true
59
+ try { child.kill('SIGTERM') } catch { /* already gone */ }
60
+ const err = new Error(`${bin} timed out after ${TIMEOUT}ms`)
61
+ err.stderr = errOut
62
+ err.code = 'ETIMEDOUT'
63
+ reject(err)
64
+ }, TIMEOUT)
65
+ const done = (err, value) => {
66
+ if (settled) return
67
+ settled = true
68
+ clearTimeout(timer)
69
+ if (err) reject(err); else resolve(value)
70
+ }
71
+ child.on('error', (err) => done(err))
72
+ child.on('close', (code) => {
73
+ if (code === 0) return done(null, out.trim())
74
+ const err = new Error(`${bin} exited with ${code}${errOut.trim() ? ': ' + errOut.trim().slice(0, 300) : ''}`)
75
+ err.code = code
76
+ err.stderr = errOut
77
+ done(err)
78
+ })
79
+ child.stdout.on('data', (d) => { out += d })
80
+ child.stderr.on('data', (d) => { errOut += d })
81
+ // A helper may close its read end before stdin.end() flushes. EPIPE is an
82
+ // ASYNC Writable error, so the synchronous try/catch below cannot see it;
83
+ // without this listener it becomes an uncaughtException and kills the host.
84
+ if (child.stdin) child.stdin.on('error', (err) => {
85
+ try { child.kill('SIGTERM') } catch { /* already gone */ }
86
+ done(err)
87
+ })
88
+ // Always end stdin: a helper that reads a secret from stdin needs EOF, and one
89
+ // that does not must not inherit an open pipe.
90
+ if (child.stdin) try { child.stdin.end(String(input)) } catch { /* closed early */ }
91
+ })
92
+ }
93
+
94
+ export function platformBackend() {
95
+ if (process.platform === 'darwin') return 'keychain'
96
+ if (process.platform === 'win32') return 'windows'
97
+ return 'secret' // linux (secret-tool may be absent → falls back)
98
+ }
99
+
100
+ function account(machineId) {
101
+ // Only machine ids are stored; sanitize just in case.
102
+ return String(machineId || '').replace(/[^a-zA-Z0-9._-]/g, '_')
103
+ }
104
+
105
+ /** Redact a failed command's diagnostics: execFile puts the FULL command line
106
+ * (which carries the password as an argv) into `err.message`, and this string is
107
+ * shown in the settings UI — so the secret must never survive it. */
108
+ function safeReason(err, password) {
109
+ const raw = [err && err.stderr, err && err.message, err && err.code]
110
+ .filter(Boolean).map(String).join(' ')
111
+ const secret = String(password == null ? '' : password)
112
+ const scrubbed = secret ? raw.split(secret).join('***') : raw
113
+ return scrubbed.replace(/\s+/g, ' ').trim().slice(0, 300)
114
+ }
115
+
116
+ /** PowerShell one-liner that DPAPI-protects a password (CurrentUser scope).
117
+ * Exported because the issue #30 fix (the mandatory Add-Type preamble) is only
118
+ * observable here — a Windows host cannot be exercised from the test suite. */
119
+ export function dpapiProtectScript(password) {
120
+ return PS_SECURITY_ASSEMBLY +
121
+ `$p='${String(password).replace(/'/g, "''")}';` +
122
+ `$s=[System.Security.Cryptography.ProtectedData]::Protect([Text.Encoding]::UTF8.GetBytes($p),$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser);` +
123
+ `[Convert]::ToBase64String($s)`
124
+ }
125
+
126
+ /** PowerShell one-liner that reverses dpapiProtectScript(). */
127
+ export function dpapiUnprotectScript(b64) {
128
+ return PS_SECURITY_ASSEMBLY +
129
+ `$s=[Convert]::FromBase64String('${String(b64).replace(/'/g, "''")}');` +
130
+ `[Text.Encoding]::UTF8.GetString([System.Security.Cryptography.ProtectedData]::Unprotect($s,$null,[System.Security.Cryptography.DataProtectionScope]::CurrentUser))`
131
+ }
132
+
133
+ /** Save a password to the OS store. Resolves {ok, backend, error} — ok:false on
134
+ * any failure (caller falls back to plaintext). `error` is a password-free
135
+ * diagnostic for the UI. */
136
+ export async function saveSecret(machineId, password, secretsDir) {
137
+ const acc = account(machineId)
138
+ try {
139
+ if (process.platform === 'darwin') {
140
+ await run('security', ['add-generic-password', '-U', '-s', SERVICE, '-a', acc, '-w', String(password)])
141
+ return { ok: true, backend: 'keychain', error: '' }
142
+ }
143
+ if (process.platform === 'win32') {
144
+ // DPAPI-encrypt and store under the harness home.
145
+ const script = dpapiProtectScript(password)
146
+ const b64 = await run('powershell', ['-NoProfile', '-STA', '-Command', script])
147
+ if (!b64) return { ok: false, backend: 'windows', error: 'DPAPI returned no ciphertext' }
148
+ mkdirSync(secretsDir || '.', { recursive: true })
149
+ writeFileSync(joinPath(secretsDir || '.', acc + '.bin'), b64, 'utf8')
150
+ return { ok: true, backend: 'windows', error: '' }
151
+ }
152
+ if (process.platform === 'linux') {
153
+ await run('secret-tool', ['store', '--label=' + SERVICE, 'service', SERVICE, 'account', acc], String(password) + '\n')
154
+ return { ok: true, backend: 'secret', error: '' }
155
+ }
156
+ } catch (err) {
157
+ // Some OS helpers can fail after committing. Verify the requested value
158
+ // before reporting refusal; a successful secure-store read is the actual
159
+ // postcondition, and does not weaken the plaintext fallback policy.
160
+ if (await getSecret(machineId, secretsDir) === String(password)) {
161
+ return { ok: true, backend: platformBackend(), error: '' }
162
+ }
163
+ return { ok: false, backend: platformBackend(), error: safeReason(err, password) || 'secret store write failed' }
164
+ }
165
+ return { ok: false, backend: platformBackend(), error: `unsupported platform: ${process.platform}` }
166
+ }
167
+
168
+ /** Decide where a machine password is persisted (issue #30).
169
+ *
170
+ * The contract the settings UI relies on: a password is NEVER silently dropped.
171
+ * Historically that guarantee was upheld by falling back to PLAINTEXT in
172
+ * machines.json, which is a bad trade in one specific way: the user asked for
173
+ * encryption, the store failed, and the secret ended up less protected than if
174
+ * they had never asked. Worse, a locked keychain / missing secret-tool is
175
+ * exactly the moment when quietly writing a password to a world-readable file
176
+ * on disk is most likely to go unnoticed.
177
+ *
178
+ * So the fallback is a POLICY, not a fixed behaviour (`onStoreFailure`):
179
+ *
180
+ * `refuse` (default) — do not store the password at all. The machine is
181
+ * saved WITHOUT a credential and the caller reports how to fix the
182
+ * store; the user retypes (or connects) and nothing lands in
183
+ * plaintext by accident. `stored: 'none'` makes that explicit.
184
+ * `plain` — the legacy behaviour: write it to machines.json and raise
185
+ * `warning: 'secret-store-failed'`. Opt-in only, for users who
186
+ * genuinely prefer a working machine over the storage guarantee.
187
+ *
188
+ * An explicit `backend: 'plain'` still means plain by REQUEST (the user turned
189
+ * encryption off), and is unaffected by this policy.
190
+ *
191
+ * `save` is injectable so both paths are unit-testable on any platform.
192
+ *
193
+ * @param {object} arg
194
+ * @param {string} arg.backend - the platform backend name ('keychain'|'windows'|'secret'|'plain').
195
+ * @param {string} arg.machineId
196
+ * @param {string} arg.password
197
+ * @param {string} [arg.secretsDir]
198
+ * @param {'refuse'|'plain'} [arg.onStoreFailure] - see above.
199
+ * @param {Function} [arg.save] - injectable secure-store writer.
200
+ * @returns {Promise<{stored:'secret'|'plain'|'none', credentialBackend:string, password:string, warning:string, error:string}>}
201
+ */
202
+ export async function persistPassword({
203
+ backend, machineId, password, secretsDir,
204
+ onStoreFailure = 'refuse',
205
+ save = saveSecret,
206
+ }) {
207
+ const pw = password == null ? '' : String(password)
208
+ const want = backend && backend !== 'plain' ? backend : 'plain'
209
+ if (!pw) return { stored: 'none', credentialBackend: want, password: '', warning: '', error: '' }
210
+ if (want === 'plain') return { stored: 'plain', credentialBackend: 'plain', password: pw, warning: '', error: '' }
211
+ let res
212
+ try {
213
+ res = await save(machineId, pw, secretsDir)
214
+ } catch (err) {
215
+ res = { ok: false, error: safeReason(err, pw) }
216
+ }
217
+ if (res && res.ok) {
218
+ return { stored: 'secret', credentialBackend: res.backend || want, password: '', warning: '', error: '' }
219
+ }
220
+ const error = String((res && res.error) || '') || 'secret store write failed'
221
+ if (onStoreFailure === 'plain') {
222
+ return {
223
+ stored: 'plain',
224
+ credentialBackend: 'plain',
225
+ password: pw,
226
+ warning: 'secret-store-failed',
227
+ error,
228
+ }
229
+ }
230
+ // Default: refuse. Nothing is written, and the caller surfaces the store
231
+ // failure plus the platform-specific repair hint instead of a silent downgrade.
232
+ return {
233
+ stored: 'none',
234
+ credentialBackend: want,
235
+ password: '',
236
+ warning: 'secret-store-refused',
237
+ error,
238
+ }
239
+ }
240
+
241
+ /** Fetch a stored password. Resolves string|null. */
242
+ export async function getSecret(machineId, secretsDir) {
243
+ const acc = account(machineId)
244
+ try {
245
+ if (process.platform === 'darwin') {
246
+ return await run('security', ['find-generic-password', '-s', SERVICE, '-a', acc, '-w'])
247
+ }
248
+ if (process.platform === 'win32') {
249
+ const b64 = readFileSync(joinPath(secretsDir || '.', acc + '.bin'), 'utf8').trim()
250
+ if (!b64) return null
251
+ const script = dpapiUnprotectScript(b64)
252
+ return await run('powershell', ['-NoProfile', '-STA', '-Command', script])
253
+ }
254
+ if (process.platform === 'linux') {
255
+ return await run('secret-tool', ['lookup', 'service', SERVICE, 'account', acc])
256
+ }
257
+ } catch { /* fall through */ }
258
+ return null
259
+ }
260
+
261
+ /** Delete a stored password (idempotent). */
262
+ export async function deleteSecret(machineId, secretsDir) {
263
+ const acc = account(machineId)
264
+ try {
265
+ if (process.platform === 'darwin') {
266
+ await run('security', ['delete-generic-password', '-s', SERVICE, '-a', acc]).catch(() => {})
267
+ return
268
+ }
269
+ if (process.platform === 'win32') {
270
+ try { unlinkSync(joinPath(secretsDir || '.', acc + '.bin')) } catch { /* absent */ }
271
+ return
272
+ }
273
+ if (process.platform === 'linux') {
274
+ await run('secret-tool', ['clear', 'service', SERVICE, 'account', acc]).catch(() => {})
275
+ }
276
+ } catch { /* best effort */ }
277
+ }