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/openssh.js CHANGED
@@ -1,940 +1,950 @@
1
- // dsh-remote — the "system OpenSSH" SSH backend (issue #51).
2
- //
3
- // ## Why this exists
4
- //
5
- // The default backend (lib/pool.js) speaks SSH itself through ssh2, so it can
6
- // only use the authentication methods ssh2 implements: password, private key,
7
- // ssh-agent and keyboard-interactive. Enterprise hosts that only allow
8
- // GSSAPI/Kerberos are unreachable, even though `ssh <alias>` in the user's own
9
- // terminal works — the local Kerberos ticket (kinit) is simply not something
10
- // ssh2 knows how to present.
11
- //
12
- // This backend delegates the transport to the LOCAL `ssh` executable, so every
13
- // `~/.ssh/config` feature the user already relies on applies: gssapi-with-mic,
14
- // ProxyJump, ProxyCommand, ControlPath, Host aliases, IdentityFile,
15
- // PKCS11Provider, Match blocks… Anything OpenSSH can do, this backend can do,
16
- // because OpenSSH is the one doing it.
17
- //
18
- // ## How each primitive is implemented
19
- //
20
- // exec → `ssh <opts> -- <dest> <command>` (one process per call)
21
- // sftp → `ssh <opts> -s <dest> sftp` + ssh2's OWN SFTP protocol engine
22
- // driven over the resulting raw byte stream
23
- // forwardOut → `ssh <opts> -W <host>:<port> <dest>` (one process per tunnel)
24
- // reverse → `ssh <opts> -N -R <bind>:<port>:<h>:<p> <dest>`
25
- //
26
- // The SFTP one deserves a note, because it is the reason this backend did not
27
- // have to reimplement file transfer: `ssh -s <dest> sftp` on stdio is a PLAIN
28
- // SFTP v3 byte stream (verified against a real host — the subsystem replies
29
- // with its VERSION packet and nothing else on stdout). ssh2 already ships a
30
- // complete, battle-tested SFTP implementation that speaks exactly that protocol
31
- // over a duplex stream, so this module gives it a minimal `_protocol` shim and
32
- // hands it the child process's stdio. File transfer therefore has the same
33
- // semantics — and the same large-packet optimisations — as the native backend.
34
- //
35
- // ## Trade-offs (documented, not hidden)
36
- //
37
- // • spawn-per-operation: unlike the native pool there is no long-lived
38
- // connection multiplexed across commands, so each `exec`/`forwardOut` pays
39
- // a fresh SSH handshake. That is inherent to delegating to the `ssh` CLI:
40
- // Windows OpenSSH rejects ControlMaster ("getsockname failed: Not a
41
- // socket", measured), and a portable multiplexing layer would be a second
42
- // implementation of what the native backend already does. The SFTP path IS
43
- // kept persistent, because the workspace picker and the explorer hammer it.
44
- // • the passphrase/password prompt: OpenSSH asks for both through the same
45
- // askpass channel, so when a secret is configured this backend offers it
46
- // for whichever prompt appears (password first, then passphrase). A host
47
- // needing two DIFFERENT secrets is not representable here — use the native
48
- // backend for that.
49
- // • reverse forwards need their target up front (the CLI takes it as an
50
- // argument), so they are exposed as `reverseForward()` and ForwardManager
51
- // prefers it when present.
52
- // • host keys are checked by ssh itself against the user's own known_hosts,
53
- // not against the plugin's TOFU store: making `ssh` use a different trust
54
- // anchor per machine is exactly the kind of override that breaks the
55
- // enterprise setups this backend exists to serve. `hostKeyMode` maps onto
56
- // StrictHostKeyChecking instead.
57
-
58
- import { spawn } from 'node:child_process'
59
- import { accessSync, chmodSync, constants as fsConstants, mkdirSync, writeFileSync } from 'node:fs'
60
- import { createRequire } from 'node:module'
61
- import { EventEmitter } from 'node:events'
62
- import { homedir, tmpdir } from 'node:os'
63
- import path from 'node:path'
64
- import { Duplex } from 'node:stream'
65
- import { buildSftpSurface } from './sftp-surface.js'
66
- import { truncate } from './paths.js'
67
-
68
- // The SFTP protocol engine lives at lib/protocol/SFTP.js inside ssh2 and is not
69
- // part of its public API. Creating it through createRequire keeps this module
70
- // ESM-clean while still reaching it; if a future ssh2 moves it, this fails with
71
- // an actionable message instead of a bare MODULE_NOT_FOUND at connect time.
72
- const require_ = createRequire(import.meta.url)
73
- let SftpEngine = null
74
- export function loadSftpEngine() {
75
- if (SftpEngine) return SftpEngine
76
- try {
77
- const entry = require_.resolve('ssh2')
78
- const sftpPath = entry.replace(/lib[\\/]index\.js$/, 'lib/protocol/SFTP.js')
79
- SftpEngine = require_(sftpPath).SFTP
80
- } catch (err) {
81
- throw new Error("system-OpenSSH backend could not load ssh2's SFTP engine: " + ((err && err.message) || err))
82
- }
83
- if (typeof SftpEngine !== 'function') {
84
- throw new Error("system-OpenSSH backend found no SFTP engine in this ssh2 install")
85
- }
86
- return SftpEngine
87
- }
88
-
89
- /** The `ssh` executable this backend drives (config override wins). */
90
- export function resolveSshBinary(config = {}) {
91
- return String(config.sshBinary || '').trim() || 'ssh'
92
- }
93
-
94
- /**
95
- * Path of the user's own known_hosts. Exposed for the UI; the backend itself
96
- * never points ssh at a different file (see the header).
97
- */
98
- export function defaultKnownHostsPath() {
99
- return path.join(homedir(), '.ssh', 'known_hosts')
100
- }
101
-
102
- /**
103
- * Translate `hostKeyMode` into OpenSSH's StrictHostKeyChecking.
104
- *
105
- * `accept-new` is ssh's own default on modern OpenSSH and matches the plugin's
106
- * TOFU default; `verify` refuses unknown hosts; `off` accepts anything.
107
- */
108
- export function hostKeyArgs(config = {}) {
109
- const mode = config.hostKeyMode === 'verify' || config.hostKeyMode === 'off' ? config.hostKeyMode : 'accept-new'
110
- const strict = mode === 'verify' ? 'yes' : mode === 'off' ? 'no' : 'accept-new'
111
- return ['-o', `StrictHostKeyChecking=${strict}`]
112
- }
113
-
114
- /**
115
- * Where the generated askpass helper lives. One stable directory per user, so
116
- * the helper is written once and reused; the helper carries NO secret (it reads
117
- * the secret from the environment), which is why writing it to disk is safe.
118
- */
119
- export function askpassDir() {
120
- return path.join(tmpdir(), 'dsh-remote-askpass')
121
- }
122
-
123
- /**
124
- * Ensure an askpass helper exists and return its path.
125
- *
126
- * The helper prints $DSH_REMOTE_SSH_SECRET. Passing the secret through the
127
- * environment (rather than as an argument or a file) keeps it out of `ps`,
128
- * argv and the filesystem. The Windows helper is a .cmd that invokes Node via
129
- * `process.execPath`, because `@echo %VAR%` would mangle secrets containing cmd
130
- * metacharacters (&, %, ^ …) and a bare `echo` is not a shell we control.
131
- */
132
- export function ensureAskpassHelper() {
133
- const dir = askpassDir()
134
- try { mkdirSync(dir, { recursive: true }) } catch { /* already there */ }
135
- if (process.platform === 'win32') {
136
- const js = path.join(dir, 'askpass.js')
137
- const cmd = path.join(dir, 'askpass.cmd')
138
- try {
139
- writeFileSync(js, 'process.stdout.write((process.env.DSH_REMOTE_SSH_SECRET || "") + "\\n")\n')
140
- writeFileSync(cmd, '@echo off\r\n"' + process.execPath + '" "' + js + '"\r\n')
141
- } catch (err) {
142
- throw new Error('system-OpenSSH backend could not write its askpass helper: ' + ((err && err.message) || err))
143
- }
144
- return cmd
145
- }
146
- const sh = path.join(dir, 'askpass.sh')
147
- try {
148
- writeFileSync(sh, '#!/bin/sh\nprintf \'%s\\n\' "$DSH_REMOTE_SSH_SECRET"\n')
149
- try { chmodSync(sh, 0o700) } catch { /* best effort on odd filesystems */ }
150
- } catch (err) {
151
- throw new Error('system-OpenSSH backend could not write its askpass helper: ' + ((err && err.message) || err))
152
- }
153
- return sh
154
- }
155
-
156
- /** Env that hands the secret to the askpass helper (never argv, never a file). */
157
- export function askpassEnv(secret) {
158
- return {
159
- ...process.env,
160
- SSH_ASKPASS: ensureAskpassHelper(),
161
- SSH_ASKPASS_REQUIRE: 'force',
162
- DISPLAY: process.env.DISPLAY || ':0',
163
- DSH_REMOTE_SSH_SECRET: String(secret),
164
- }
165
- }
166
-
167
- /**
168
- * Keep an EPIPE on a child's stdin from becoming a process-wide crash.
169
- *
170
- * A child that stops reading — the remote side of `ssh -s sftp` dying mid-
171
- * transfer is the one that bites — makes the NEXT write to its stdin fail. Node
172
- * reports that asynchronously through the Writable's `'error'` event, so a
173
- * synchronous `try/catch` around `write()` never sees it; an unhandled
174
- * `'error'` on a stream is an uncaught exception, and the Host treats one of
175
- * those as fatal (issue #118: `dsh: fatal uncaught exception: Error: write
176
- * EPIPE` → the whole app's host process exits and every session is lost).
177
- *
178
- * Every `spawn` in this file therefore gets this hook: swallow the pipe error,
179
- * report it to `onError` when the caller has cleanup to do, and let the
180
- * existing `'close'`/`'error'` handling own the rest. A missing `ssh` binary
181
- * is a different signal — spawn reports it on the CHILD, not on its stdin — so
182
- * it still reaches the caller as a real error.
183
- *
184
- * @param {import('node:child_process').ChildProcess} child
185
- * @param {(err: Error) => void} [onError] - e.g. drop the cached SFTP session.
186
- * @returns {import('node:child_process').ChildProcess} the same child.
187
- */
188
- export function guardChildStdin(child, onError) {
189
- const stdin = child && child.stdin
190
- if (!stdin || typeof stdin.on !== 'function') return child
191
- // A listener is the difference between "this stream reported a problem" and
192
- // "this process died": without one Node re-throws the error as an uncaught
193
- // exception. There is nothing to retry here — the pipe is gone — so all that
194
- // is left is to let the caller drop whatever it cached for this child; the
195
- // child's own 'close'/'error' handling still reports the real failure.
196
- stdin.on('error', (err) => {
197
- if (typeof onError === 'function') { try { onError(err) } catch { /* best effort */ } }
198
- })
199
- return child
200
- }
201
-
202
- /** Is `ssh` runnable? Used to fail with an actionable message, not ENOENT. */
203
- export function sshBinaryAvailable(binary) {
204
- if (binary.includes('/') || binary.includes('\\')) {
205
- try { accessSync(binary, fsConstants.X_OK); return true } catch { return false }
206
- }
207
- const exts = process.platform === 'win32'
208
- ? String(process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';').filter(Boolean)
209
- : ['']
210
- for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
211
- if (!dir) continue
212
- for (const ext of exts) {
213
- try { accessSync(path.join(dir, binary + ext), fsConstants.X_OK); return true } catch { /* keep looking */ }
214
- }
215
- }
216
- return false
217
- }
218
-
219
- /**
220
- * Options shared by every `ssh` invocation for this target.
221
- *
222
- * Deliberately NOT passed: PreferredAuthentications / GSSAPIAuthentication /
223
- * PubkeyAcceptedKeyTypes / IdentitiesOnly-from-the-alias / ProxyJump-from-the-
224
- * alias. Those must come from the user's `~/.ssh/config` — overriding them is
225
- * precisely what would break the enterprise setups this backend exists for.
226
- *
227
- * @param {object} config - the pool config.
228
- * @param {object} [opts]
229
- * @param {boolean} [opts.forSecret] - true when a secret will be offered via
230
- * askpass, which means BatchMode must be OFF (BatchMode forbids every
231
- * interactive prompt, askpass included) and the prompt count bounded instead.
232
- */
233
- export function baseSshArgs(config, { forSecret = false } = {}) {
234
- const args = []
235
- if (config.port && Number(config.port) !== 22) args.push('-p', String(Number(config.port)))
236
- if (config.username) args.push('-l', String(config.username))
237
- if (config.privateKeyPath) args.push('-i', String(config.privateKeyPath))
238
- // An explicit jump host — the same shape the native backend's `proxy` takes.
239
- // A jump host that comes from ~/.ssh/config needs nothing here.
240
- const proxy = config.proxy
241
- if (proxy && proxy.host) {
242
- const user = proxy.username ? `${proxy.username}@` : ''
243
- const port = proxy.port && Number(proxy.port) !== 22 ? `:${Number(proxy.port)}` : ''
244
- args.push('-J', `${user}${proxy.host}${port}`)
245
- }
246
- // An explicit known_hosts file (tests keep loopback keys OUT of the user's
247
- // real ~/.ssh/known_hosts with this; ssh ignores $HOME on some platforms).
248
- // Checking strength is unchanged — StrictHostKeyChecking below still applies.
249
- if (config.knownHostsFile) args.push('-o', `UserKnownHostsFile=${config.knownHostsFile}`)
250
- args.push(...hostKeyArgs(config))
251
- const connectSecs = Math.max(1, Math.round((Number(config.connectTimeoutMs) || 15000) / 1000))
252
- args.push('-o', `ConnectTimeout=${connectSecs}`, '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3')
253
- // Without a configured secret we must not hang on an interactive prompt:
254
- // BatchMode makes ssh fail fast instead, and leaves key/agent/GSSAPI intact.
255
- if (!forSecret) args.push('-o', 'BatchMode=yes')
256
- else args.push('-o', 'NumberOfPasswordPrompts=1')
257
- return args
258
- }
259
-
260
- /**
261
- * One live system-OpenSSH connection.
262
- *
263
- * This deliberately mimics the ssh2 Client surface the rest of the plugin
264
- * consumes — `forwardOut` plus a reverse-forward capability — so
265
- * ForwardManager/WebAttach work unchanged. It is an EventEmitter because the
266
- * native pool's client is one and callers attach listeners to it.
267
- */
268
- export class OpenSshConnection extends EventEmitter {
269
- constructor(pool, { sshBinary, secret }) {
270
- super()
271
- this.pool = pool
272
- this.sshBinary = sshBinary
273
- this.secret = secret
274
- this.closed = false
275
- /** Live child processes to reap on close. */
276
- this.children = new Set()
277
- }
278
-
279
- shortDescription() {
280
- return `${this.pool.destination()} via ${this.sshBinary}`
281
- }
282
-
283
- spawnSsh(extraArgs, { tty = false } = {}) {
284
- if (this.closed) throw new Error('ssh connection closed')
285
- const args = [
286
- ...baseSshArgs(this.pool._argConfig(), { forSecret: !!this.secret }),
287
- ...extraArgs,
288
- ]
289
- const child = spawn(this.sshBinary, args, {
290
- stdio: ['pipe', 'pipe', 'pipe'],
291
- env: this.secret ? askpassEnv(this.secret) : undefined,
292
- })
293
- this.children.add(child)
294
- const reap = () => this.children.delete(child)
295
- // Every connection-level child goes through here (the `ssh -W` forward
296
- // channel and the `ssh -N` reverse forward), so the stdin guard for those
297
- // two paths belongs here rather than at each call site: a tunnel whose peer
298
- // vanished must end as a closed channel, not as a fatal EPIPE (issue #118).
299
- guardChildStdin(child)
300
- child.on('close', reap)
301
- child.on('error', reap)
302
- if (tty) { /* no pty support through the CLI without a tty helper */ }
303
- return child
304
- }
305
-
306
- /**
307
- * Local forward: carry bytes to <destHost>:<destPort> as seen FROM the
308
- * remote, through `ssh -W`.
309
- *
310
- * @returns {boolean} true synchronously, so capability probes can be sync.
311
- */
312
- forwardOut(_srcHost, _srcPort, destHost, destPort, cb) {
313
- let child
314
- try {
315
- child = this.spawnSsh(['-W', `${destHost}:${destPort}`, '--', this.pool.destination()])
316
- } catch (err) {
317
- setImmediate(() => cb(err))
318
- return true
319
- }
320
- // `ssh -W` reports failures on stderr and then exits; surface that as the
321
- // channel error so the caller destroys its socket instead of hanging.
322
- let stderr = ''
323
- let handed = false
324
- const channel = new Duplex({
325
- read() {},
326
- write(chunk, _enc, done) { try { child.stdin.write(chunk, done) } catch (e) { done(e) } },
327
- final(done) { try { child.stdin.end(done) } catch { done() } },
328
- destroy(err, done) { try { child.kill() } catch {} ; done(err) },
329
- })
330
- channel.close = () => { try { child.kill() } catch {} }
331
- child.stderr.on('data', (d) => { stderr += d })
332
- child.stdout.on('data', (d) => channel.push(d))
333
- child.stdout.on('end', () => channel.push(null))
334
- child.on('error', (e) => { if (!handed) { handed = true; cb(e); return } channel.destroy(e) })
335
- child.on('close', (code) => {
336
- if (handed) { channel.push(null); return }
337
- handed = true
338
- if (code === 0) { cb(null, channel); return }
339
- cb(new Error(`ssh -W to ${destHost}:${destPort} failed (exit ${code})${stderr ? ': ' + stderr.trim() : ''}`))
340
- })
341
- return true
342
- }
343
-
344
- /** Tells ForwardManager that the CLI-specific reverse path is available. */
345
- get supportsReverseForward() { return true }
346
-
347
- /**
348
- * Reverse forward: ask the REMOTE to listen on <bindHost>:<listenPort> and
349
- * carry connections to <targetHost>:<targetPort>. Unlike ssh2's two-phase
350
- * `forwardIn` + `tcpip`, the `ssh -R` CLI takes the final target as an
351
- * argument, so nothing has to be resolved lazily.
352
- *
353
- * @returns {Promise<{child: object, close: Function}>}
354
- */
355
- reverseForward({ bindHost = '127.0.0.1', listenPort, targetHost = '127.0.0.1', targetPort }) {
356
- return new Promise((resolve, reject) => {
357
- const spec = `${bindHost}:${listenPort}:${targetHost}:${targetPort}`
358
- let child
359
- try {
360
- child = this.spawnSsh(['-N', '-o', 'ExitOnForwardFailure=yes', '-R', spec, '--', this.pool.destination()])
361
- } catch (err) { return reject(err) }
362
- let stderr = ''
363
- let settled = false
364
- const fail = (err) => {
365
- if (settled) return
366
- settled = true
367
- clearTimeout(timer)
368
- try { child.kill() } catch {}
369
- reject(err)
370
- }
371
- child.stderr.on('data', (d) => {
372
- stderr += d
373
- // Nothing prints on success; an error before the grace window is the
374
- // only signal `ssh -N` gives that the forward did not take.
375
- if (/warning|error|failed|refused|denied|cannot|not permitted|unable/i.test(String(d))) {
376
- fail(new Error(`reverse forward ${spec} failed: ${stderr.trim()}`))
377
- }
378
- })
379
- child.on('error', fail)
380
- // `ssh -N` stays in the foreground; a process that outlives the grace
381
- // window means the remote listener was accepted.
382
- const timer = setTimeout(() => {
383
- if (settled) return
384
- settled = true
385
- resolve({ child, close: () => { try { child.kill() } catch {} } })
386
- }, 700)
387
- child.on('close', (code) => {
388
- if (settled) return
389
- settled = true
390
- clearTimeout(timer)
391
- reject(new Error(`reverse forward ${spec} exited early (${code})${stderr ? ': ' + stderr.trim() : ''}`))
392
- })
393
- })
394
- }
395
-
396
- /** Superseded by reverseForward() (the CLI needs the target up front). */
397
- forwardIn(_host, _port, cb) {
398
- setImmediate(() => cb(new Error(
399
- 'the system-OpenSSH backend opens reverse forwards with `ssh -R`, which needs the target up front — use reverseForward()',
400
- )))
401
- }
402
-
403
- close() {
404
- this.closed = true
405
- for (const child of [...this.children]) {
406
- try { child.kill() } catch {}
407
- }
408
- this.children.clear()
409
- }
410
- }
411
-
412
- /**
413
- * A system-OpenSSH pool: the same public surface as lib/pool.js's SshPool,
414
- * backed by the local `ssh` CLI. Callers cannot tell the two apart — see
415
- * test/openssh-backend.test.js, which drives both through one shared contract.
416
- */
417
- export class SystemOpenSshPool {
418
- constructor(config, opts = {}) {
419
- this.config = config
420
- // The native backend's JSON fingerprint registry is NOT an OpenSSH
421
- // known_hosts file. ActivePool supplies a dedicated plain-text path; the
422
- // fallback preserves direct-construction compatibility (issue #118).
423
- this._knownHostsFile = opts.opensshKnownHostsFile ?? opts.knownHostsFile
424
- this.client = null
425
- this.connecting = null
426
- this.proxyPool = null
427
- // Generational token, exactly as the native pool: a stale in-flight connect
428
- // must never hand this pool a connection to an old host.
429
- this.epoch = 0
430
- this.platform = 'unknown'
431
- this.gitBashPath = ''
432
- this.shellMode = 'native'
433
- this._detecting = null
434
- this.passwordResolver = null
435
- this.onReady = null
436
- this.onCloseHook = null
437
- /** The persistent `ssh -s ... sftp` session (kept across calls). */
438
- this._sftpSession = null
439
- this._sftpChild = null
440
- /** Memoized askpass secret for this target (null = not resolved yet). */
441
- this._secret = null
442
- this._secretPromise = null
443
- }
444
-
445
- /**
446
- * The config baseSshArgs should see. `opts.knownHostsFile` (a path, or a
447
- * function returning one, exactly like the native pool) used to be stored
448
- * and silently dropped — so a custom known_hosts never reached the CLI, and
449
- * tests had no way to keep loopback keys out of the user's real file.
450
- * Resolved per call so a function value is honored as late as the native
451
- * backend resolves it.
452
- */
453
- _argConfig() {
454
- const kh = typeof this._knownHostsFile === 'function' ? this._knownHostsFile() : this._knownHostsFile
455
- return kh ? { ...this.config, knownHostsFile: kh } : this.config
456
- }
457
-
458
- /** The destination OpenSSH should connect to (an alias passes through). */
459
- destination() {
460
- // A bare alias resolves through ~/.ssh/config inside ssh itself, so it is
461
- // handed over untouched; user/port ride on `-l`/`-p` when recorded.
462
- return String(this.config.host || '')
463
- }
464
-
465
- setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary }, previous) {
466
- const base = previous || this.config
467
- const wanted = []
468
- if (host !== undefined) wanted.push(['host', String(host)])
469
- if (port !== undefined && Number(port)) wanted.push(['port', Number(port)])
470
- if (username !== undefined) wanted.push(['username', String(username)])
471
- if (password !== undefined && password !== null) wanted.push(['password', String(password)])
472
- if (privateKeyPath !== undefined) wanted.push(['privateKeyPath', String(privateKeyPath)])
473
- if (passphrase !== undefined) wanted.push(['passphrase', String(passphrase)])
474
- if (workspace !== undefined) wanted.push(['workspace', String(workspace)])
475
- if (useAgent !== undefined) wanted.push(['useAgent', !!useAgent])
476
- if (keyboardInteractive !== undefined) wanted.push(['keyboardInteractive', !!keyboardInteractive])
477
- if (proxy !== undefined) wanted.push(['proxy', proxy])
478
- if (hostKeyMode !== undefined) wanted.push(['hostKeyMode', String(hostKeyMode)])
479
- // Issue #51: kept in step with the native pool's setTarget — the two
480
- // backends share one contract (see test/issue51-openssh-backend.test.js), so
481
- // a field one of them diffs must not be silently ignored by the other.
482
- if (backend !== undefined) wanted.push(['backend', String(backend)])
483
- if (sshBinary !== undefined) wanted.push(['sshBinary', String(sshBinary)])
484
- const differs = ([k, v]) => (k === 'proxy'
485
- ? JSON.stringify(base[k] ?? null) !== JSON.stringify(v ?? null)
486
- : base[k] !== v)
487
- if (wanted.some(differs)) {
488
- for (const [k, v] of wanted) this.config[k] = v
489
- this.platform = 'unknown'
490
- this.gitBashPath = ''
491
- this.shellMode = 'native'
492
- this._detecting = null
493
- this.close()
494
- }
495
- return this
496
- }
497
-
498
- /**
499
- * The secret to offer askpass, resolved once per target.
500
- *
501
- * `connect()` no longer has to run first: `exec`/`sftp` call this themselves,
502
- * so a pool that is only ever used for file listing still authenticates.
503
- */
504
- _resolveSecret() {
505
- if (this._secret !== null) return Promise.resolve(this._secret)
506
- if (this._secretPromise) return this._secretPromise
507
- const epoch = this.epoch
508
- this._secretPromise = (async () => {
509
- let secret = this.config.password || ''
510
- if (!secret && this.passwordResolver) {
511
- try { secret = (await this.passwordResolver()) || '' } catch { /* fall through */ }
512
- }
513
- if (!secret) secret = this.config.passphrase || ''
514
- // A target switch invalidates the answer; leave the memo for the new one.
515
- if (this.epoch === epoch) this._secret = String(secret || '')
516
- this._secretPromise = null
517
- return String(secret || '')
518
- })()
519
- return this._secretPromise
520
- }
521
-
522
- /** Validate the environment; there is no socket to hold open. */
523
- connect() {
524
- if (this.client) return Promise.resolve(this.client)
525
- if (this.connecting) return this.connecting
526
- const epoch = this.epoch
527
- const pending = this._doConnect(epoch)
528
- this.connecting = pending
529
- const clear = () => { if (this.epoch === epoch && this.connecting === pending) this.connecting = null }
530
- pending.then(clear, clear)
531
- return pending
532
- }
533
-
534
- async _doConnect(epoch) {
535
- const isCurrent = () => this.epoch === epoch
536
- const sshBinary = resolveSshBinary(this.config)
537
- if (!this.config.host) throw new Error('no host configured')
538
- if (!sshBinaryAvailable(sshBinary)) {
539
- throw new Error(
540
- `the system-OpenSSH backend needs a \`${sshBinary}\` executable on PATH`
541
- + ' — install OpenSSH, or set the backend back to "native"',
542
- )
543
- }
544
- const secret = await this._resolveSecret()
545
- if (!isCurrent()) throw new Error('ssh target changed during connect')
546
- // Native semantics are "connect() throws when the SSH connection fails", and
547
- // a probe also gives the settings page a real latency number. The CLI has no
548
- // socket to keep, so this is the only point where the target is proven.
549
- const probe = await this._runSsh(['--', this.destination(), 'true'], { timeoutMs: this.config.connectTimeoutMs || 15000 })
550
- if (!isCurrent()) throw new Error('ssh target changed during connect')
551
- if (probe.code !== 0) {
552
- throw new Error(`ssh failed (exit ${probe.code})${String(probe.stderr || '').trim() ? ': ' + String(probe.stderr).trim() : ''}`)
553
- }
554
- void secret
555
- const conn = new OpenSshConnection(this, { sshBinary, secret })
556
- this.client = conn
557
- if (this.onReady) { try { this.onReady(conn) } catch {} }
558
- return conn
559
- }
560
-
561
- /**
562
- * Run one `ssh` invocation and collect its result.
563
- *
564
- * @param {string[]} extraArgs - arguments appended after the shared base.
565
- * @param {object} [opts] - `timeoutMs`, `signal` (AbortSignal), `stdin`,
566
- * `onData(channel, chunk)` — a streaming tap the native backend has had
567
- * since issue #70. A background job's value is its LIVE output, which the
568
- * job ring must receive as it arrives; a backend that only returns the
569
- * accumulated text loses every byte the caller stopped waiting for
570
- * (issue #80). Tap errors are not command errors, so the call is guarded.
571
- * @returns {Promise<{code: number|null, signal: string|null, stdout: string, stderr: string}>}
572
- */
573
- async _runSsh(extraArgs, opts = {}) {
574
- if (!this.config.host) throw new Error('no host configured')
575
- const secret = await this._resolveSecret()
576
- const timeoutMs = opts.timeoutMs === 0 ? 0 : (opts.timeoutMs || this.config.commandTimeoutMs)
577
- const sshBinary = resolveSshBinary(this.config)
578
- const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), ...extraArgs]
579
- return new Promise((resolve) => {
580
- let child
581
- try {
582
- child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
583
- } catch (err) {
584
- return resolve({ code: -1, signal: 'SPAWN_FAILED', stdout: '', stderr: String((err && err.message) || err) })
585
- }
586
- // This path may stream a script into `bash -s` and can be written to
587
- // after the command already exited (Git Bash); a broken pipe there must
588
- // fail the call, not the process (issue #118).
589
- guardChildStdin(child)
590
- let stdout = ''
591
- let stderr = ''
592
- let settled = false
593
- let exitCode = null
594
- let exitSignal = null
595
- const cap = Math.max(this.config.maxOutputChars * 4, 1024 * 1024)
596
- const onData = typeof opts.onData === 'function' ? opts.onData : null
597
- const cleanupAbort = () => { if (opts.signal && onAbort) opts.signal.removeEventListener('abort', onAbort) }
598
- let onAbort = null
599
- const finish = () => {
600
- if (settled) return
601
- settled = true
602
- clearTimeout(timer)
603
- cleanupAbort()
604
- resolve({
605
- code: exitCode,
606
- signal: exitSignal,
607
- stdout: truncate(stdout, this.config.maxOutputChars),
608
- stderr: truncate(stderr, this.config.maxOutputChars),
609
- })
610
- }
611
- const killHard = () => { try { setTimeout(() => { try { child.kill('SIGKILL') } catch {} }, 800).unref?.() } catch {} }
612
- // No timer at all for an explicit no-deadline call (0) — see pool.js
613
- // _execRaw; arming one would fire at once or kill a promoted job (issue #95).
614
- const timer = timeoutMs > 0 ? setTimeout(() => {
615
- if (settled) return
616
- exitCode = -1
617
- exitSignal = 'TIMEOUT'
618
- try { child.kill() } catch {}
619
- killHard()
620
- finish()
621
- }, timeoutMs) : null
622
- if (opts.signal) {
623
- if (opts.signal.aborted) {
624
- try { child.kill() } catch {}
625
- exitCode = -1; exitSignal = 'ABORTED'
626
- return finish()
627
- }
628
- onAbort = () => {
629
- if (settled) return
630
- exitCode = -1; exitSignal = 'ABORTED'
631
- try { child.kill() } catch {}
632
- killHard()
633
- finish()
634
- }
635
- opts.signal.addEventListener('abort', onAbort, { once: true })
636
- }
637
- // The tap fires even past the local cap, exactly like the native
638
- // backend's: a promoted job's ring has its own bounds and must keep
639
- // receiving output the truncated return value no longer holds.
640
- child.stdout.on('data', (d) => {
641
- if (stdout.length < cap) stdout += d
642
- if (onData) { try { onData('stdout', d) } catch { /* tap errors are not command errors */ } }
643
- })
644
- child.stderr.on('data', (d) => {
645
- if (stderr.length < cap) stderr += d
646
- if (onData) { try { onData('stderr', d) } catch { /* tap errors are not command errors */ } }
647
- })
648
- child.on('error', (e) => {
649
- if (settled) return
650
- stderr += String((e && e.message) || e)
651
- exitCode = -1
652
- finish()
653
- })
654
- child.on('close', (code, sig) => {
655
- if (settled) return
656
- exitCode = code
657
- exitSignal = sig || null
658
- finish()
659
- })
660
- try { child.stdin.end(opts.stdin === undefined || opts.stdin === null ? undefined : String(opts.stdin)) } catch {}
661
- })
662
- }
663
-
664
- /** Detect the remote platform + locate Git Bash once; cached per target. */
665
- detect() {
666
- if (this.platform !== 'unknown') return Promise.resolve()
667
- if (this._detecting) return this._detecting
668
- this._detecting = this._detect().finally(() => { this._detecting = null })
669
- return this._detecting
670
- }
671
-
672
- async _detect() {
673
- let res
674
- try {
675
- res = await this._runSsh(['--', this.destination(), 'cmd /c ver'], { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
676
- } catch {
677
- this.platform = 'unknown'
678
- this.shellMode = 'native'
679
- return
680
- }
681
- const out = String(res.stdout || '') + '\n' + String(res.stderr || '')
682
- if (res.code === 0 && /microsoft windows/i.test(out)) {
683
- this.platform = 'windows'
684
- await this._resolveGitBash()
685
- return
686
- }
687
- try {
688
- const u = await this._runSsh(['--', this.destination(), 'uname -s'], { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
689
- if (/mingw|msys|cygwin/i.test(String(u.stdout || ''))) {
690
- this.platform = 'windows'
691
- await this._resolveGitBash()
692
- return
693
- }
694
- } catch { /* inconclusive — fall through to posix */ }
695
- this.platform = 'posix'
696
- this.shellMode = 'native'
697
- this.gitBashPath = ''
698
- }
699
-
700
- async _resolveGitBash() {
701
- const cfg = String(this.config.shell || '').trim()
702
- const exists = async (p) => {
703
- const r = await this._runSsh(['--', this.destination(), `cmd /c if exist "${p}" (echo Y) else (echo N)`], { timeoutMs: 8000 })
704
- return /Y/.test(String(r.stdout || ''))
705
- }
706
- if (cfg && cfg !== 'git-bash' && cfg !== 'native') {
707
- if (await exists(cfg)) { this.gitBashPath = cfg; this.shellMode = 'git-bash'; return }
708
- }
709
- if (cfg === 'native') { this.shellMode = 'native'; this.gitBashPath = ''; return }
710
- try {
711
- const r = await this._runSsh(['--', this.destination(), 'cmd /c where bash'], { timeoutMs: 8000 })
712
- const first = String(r.stdout || '').trim().split(/\r?\n/)[0].trim()
713
- if (first) { this.gitBashPath = first; this.shellMode = 'git-bash'; return }
714
- } catch { /* fall through to the candidate list */ }
715
- const candidates = [
716
- 'C:\\Program Files\\Git\\bin\\bash.exe',
717
- 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
718
- ...(process.env.LOCALAPPDATA ? [process.env.LOCALAPPDATA + '\\Programs\\Git\\bin\\bash.exe'] : []),
719
- ]
720
- for (const c of candidates) {
721
- if (await exists(c)) { this.gitBashPath = c; this.shellMode = 'git-bash'; return }
722
- }
723
- this.shellMode = 'git-bash'
724
- this.gitBashPath = ''
725
- }
726
-
727
- /** Run one remote command (Windows + Git Bash is wrapped exactly as native). */
728
- exec(command, timeoutMsOrOpts) {
729
- const opts = timeoutMsOrOpts && typeof timeoutMsOrOpts === 'object' ? timeoutMsOrOpts : { timeoutMs: timeoutMsOrOpts }
730
- return this.detect().then(() => {
731
- const timeoutMs = opts.timeoutMs === 0 ? 0 : (opts.timeoutMs || this.config.commandTimeoutMs)
732
- if (this.platform === 'windows' && this.gitBashPath) {
733
- // Pipe the script to `bash -s` over stdin: no quoting round-trip, so
734
- // quotes/backslashes/newlines survive verbatim (same as the native pool).
735
- return this._runSsh(['--', this.destination(), `"${this.gitBashPath}" -s`], { timeoutMs, signal: opts.signal, stdin: String(command), onData: opts.onData })
736
- }
737
- return this._runSsh(['--', this.destination(), String(command)], { timeoutMs, signal: opts.signal, onData: opts.onData })
738
- })
739
- }
740
-
741
- /** Open a fresh `ssh -s <dest> sftp` session and its ssh2 SFTP engine. */
742
- async _openSftpChannel() {
743
- const Sftp = loadSftpEngine()
744
- const secret = await this._resolveSecret()
745
- const sshBinary = resolveSshBinary(this.config)
746
- const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), '-s', this.destination(), 'sftp']
747
- const child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
748
-
749
- // ssh2's SFTP engine only reaches `_protocol` for channelData/channelClose,
750
- // and reads `_remoteIdentRaw` to pick its packet sizes.
751
- //
752
- // ## Flow control, the subtle part
753
- //
754
- // Over real SSH the engine's send window is topped up by CHANNEL_WINDOW_ADJUST
755
- // messages from the peer. On a raw `ssh -s sftp` pipe THERE ARE NO SUCH
756
- // MESSAGES — the local ssh owns the SSH-layer window and the server's grants,
757
- // and all we have is a byte pipe with OS-level backpressure. So the engine's
758
- // window has to be mapped onto the pipe's writability:
759
- //
760
- // • a write the pipe accepts → more will fit;
761
- // • the pipe fills (`stdin.write` returns false) → clamp the window so the
762
- // engine buffers the remainder instead of queueing it all in memory;
763
- // • the pipe drains → grant the window back and let the engine flush.
764
- //
765
- // The trap, and why the constants below are what they are: ssh2 arms its
766
- // flush callback (`_waitWindow` / `_chunkcb = drainBuffer`) ONLY from inside
767
- // its own subtraction, at the moment that subtraction takes the window to
768
- // exactly 0. So the window must be handed over in EXACT MULTIPLES of
769
- // packetSize and then left alone: the engine's own arithmetic then lands on 0
770
- // during normal operation and arms the flush callback we depend on.
771
- //
772
- // Do NOT "help" by clamping the window to 0 from inside channelData when the
773
- // pipe reports itself full. That sets the window to 0 AFTER the subtraction
774
- // has already happened, so the callback is never armed and the buffered
775
- // remainder is never flushed — the transfer deadlocks with a full window.
776
- // (Measured: a 4 MB upload stopped dead after 32 KB, with `_buffer.length`
777
- // stuck at 1 and no callback pending.) The pipe's own `drain` event is the
778
- // only place the window is refilled.
779
- //
780
- // Also tempting-but-wrong: adding each received packet's length to the
781
- // window. That happens to work for a DOWNLOAD (the peer's data is the
782
- // window) and deadlocks an upload, because a write's acknowledgements are
783
- // tiny status packets while each send consumes ~32 KB.
784
- //
785
- // See scripts/integration-openssh-large.mjs, which is what caught all of this.
786
- const PACKET = 32768
787
- const GRANT = PACKET * 8 // 256 KB per burst, and a multiple of packetSize
788
- const chan = { sftp: null }
789
- const fakeClient = {
790
- _protocol: {
791
- _remoteIdentRaw: Buffer.from('SSH-2.0-OpenSSH'),
792
- // Hand the bytes to the pipe and nothing else. Backpressure is expressed
793
- // through the engine's own window draining (see above); the OS pipe
794
- // buffer plus Node's write buffer absorb the in-flight remainder.
795
- channelData(_id, data) { try { child.stdin.write(data) } catch { /* close handles it */ } },
796
- channelClose() { try { child.stdin.end() } catch {} },
797
- },
798
- }
799
- const chanInfo = {
800
- type: 'sftp',
801
- incoming: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
802
- outgoing: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
803
- }
804
- // The stdin pipe can die underneath the engine at any moment (the remote
805
- // side of the sftp subsystem exits, the link drops — issue #118). Each write
806
- // after that fails, and without an 'error' listener the failure is an
807
- // uncaught exception that takes the whole Host down. Registering the guard
808
- // here, next to the only two places that write to this pipe, keeps the
809
- // blast radius at "this session is gone": 'close' fires as usual and the
810
- // cached session is dropped by sftp()'s own handler.
811
- guardChildStdin(child, () => { try { child.kill() } catch { /* already gone */ } })
812
- const sftp = new Sftp(fakeClient, chanInfo, {})
813
- chan.sftp = sftp
814
-
815
- // The pipe has room again: grant the window back and let the engine flush
816
- // whatever it buffered while the pipe was full.
817
- const onStdinDrain = () => {
818
- if (!chan.sftp) return
819
- chan.sftp.outgoing.window = GRANT
820
- if (chan.sftp._waitWindow) {
821
- chan.sftp._waitWindow = false
822
- const cb = chan.sftp._chunkcb
823
- chan.sftp._chunkcb = undefined
824
- if (typeof cb === 'function') cb.call(chan.sftp)
825
- }
826
- }
827
- child.stdin.on('drain', onStdinDrain)
828
- // A dead SSH process reports stdin EPIPE asynchronously. Without a stream
829
- // error listener Node crashes the host before close/drop can reset the
830
- // cached session (issue #118); kill it so that existing recovery runs.
831
- child.stdin.on('error', () => { try { child.kill() } catch {} })
832
-
833
- return new Promise((resolve, reject) => {
834
- let stderr = ''
835
- let settled = false
836
- const done = (err) => {
837
- if (settled) return
838
- settled = true
839
- clearTimeout(timer)
840
- if (err) { try { child.kill() } catch {} ; reject(err) } else resolve({ child, sftp })
841
- }
842
- const timer = setTimeout(() => {
843
- done(new Error(`sftp session to ${this.destination()} timed out${stderr ? ': ' + stderr.trim() : ''}`))
844
- }, this.config.commandTimeoutMs)
845
- child.stderr.on('data', (d) => { stderr += d })
846
- sftp.on('error', (e) => done(new Error('sftp session failed: ' + ((e && e.message) || e))))
847
- sftp.on('ready', () => done(null))
848
- child.on('error', (e) => done(e))
849
- child.on('close', (code) => done(new Error(`ssh sftp exited (${code})${stderr ? ': ' + stderr.trim() : ''}`)))
850
- // Inbound is simpler: the local ssh already did the SSH-level window
851
- // accounting before handing us these bytes, so they just go straight in.
852
- child.stdout.on('data', (d) => { sftp.push(d) })
853
- child.stdout.on('end', () => { try { sftp.push(null) } catch { /* already gone */ } })
854
- sftp._init()
855
- })
856
- }
857
-
858
- /**
859
- * A persistent SFTP session, kept across calls: the picker and the explorer
860
- * issue one listing per interaction, and re-handshaking each time would be
861
- * visibly slow. A session that dies is dropped so the next call reconnects.
862
- */
863
- sftp() {
864
- if (this._sftpSession) return this._sftpSession
865
- const epoch = this.epoch
866
- const session = this._openSftpChannel().then(({ child, sftp }) => {
867
- const drop = () => {
868
- if (this._sftpSession === session) this._sftpSession = null
869
- if (this._sftpChild === child) this._sftpChild = null
870
- }
871
- child.on('close', drop)
872
- sftp.on('end', drop)
873
- sftp.on('error', drop)
874
- // A target switch during the handshake must not adopt the old host's
875
- // session (the same generational guard connect() uses).
876
- if (this.epoch !== epoch) {
877
- try { child.kill() } catch {}
878
- throw new Error('ssh target changed while opening sftp')
879
- }
880
- this._sftpChild = child
881
- return buildSftpSurface(sftp, {
882
- commandTimeoutMs: this.config.commandTimeoutMs,
883
- onTimeout: () => {
884
- // A timed-out SFTP session is dead: kill the child and drop the cached
885
- // session so the next call re-handshakes instead of queueing behind the
886
- // wedged one (issue #65).
887
- try { child.kill() } catch { /* already gone */ }
888
- drop()
889
- },
890
- })
891
- })
892
- // Never cache a rejected open: the next call must retry rather than get the
893
- // same error back forever (a failed handshake is usually transient).
894
- session.catch(() => { if (this._sftpSession === session) this._sftpSession = null })
895
- this._sftpSession = session
896
- return session
897
- }
898
-
899
- invalidate() {
900
- this.epoch++
901
- const client = this.client
902
- this.client = null
903
- this.connecting = null
904
- this._secret = null
905
- this._secretPromise = null
906
- if (client) { try { client.close() } catch {} }
907
- this._dropSftpSession()
908
- if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
909
- if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
910
- }
911
-
912
- _dropSftpSession() {
913
- const session = this._sftpSession
914
- this._sftpSession = null
915
- if (this._sftpChild) {
916
- try { this._sftpChild.kill() } catch {}
917
- this._sftpChild = null
918
- }
919
- // Swallow the rejection: nobody awaits a session we are tearing down.
920
- if (session && typeof session.catch === 'function') session.catch(() => {})
921
- }
922
-
923
- close() {
924
- this.epoch++
925
- const client = this.client
926
- this.client = null
927
- this.connecting = null
928
- this._secret = null
929
- this._secretPromise = null
930
- if (client) { try { client.close() } catch {} }
931
- this._dropSftpSession()
932
- if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
933
- if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
934
- }
935
- }
936
-
937
- /** Pick the pool class for a config: 'openssh' backend, else the native pool. */
938
- export function isSystemOpenSshBackend(config = {}) {
939
- return String(config.backend || '').toLowerCase() === 'openssh'
940
- }
1
+ // dsh-remote — the "system OpenSSH" SSH backend (issue #51).
2
+ //
3
+ // ## Why this exists
4
+ //
5
+ // The default backend (lib/pool.js) speaks SSH itself through ssh2, so it can
6
+ // only use the authentication methods ssh2 implements: password, private key,
7
+ // ssh-agent and keyboard-interactive. Enterprise hosts that only allow
8
+ // GSSAPI/Kerberos are unreachable, even though `ssh <alias>` in the user's own
9
+ // terminal works — the local Kerberos ticket (kinit) is simply not something
10
+ // ssh2 knows how to present.
11
+ //
12
+ // This backend delegates the transport to the LOCAL `ssh` executable, so every
13
+ // `~/.ssh/config` feature the user already relies on applies: gssapi-with-mic,
14
+ // ProxyJump, ProxyCommand, ControlPath, Host aliases, IdentityFile,
15
+ // PKCS11Provider, Match blocks… Anything OpenSSH can do, this backend can do,
16
+ // because OpenSSH is the one doing it.
17
+ //
18
+ // ## How each primitive is implemented
19
+ //
20
+ // exec → `ssh <opts> -- <dest> <command>` (one process per call)
21
+ // sftp → `ssh <opts> -s <dest> sftp` + ssh2's OWN SFTP protocol engine
22
+ // driven over the resulting raw byte stream
23
+ // forwardOut → `ssh <opts> -W <host>:<port> <dest>` (one process per tunnel)
24
+ // reverse → `ssh <opts> -N -R <bind>:<port>:<h>:<p> <dest>`
25
+ //
26
+ // The SFTP one deserves a note, because it is the reason this backend did not
27
+ // have to reimplement file transfer: `ssh -s <dest> sftp` on stdio is a PLAIN
28
+ // SFTP v3 byte stream (verified against a real host — the subsystem replies
29
+ // with its VERSION packet and nothing else on stdout). ssh2 already ships a
30
+ // complete, battle-tested SFTP implementation that speaks exactly that protocol
31
+ // over a duplex stream, so this module gives it a minimal `_protocol` shim and
32
+ // hands it the child process's stdio. File transfer therefore has the same
33
+ // semantics — and the same large-packet optimisations — as the native backend.
34
+ //
35
+ // ## Trade-offs (documented, not hidden)
36
+ //
37
+ // • spawn-per-operation: unlike the native pool there is no long-lived
38
+ // connection multiplexed across commands, so each `exec`/`forwardOut` pays
39
+ // a fresh SSH handshake. That is inherent to delegating to the `ssh` CLI:
40
+ // Windows OpenSSH rejects ControlMaster ("getsockname failed: Not a
41
+ // socket", measured), and a portable multiplexing layer would be a second
42
+ // implementation of what the native backend already does. The SFTP path IS
43
+ // kept persistent, because the workspace picker and the explorer hammer it.
44
+ // • the passphrase/password prompt: OpenSSH asks for both through the same
45
+ // askpass channel, so when a secret is configured this backend offers it
46
+ // for whichever prompt appears (password first, then passphrase). A host
47
+ // needing two DIFFERENT secrets is not representable here — use the native
48
+ // backend for that.
49
+ // • reverse forwards need their target up front (the CLI takes it as an
50
+ // argument), so they are exposed as `reverseForward()` and ForwardManager
51
+ // prefers it when present.
52
+ // • host keys are checked by ssh itself against the user's own known_hosts,
53
+ // not against the plugin's TOFU store: making `ssh` use a different trust
54
+ // anchor per machine is exactly the kind of override that breaks the
55
+ // enterprise setups this backend exists to serve. `hostKeyMode` maps onto
56
+ // StrictHostKeyChecking instead.
57
+
58
+ import { spawn } from 'node:child_process'
59
+ import { accessSync, chmodSync, constants as fsConstants, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
60
+ import { createRequire } from 'node:module'
61
+ import { EventEmitter } from 'node:events'
62
+ import { homedir, tmpdir } from 'node:os'
63
+ import path from 'node:path'
64
+ import { Duplex } from 'node:stream'
65
+ import { buildSftpSurface } from './sftp-surface.js'
66
+ import { truncate } from './paths.js'
67
+
68
+ // The SFTP protocol engine lives at lib/protocol/SFTP.js inside ssh2 and is not
69
+ // part of its public API. Creating it through createRequire keeps this module
70
+ // ESM-clean while still reaching it; if a future ssh2 moves it, this fails with
71
+ // an actionable message instead of a bare MODULE_NOT_FOUND at connect time.
72
+ const require_ = createRequire(import.meta.url)
73
+ let SftpEngine = null
74
+ export function loadSftpEngine() {
75
+ if (SftpEngine) return SftpEngine
76
+ try {
77
+ const entry = require_.resolve('ssh2')
78
+ const sftpPath = entry.replace(/lib[\\/]index\.js$/, 'lib/protocol/SFTP.js')
79
+ SftpEngine = require_(sftpPath).SFTP
80
+ } catch (err) {
81
+ throw new Error("system-OpenSSH backend could not load ssh2's SFTP engine: " + ((err && err.message) || err))
82
+ }
83
+ if (typeof SftpEngine !== 'function') {
84
+ throw new Error("system-OpenSSH backend found no SFTP engine in this ssh2 install")
85
+ }
86
+ return SftpEngine
87
+ }
88
+
89
+ /** The `ssh` executable this backend drives (config override wins). */
90
+ export function resolveSshBinary(config = {}) {
91
+ return String(config.sshBinary || '').trim() || 'ssh'
92
+ }
93
+
94
+ /**
95
+ * Path of the user's own known_hosts. Exposed for the UI; the backend itself
96
+ * never points ssh at a different file (see the header).
97
+ */
98
+ export function defaultKnownHostsPath() {
99
+ return path.join(homedir(), '.ssh', 'known_hosts')
100
+ }
101
+
102
+ /**
103
+ * Translate `hostKeyMode` into OpenSSH's StrictHostKeyChecking.
104
+ *
105
+ * `accept-new` is ssh's own default on modern OpenSSH and matches the plugin's
106
+ * TOFU default; `verify` refuses unknown hosts; `off` accepts anything.
107
+ */
108
+ export function hostKeyArgs(config = {}) {
109
+ const mode = config.hostKeyMode === 'verify' || config.hostKeyMode === 'off' ? config.hostKeyMode : 'accept-new'
110
+ const strict = mode === 'verify' ? 'yes' : mode === 'off' ? 'no' : 'accept-new'
111
+ return ['-o', `StrictHostKeyChecking=${strict}`]
112
+ }
113
+
114
+ /**
115
+ * One private directory per process. Different DSH/Node processes must never
116
+ * rewrite a helper while another process is executing it (Windows EBUSY).
117
+ * The helper carries no secret; it reads the secret from its environment.
118
+ */
119
+ let askpassDirectory = null
120
+ let readyAskpassHelper = null
121
+ export function askpassDir() {
122
+ if (!askpassDirectory) {
123
+ const dir = mkdtempSync(path.join(tmpdir(), 'dsh-remote-askpass-'))
124
+ askpassDirectory = dir
125
+ process.once('exit', () => { try { rmSync(dir, { recursive: true, force: true }) } catch { /* still in use */ } })
126
+ }
127
+ return askpassDirectory
128
+ }
129
+
130
+ /**
131
+ * Ensure an askpass helper exists and return its path.
132
+ *
133
+ * The helper prints $DSH_REMOTE_SSH_SECRET. Passing the secret through the
134
+ * environment (rather than as an argument or a file) keeps it out of `ps`,
135
+ * argv and the filesystem. The Windows helper is a .cmd that invokes Node via
136
+ * `process.execPath`, because `@echo %VAR%` would mangle secrets containing cmd
137
+ * metacharacters (&, %, ^ …) and a bare `echo` is not a shell we control.
138
+ */
139
+ export function ensureAskpassHelper() {
140
+ if (readyAskpassHelper && existsSync(readyAskpassHelper)) return readyAskpassHelper
141
+ const dir = askpassDir()
142
+ try { mkdirSync(dir, { recursive: true }) } catch { /* already there */ }
143
+ if (process.platform === 'win32') {
144
+ const js = path.join(dir, 'askpass.js')
145
+ const cmd = path.join(dir, 'askpass.cmd')
146
+ try {
147
+ writeFileSync(js, 'process.stdout.write((process.env.DSH_REMOTE_SSH_SECRET || "") + "\\n")\n')
148
+ writeFileSync(cmd, '@echo off\r\n"' + process.execPath + '" "' + js + '"\r\n')
149
+ } catch (err) {
150
+ throw new Error('system-OpenSSH backend could not write its askpass helper: ' + ((err && err.message) || err))
151
+ }
152
+ readyAskpassHelper = cmd
153
+ return cmd
154
+ }
155
+ const sh = path.join(dir, 'askpass.sh')
156
+ try {
157
+ writeFileSync(sh, '#!/bin/sh\nprintf \'%s\\n\' "$DSH_REMOTE_SSH_SECRET"\n')
158
+ try { chmodSync(sh, 0o700) } catch { /* best effort on odd filesystems */ }
159
+ } catch (err) {
160
+ throw new Error('system-OpenSSH backend could not write its askpass helper: ' + ((err && err.message) || err))
161
+ }
162
+ readyAskpassHelper = sh
163
+ return sh
164
+ }
165
+
166
+ /** Env that hands the secret to the askpass helper (never argv, never a file). */
167
+ export function askpassEnv(secret) {
168
+ return {
169
+ ...process.env,
170
+ SSH_ASKPASS: ensureAskpassHelper(),
171
+ SSH_ASKPASS_REQUIRE: 'force',
172
+ DISPLAY: process.env.DISPLAY || ':0',
173
+ DSH_REMOTE_SSH_SECRET: String(secret),
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Keep an EPIPE on a child's stdin from becoming a process-wide crash.
179
+ *
180
+ * A child that stops reading — the remote side of `ssh -s sftp` dying mid-
181
+ * transfer is the one that bites — makes the NEXT write to its stdin fail. Node
182
+ * reports that asynchronously through the Writable's `'error'` event, so a
183
+ * synchronous `try/catch` around `write()` never sees it; an unhandled
184
+ * `'error'` on a stream is an uncaught exception, and the Host treats one of
185
+ * those as fatal (issue #118: `dsh: fatal uncaught exception: Error: write
186
+ * EPIPE` → the whole app's host process exits and every session is lost).
187
+ *
188
+ * Every `spawn` in this file therefore gets this hook: swallow the pipe error,
189
+ * report it to `onError` when the caller has cleanup to do, and let the
190
+ * existing `'close'`/`'error'` handling own the rest. A missing `ssh` binary
191
+ * is a different signal — spawn reports it on the CHILD, not on its stdin — so
192
+ * it still reaches the caller as a real error.
193
+ *
194
+ * @param {import('node:child_process').ChildProcess} child
195
+ * @param {(err: Error) => void} [onError] - e.g. drop the cached SFTP session.
196
+ * @returns {import('node:child_process').ChildProcess} the same child.
197
+ */
198
+ export function guardChildStdin(child, onError) {
199
+ const stdin = child && child.stdin
200
+ if (!stdin || typeof stdin.on !== 'function') return child
201
+ // A listener is the difference between "this stream reported a problem" and
202
+ // "this process died": without one Node re-throws the error as an uncaught
203
+ // exception. There is nothing to retry here — the pipe is gone — so all that
204
+ // is left is to let the caller drop whatever it cached for this child; the
205
+ // child's own 'close'/'error' handling still reports the real failure.
206
+ stdin.on('error', (err) => {
207
+ if (typeof onError === 'function') { try { onError(err) } catch { /* best effort */ } }
208
+ })
209
+ return child
210
+ }
211
+
212
+ /** Is `ssh` runnable? Used to fail with an actionable message, not ENOENT. */
213
+ export function sshBinaryAvailable(binary) {
214
+ if (binary.includes('/') || binary.includes('\\')) {
215
+ try { accessSync(binary, fsConstants.X_OK); return true } catch { return false }
216
+ }
217
+ const exts = process.platform === 'win32'
218
+ ? String(process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';').filter(Boolean)
219
+ : ['']
220
+ for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
221
+ if (!dir) continue
222
+ for (const ext of exts) {
223
+ try { accessSync(path.join(dir, binary + ext), fsConstants.X_OK); return true } catch { /* keep looking */ }
224
+ }
225
+ }
226
+ return false
227
+ }
228
+
229
+ /**
230
+ * Options shared by every `ssh` invocation for this target.
231
+ *
232
+ * Deliberately NOT passed: PreferredAuthentications / GSSAPIAuthentication /
233
+ * PubkeyAcceptedKeyTypes / IdentitiesOnly-from-the-alias / ProxyJump-from-the-
234
+ * alias. Those must come from the user's `~/.ssh/config` — overriding them is
235
+ * precisely what would break the enterprise setups this backend exists for.
236
+ *
237
+ * @param {object} config - the pool config.
238
+ * @param {object} [opts]
239
+ * @param {boolean} [opts.forSecret] - true when a secret will be offered via
240
+ * askpass, which means BatchMode must be OFF (BatchMode forbids every
241
+ * interactive prompt, askpass included) and the prompt count bounded instead.
242
+ */
243
+ export function baseSshArgs(config, { forSecret = false } = {}) {
244
+ const args = []
245
+ if (config.port && Number(config.port) !== 22) args.push('-p', String(Number(config.port)))
246
+ if (config.username) args.push('-l', String(config.username))
247
+ if (config.privateKeyPath) args.push('-i', String(config.privateKeyPath))
248
+ // An explicit jump host — the same shape the native backend's `proxy` takes.
249
+ // A jump host that comes from ~/.ssh/config needs nothing here.
250
+ const proxy = config.proxy
251
+ if (proxy && proxy.host) {
252
+ const user = proxy.username ? `${proxy.username}@` : ''
253
+ const port = proxy.port && Number(proxy.port) !== 22 ? `:${Number(proxy.port)}` : ''
254
+ args.push('-J', `${user}${proxy.host}${port}`)
255
+ }
256
+ // An explicit known_hosts file (tests keep loopback keys OUT of the user's
257
+ // real ~/.ssh/known_hosts with this; ssh ignores $HOME on some platforms).
258
+ // Checking strength is unchanged — StrictHostKeyChecking below still applies.
259
+ if (config.knownHostsFile) args.push('-o', `UserKnownHostsFile=${config.knownHostsFile}`)
260
+ args.push(...hostKeyArgs(config))
261
+ const connectSecs = Math.max(1, Math.round((Number(config.connectTimeoutMs) || 15000) / 1000))
262
+ args.push('-o', `ConnectTimeout=${connectSecs}`, '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3')
263
+ // Without a configured secret we must not hang on an interactive prompt:
264
+ // BatchMode makes ssh fail fast instead, and leaves key/agent/GSSAPI intact.
265
+ if (!forSecret) args.push('-o', 'BatchMode=yes')
266
+ else args.push('-o', 'NumberOfPasswordPrompts=1')
267
+ return args
268
+ }
269
+
270
+ /**
271
+ * One live system-OpenSSH connection.
272
+ *
273
+ * This deliberately mimics the ssh2 Client surface the rest of the plugin
274
+ * consumes — `forwardOut` plus a reverse-forward capability — so
275
+ * ForwardManager/WebAttach work unchanged. It is an EventEmitter because the
276
+ * native pool's client is one and callers attach listeners to it.
277
+ */
278
+ export class OpenSshConnection extends EventEmitter {
279
+ constructor(pool, { sshBinary, secret }) {
280
+ super()
281
+ this.pool = pool
282
+ this.sshBinary = sshBinary
283
+ this.secret = secret
284
+ this.closed = false
285
+ /** Live child processes to reap on close. */
286
+ this.children = new Set()
287
+ }
288
+
289
+ shortDescription() {
290
+ return `${this.pool.destination()} via ${this.sshBinary}`
291
+ }
292
+
293
+ spawnSsh(extraArgs, { tty = false } = {}) {
294
+ if (this.closed) throw new Error('ssh connection closed')
295
+ const args = [
296
+ ...baseSshArgs(this.pool._argConfig(), { forSecret: !!this.secret }),
297
+ ...extraArgs,
298
+ ]
299
+ const child = spawn(this.sshBinary, args, {
300
+ stdio: ['pipe', 'pipe', 'pipe'],
301
+ env: this.secret ? askpassEnv(this.secret) : undefined,
302
+ })
303
+ this.children.add(child)
304
+ const reap = () => this.children.delete(child)
305
+ // Every connection-level child goes through here (the `ssh -W` forward
306
+ // channel and the `ssh -N` reverse forward), so the stdin guard for those
307
+ // two paths belongs here rather than at each call site: a tunnel whose peer
308
+ // vanished must end as a closed channel, not as a fatal EPIPE (issue #118).
309
+ guardChildStdin(child)
310
+ child.on('close', reap)
311
+ child.on('error', reap)
312
+ if (tty) { /* no pty support through the CLI without a tty helper */ }
313
+ return child
314
+ }
315
+
316
+ /**
317
+ * Local forward: carry bytes to <destHost>:<destPort> as seen FROM the
318
+ * remote, through `ssh -W`.
319
+ *
320
+ * @returns {boolean} true synchronously, so capability probes can be sync.
321
+ */
322
+ forwardOut(_srcHost, _srcPort, destHost, destPort, cb) {
323
+ let child
324
+ try {
325
+ child = this.spawnSsh(['-W', `${destHost}:${destPort}`, '--', this.pool.destination()])
326
+ } catch (err) {
327
+ setImmediate(() => cb(err))
328
+ return true
329
+ }
330
+ // `ssh -W` reports failures on stderr and then exits; surface that as the
331
+ // channel error so the caller destroys its socket instead of hanging.
332
+ let stderr = ''
333
+ let handed = false
334
+ const channel = new Duplex({
335
+ read() {},
336
+ write(chunk, _enc, done) { try { child.stdin.write(chunk, done) } catch (e) { done(e) } },
337
+ final(done) { try { child.stdin.end(done) } catch { done() } },
338
+ destroy(err, done) { try { child.kill() } catch {} ; done(err) },
339
+ })
340
+ channel.close = () => { try { child.kill() } catch {} }
341
+ child.stderr.on('data', (d) => { stderr += d })
342
+ child.stdout.on('data', (d) => channel.push(d))
343
+ child.stdout.on('end', () => channel.push(null))
344
+ child.on('error', (e) => { if (!handed) { handed = true; cb(e); return } channel.destroy(e) })
345
+ child.on('close', (code) => {
346
+ if (handed) { channel.push(null); return }
347
+ handed = true
348
+ if (code === 0) { cb(null, channel); return }
349
+ cb(new Error(`ssh -W to ${destHost}:${destPort} failed (exit ${code})${stderr ? ': ' + stderr.trim() : ''}`))
350
+ })
351
+ return true
352
+ }
353
+
354
+ /** Tells ForwardManager that the CLI-specific reverse path is available. */
355
+ get supportsReverseForward() { return true }
356
+
357
+ /**
358
+ * Reverse forward: ask the REMOTE to listen on <bindHost>:<listenPort> and
359
+ * carry connections to <targetHost>:<targetPort>. Unlike ssh2's two-phase
360
+ * `forwardIn` + `tcpip`, the `ssh -R` CLI takes the final target as an
361
+ * argument, so nothing has to be resolved lazily.
362
+ *
363
+ * @returns {Promise<{child: object, close: Function}>}
364
+ */
365
+ reverseForward({ bindHost = '127.0.0.1', listenPort, targetHost = '127.0.0.1', targetPort }) {
366
+ return new Promise((resolve, reject) => {
367
+ const spec = `${bindHost}:${listenPort}:${targetHost}:${targetPort}`
368
+ let child
369
+ try {
370
+ child = this.spawnSsh(['-N', '-o', 'ExitOnForwardFailure=yes', '-R', spec, '--', this.pool.destination()])
371
+ } catch (err) { return reject(err) }
372
+ let stderr = ''
373
+ let settled = false
374
+ const fail = (err) => {
375
+ if (settled) return
376
+ settled = true
377
+ clearTimeout(timer)
378
+ try { child.kill() } catch {}
379
+ reject(err)
380
+ }
381
+ child.stderr.on('data', (d) => {
382
+ stderr += d
383
+ // Nothing prints on success; an error before the grace window is the
384
+ // only signal `ssh -N` gives that the forward did not take.
385
+ if (/warning|error|failed|refused|denied|cannot|not permitted|unable/i.test(String(d))) {
386
+ fail(new Error(`reverse forward ${spec} failed: ${stderr.trim()}`))
387
+ }
388
+ })
389
+ child.on('error', fail)
390
+ // `ssh -N` stays in the foreground; a process that outlives the grace
391
+ // window means the remote listener was accepted.
392
+ const timer = setTimeout(() => {
393
+ if (settled) return
394
+ settled = true
395
+ resolve({ child, close: () => { try { child.kill() } catch {} } })
396
+ }, 700)
397
+ child.on('close', (code) => {
398
+ if (settled) return
399
+ settled = true
400
+ clearTimeout(timer)
401
+ reject(new Error(`reverse forward ${spec} exited early (${code})${stderr ? ': ' + stderr.trim() : ''}`))
402
+ })
403
+ })
404
+ }
405
+
406
+ /** Superseded by reverseForward() (the CLI needs the target up front). */
407
+ forwardIn(_host, _port, cb) {
408
+ setImmediate(() => cb(new Error(
409
+ 'the system-OpenSSH backend opens reverse forwards with `ssh -R`, which needs the target up front — use reverseForward()',
410
+ )))
411
+ }
412
+
413
+ close() {
414
+ this.closed = true
415
+ for (const child of [...this.children]) {
416
+ try { child.kill() } catch {}
417
+ }
418
+ this.children.clear()
419
+ }
420
+ }
421
+
422
+ /**
423
+ * A system-OpenSSH pool: the same public surface as lib/pool.js's SshPool,
424
+ * backed by the local `ssh` CLI. Callers cannot tell the two apart — see
425
+ * test/openssh-backend.test.js, which drives both through one shared contract.
426
+ */
427
+ export class SystemOpenSshPool {
428
+ constructor(config, opts = {}) {
429
+ this.config = config
430
+ // The native backend's JSON fingerprint registry is NOT an OpenSSH
431
+ // known_hosts file. ActivePool supplies a dedicated plain-text path; the
432
+ // fallback preserves direct-construction compatibility (issue #118).
433
+ this._knownHostsFile = opts.opensshKnownHostsFile ?? opts.knownHostsFile
434
+ this.client = null
435
+ this.connecting = null
436
+ this.proxyPool = null
437
+ // Generational token, exactly as the native pool: a stale in-flight connect
438
+ // must never hand this pool a connection to an old host.
439
+ this.epoch = 0
440
+ this.platform = 'unknown'
441
+ this.gitBashPath = ''
442
+ this.shellMode = 'native'
443
+ this._detecting = null
444
+ this.passwordResolver = null
445
+ this.onReady = null
446
+ this.onCloseHook = null
447
+ /** The persistent `ssh -s ... sftp` session (kept across calls). */
448
+ this._sftpSession = null
449
+ this._sftpChild = null
450
+ /** Memoized askpass secret for this target (null = not resolved yet). */
451
+ this._secret = null
452
+ this._secretPromise = null
453
+ }
454
+
455
+ /**
456
+ * The config baseSshArgs should see. `opts.knownHostsFile` (a path, or a
457
+ * function returning one, exactly like the native pool) used to be stored
458
+ * and silently dropped — so a custom known_hosts never reached the CLI, and
459
+ * tests had no way to keep loopback keys out of the user's real file.
460
+ * Resolved per call so a function value is honored as late as the native
461
+ * backend resolves it.
462
+ */
463
+ _argConfig() {
464
+ const kh = typeof this._knownHostsFile === 'function' ? this._knownHostsFile() : this._knownHostsFile
465
+ return kh ? { ...this.config, knownHostsFile: kh } : this.config
466
+ }
467
+
468
+ /** The destination OpenSSH should connect to (an alias passes through). */
469
+ destination() {
470
+ // A bare alias resolves through ~/.ssh/config inside ssh itself, so it is
471
+ // handed over untouched; user/port ride on `-l`/`-p` when recorded.
472
+ return String(this.config.host || '')
473
+ }
474
+
475
+ setTarget({ host, port, username, password, privateKeyPath, passphrase, workspace, useAgent, keyboardInteractive, proxy, hostKeyMode, backend, sshBinary }, previous) {
476
+ const base = previous || this.config
477
+ const wanted = []
478
+ if (host !== undefined) wanted.push(['host', String(host)])
479
+ if (port !== undefined && Number(port)) wanted.push(['port', Number(port)])
480
+ if (username !== undefined) wanted.push(['username', String(username)])
481
+ if (password !== undefined && password !== null) wanted.push(['password', String(password)])
482
+ if (privateKeyPath !== undefined) wanted.push(['privateKeyPath', String(privateKeyPath)])
483
+ if (passphrase !== undefined) wanted.push(['passphrase', String(passphrase)])
484
+ if (workspace !== undefined) wanted.push(['workspace', String(workspace)])
485
+ if (useAgent !== undefined) wanted.push(['useAgent', !!useAgent])
486
+ if (keyboardInteractive !== undefined) wanted.push(['keyboardInteractive', !!keyboardInteractive])
487
+ if (proxy !== undefined) wanted.push(['proxy', proxy])
488
+ if (hostKeyMode !== undefined) wanted.push(['hostKeyMode', String(hostKeyMode)])
489
+ // Issue #51: kept in step with the native pool's setTarget — the two
490
+ // backends share one contract (see test/issue51-openssh-backend.test.js), so
491
+ // a field one of them diffs must not be silently ignored by the other.
492
+ if (backend !== undefined) wanted.push(['backend', String(backend)])
493
+ if (sshBinary !== undefined) wanted.push(['sshBinary', String(sshBinary)])
494
+ const differs = ([k, v]) => (k === 'proxy'
495
+ ? JSON.stringify(base[k] ?? null) !== JSON.stringify(v ?? null)
496
+ : base[k] !== v)
497
+ if (wanted.some(differs)) {
498
+ for (const [k, v] of wanted) this.config[k] = v
499
+ this.platform = 'unknown'
500
+ this.gitBashPath = ''
501
+ this.shellMode = 'native'
502
+ this._detecting = null
503
+ this.close()
504
+ }
505
+ return this
506
+ }
507
+
508
+ /**
509
+ * The secret to offer askpass, resolved once per target.
510
+ *
511
+ * `connect()` no longer has to run first: `exec`/`sftp` call this themselves,
512
+ * so a pool that is only ever used for file listing still authenticates.
513
+ */
514
+ _resolveSecret() {
515
+ if (this._secret !== null) return Promise.resolve(this._secret)
516
+ if (this._secretPromise) return this._secretPromise
517
+ const epoch = this.epoch
518
+ this._secretPromise = (async () => {
519
+ let secret = this.config.password || ''
520
+ if (!secret && this.passwordResolver) {
521
+ try { secret = (await this.passwordResolver()) || '' } catch { /* fall through */ }
522
+ }
523
+ if (!secret) secret = this.config.passphrase || ''
524
+ // A target switch invalidates the answer; leave the memo for the new one.
525
+ if (this.epoch === epoch) this._secret = String(secret || '')
526
+ this._secretPromise = null
527
+ return String(secret || '')
528
+ })()
529
+ return this._secretPromise
530
+ }
531
+
532
+ /** Validate the environment; there is no socket to hold open. */
533
+ connect() {
534
+ if (this.client) return Promise.resolve(this.client)
535
+ if (this.connecting) return this.connecting
536
+ const epoch = this.epoch
537
+ const pending = this._doConnect(epoch)
538
+ this.connecting = pending
539
+ const clear = () => { if (this.epoch === epoch && this.connecting === pending) this.connecting = null }
540
+ pending.then(clear, clear)
541
+ return pending
542
+ }
543
+
544
+ async _doConnect(epoch) {
545
+ const isCurrent = () => this.epoch === epoch
546
+ const sshBinary = resolveSshBinary(this.config)
547
+ if (!this.config.host) throw new Error('no host configured')
548
+ if (!sshBinaryAvailable(sshBinary)) {
549
+ throw new Error(
550
+ `the system-OpenSSH backend needs a \`${sshBinary}\` executable on PATH`
551
+ + ' — install OpenSSH, or set the backend back to "native"',
552
+ )
553
+ }
554
+ const secret = await this._resolveSecret()
555
+ if (!isCurrent()) throw new Error('ssh target changed during connect')
556
+ // Native semantics are "connect() throws when the SSH connection fails", and
557
+ // a probe also gives the settings page a real latency number. The CLI has no
558
+ // socket to keep, so this is the only point where the target is proven.
559
+ const probe = await this._runSsh(['--', this.destination(), 'true'], { timeoutMs: this.config.connectTimeoutMs || 15000 })
560
+ if (!isCurrent()) throw new Error('ssh target changed during connect')
561
+ if (probe.code !== 0) {
562
+ throw new Error(`ssh failed (exit ${probe.code})${String(probe.stderr || '').trim() ? ': ' + String(probe.stderr).trim() : ''}`)
563
+ }
564
+ void secret
565
+ const conn = new OpenSshConnection(this, { sshBinary, secret })
566
+ this.client = conn
567
+ if (this.onReady) { try { this.onReady(conn) } catch {} }
568
+ return conn
569
+ }
570
+
571
+ /**
572
+ * Run one `ssh` invocation and collect its result.
573
+ *
574
+ * @param {string[]} extraArgs - arguments appended after the shared base.
575
+ * @param {object} [opts] - `timeoutMs`, `signal` (AbortSignal), `stdin`,
576
+ * `onData(channel, chunk)` — a streaming tap the native backend has had
577
+ * since issue #70. A background job's value is its LIVE output, which the
578
+ * job ring must receive as it arrives; a backend that only returns the
579
+ * accumulated text loses every byte the caller stopped waiting for
580
+ * (issue #80). Tap errors are not command errors, so the call is guarded.
581
+ * @returns {Promise<{code: number|null, signal: string|null, stdout: string, stderr: string}>}
582
+ */
583
+ async _runSsh(extraArgs, opts = {}) {
584
+ if (!this.config.host) throw new Error('no host configured')
585
+ const secret = await this._resolveSecret()
586
+ const timeoutMs = opts.timeoutMs === 0 ? 0 : (opts.timeoutMs || this.config.commandTimeoutMs)
587
+ const sshBinary = resolveSshBinary(this.config)
588
+ const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), ...extraArgs]
589
+ return new Promise((resolve) => {
590
+ let child
591
+ try {
592
+ child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
593
+ } catch (err) {
594
+ return resolve({ code: -1, signal: 'SPAWN_FAILED', stdout: '', stderr: String((err && err.message) || err) })
595
+ }
596
+ // This path may stream a script into `bash -s` and can be written to
597
+ // after the command already exited (Git Bash); a broken pipe there must
598
+ // fail the call, not the process (issue #118).
599
+ guardChildStdin(child)
600
+ let stdout = ''
601
+ let stderr = ''
602
+ let settled = false
603
+ let exitCode = null
604
+ let exitSignal = null
605
+ const cap = Math.max(this.config.maxOutputChars * 4, 1024 * 1024)
606
+ const onData = typeof opts.onData === 'function' ? opts.onData : null
607
+ const cleanupAbort = () => { if (opts.signal && onAbort) opts.signal.removeEventListener('abort', onAbort) }
608
+ let onAbort = null
609
+ const finish = () => {
610
+ if (settled) return
611
+ settled = true
612
+ clearTimeout(timer)
613
+ cleanupAbort()
614
+ resolve({
615
+ code: exitCode,
616
+ signal: exitSignal,
617
+ stdout: truncate(stdout, this.config.maxOutputChars),
618
+ stderr: truncate(stderr, this.config.maxOutputChars),
619
+ })
620
+ }
621
+ const killHard = () => { try { setTimeout(() => { try { child.kill('SIGKILL') } catch {} }, 800).unref?.() } catch {} }
622
+ // No timer at all for an explicit no-deadline call (0) — see pool.js
623
+ // _execRaw; arming one would fire at once or kill a promoted job (issue #95).
624
+ const timer = timeoutMs > 0 ? setTimeout(() => {
625
+ if (settled) return
626
+ exitCode = -1
627
+ exitSignal = 'TIMEOUT'
628
+ try { child.kill() } catch {}
629
+ killHard()
630
+ finish()
631
+ }, timeoutMs) : null
632
+ if (opts.signal) {
633
+ if (opts.signal.aborted) {
634
+ try { child.kill() } catch {}
635
+ exitCode = -1; exitSignal = 'ABORTED'
636
+ return finish()
637
+ }
638
+ onAbort = () => {
639
+ if (settled) return
640
+ exitCode = -1; exitSignal = 'ABORTED'
641
+ try { child.kill() } catch {}
642
+ killHard()
643
+ finish()
644
+ }
645
+ opts.signal.addEventListener('abort', onAbort, { once: true })
646
+ }
647
+ // The tap fires even past the local cap, exactly like the native
648
+ // backend's: a promoted job's ring has its own bounds and must keep
649
+ // receiving output the truncated return value no longer holds.
650
+ child.stdout.on('data', (d) => {
651
+ if (stdout.length < cap) stdout += d
652
+ if (onData) { try { onData('stdout', d) } catch { /* tap errors are not command errors */ } }
653
+ })
654
+ child.stderr.on('data', (d) => {
655
+ if (stderr.length < cap) stderr += d
656
+ if (onData) { try { onData('stderr', d) } catch { /* tap errors are not command errors */ } }
657
+ })
658
+ child.on('error', (e) => {
659
+ if (settled) return
660
+ stderr += String((e && e.message) || e)
661
+ exitCode = -1
662
+ finish()
663
+ })
664
+ child.on('close', (code, sig) => {
665
+ if (settled) return
666
+ exitCode = code
667
+ exitSignal = sig || null
668
+ finish()
669
+ })
670
+ try { child.stdin.end(opts.stdin === undefined || opts.stdin === null ? undefined : String(opts.stdin)) } catch {}
671
+ })
672
+ }
673
+
674
+ /** Detect the remote platform + locate Git Bash once; cached per target. */
675
+ detect() {
676
+ if (this.platform !== 'unknown') return Promise.resolve()
677
+ if (this._detecting) return this._detecting
678
+ this._detecting = this._detect().finally(() => { this._detecting = null })
679
+ return this._detecting
680
+ }
681
+
682
+ async _detect() {
683
+ let res
684
+ try {
685
+ res = await this._runSsh(['--', this.destination(), 'cmd /c ver'], { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
686
+ } catch {
687
+ this.platform = 'unknown'
688
+ this.shellMode = 'native'
689
+ return
690
+ }
691
+ const out = String(res.stdout || '') + '\n' + String(res.stderr || '')
692
+ if (res.code === 0 && /microsoft windows/i.test(out)) {
693
+ this.platform = 'windows'
694
+ await this._resolveGitBash()
695
+ return
696
+ }
697
+ try {
698
+ const u = await this._runSsh(['--', this.destination(), 'uname -s'], { timeoutMs: Math.min(this.config.commandTimeoutMs, 8000) })
699
+ if (/mingw|msys|cygwin/i.test(String(u.stdout || ''))) {
700
+ this.platform = 'windows'
701
+ await this._resolveGitBash()
702
+ return
703
+ }
704
+ } catch { /* inconclusive — fall through to posix */ }
705
+ this.platform = 'posix'
706
+ this.shellMode = 'native'
707
+ this.gitBashPath = ''
708
+ }
709
+
710
+ async _resolveGitBash() {
711
+ const cfg = String(this.config.shell || '').trim()
712
+ const exists = async (p) => {
713
+ const r = await this._runSsh(['--', this.destination(), `cmd /c if exist "${p}" (echo Y) else (echo N)`], { timeoutMs: 8000 })
714
+ return /Y/.test(String(r.stdout || ''))
715
+ }
716
+ if (cfg && cfg !== 'git-bash' && cfg !== 'native') {
717
+ if (await exists(cfg)) { this.gitBashPath = cfg; this.shellMode = 'git-bash'; return }
718
+ }
719
+ if (cfg === 'native') { this.shellMode = 'native'; this.gitBashPath = ''; return }
720
+ try {
721
+ const r = await this._runSsh(['--', this.destination(), 'cmd /c where bash'], { timeoutMs: 8000 })
722
+ const first = String(r.stdout || '').trim().split(/\r?\n/)[0].trim()
723
+ if (first) { this.gitBashPath = first; this.shellMode = 'git-bash'; return }
724
+ } catch { /* fall through to the candidate list */ }
725
+ const candidates = [
726
+ 'C:\\Program Files\\Git\\bin\\bash.exe',
727
+ 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
728
+ ...(process.env.LOCALAPPDATA ? [process.env.LOCALAPPDATA + '\\Programs\\Git\\bin\\bash.exe'] : []),
729
+ ]
730
+ for (const c of candidates) {
731
+ if (await exists(c)) { this.gitBashPath = c; this.shellMode = 'git-bash'; return }
732
+ }
733
+ this.shellMode = 'git-bash'
734
+ this.gitBashPath = ''
735
+ }
736
+
737
+ /** Run one remote command (Windows + Git Bash is wrapped exactly as native). */
738
+ exec(command, timeoutMsOrOpts) {
739
+ const opts = timeoutMsOrOpts && typeof timeoutMsOrOpts === 'object' ? timeoutMsOrOpts : { timeoutMs: timeoutMsOrOpts }
740
+ return this.detect().then(() => {
741
+ const timeoutMs = opts.timeoutMs === 0 ? 0 : (opts.timeoutMs || this.config.commandTimeoutMs)
742
+ if (this.platform === 'windows' && this.gitBashPath) {
743
+ // Pipe the script to `bash -s` over stdin: no quoting round-trip, so
744
+ // quotes/backslashes/newlines survive verbatim (same as the native pool).
745
+ return this._runSsh(['--', this.destination(), `"${this.gitBashPath}" -s`], { timeoutMs, signal: opts.signal, stdin: String(command), onData: opts.onData })
746
+ }
747
+ return this._runSsh(['--', this.destination(), String(command)], { timeoutMs, signal: opts.signal, onData: opts.onData })
748
+ })
749
+ }
750
+
751
+ /** Open a fresh `ssh -s <dest> sftp` session and its ssh2 SFTP engine. */
752
+ async _openSftpChannel() {
753
+ const Sftp = loadSftpEngine()
754
+ const secret = await this._resolveSecret()
755
+ const sshBinary = resolveSshBinary(this.config)
756
+ const args = [...baseSshArgs(this._argConfig(), { forSecret: !!secret }), '-s', this.destination(), 'sftp']
757
+ const child = spawn(sshBinary, args, { stdio: ['pipe', 'pipe', 'pipe'], env: secret ? askpassEnv(secret) : undefined })
758
+
759
+ // ssh2's SFTP engine only reaches `_protocol` for channelData/channelClose,
760
+ // and reads `_remoteIdentRaw` to pick its packet sizes.
761
+ //
762
+ // ## Flow control, the subtle part
763
+ //
764
+ // Over real SSH the engine's send window is topped up by CHANNEL_WINDOW_ADJUST
765
+ // messages from the peer. On a raw `ssh -s sftp` pipe THERE ARE NO SUCH
766
+ // MESSAGES — the local ssh owns the SSH-layer window and the server's grants,
767
+ // and all we have is a byte pipe with OS-level backpressure. So the engine's
768
+ // window has to be mapped onto the pipe's writability:
769
+ //
770
+ // • a write the pipe accepts → more will fit;
771
+ // • the pipe fills (`stdin.write` returns false) → clamp the window so the
772
+ // engine buffers the remainder instead of queueing it all in memory;
773
+ // • the pipe drains → grant the window back and let the engine flush.
774
+ //
775
+ // The trap, and why the constants below are what they are: ssh2 arms its
776
+ // flush callback (`_waitWindow` / `_chunkcb = drainBuffer`) ONLY from inside
777
+ // its own subtraction, at the moment that subtraction takes the window to
778
+ // exactly 0. So the window must be handed over in EXACT MULTIPLES of
779
+ // packetSize and then left alone: the engine's own arithmetic then lands on 0
780
+ // during normal operation and arms the flush callback we depend on.
781
+ //
782
+ // Do NOT "help" by clamping the window to 0 from inside channelData when the
783
+ // pipe reports itself full. That sets the window to 0 AFTER the subtraction
784
+ // has already happened, so the callback is never armed and the buffered
785
+ // remainder is never flushed — the transfer deadlocks with a full window.
786
+ // (Measured: a 4 MB upload stopped dead after 32 KB, with `_buffer.length`
787
+ // stuck at 1 and no callback pending.) The pipe's own `drain` event is the
788
+ // only place the window is refilled.
789
+ //
790
+ // Also tempting-but-wrong: adding each received packet's length to the
791
+ // window. That happens to work for a DOWNLOAD (the peer's data is the
792
+ // window) and deadlocks an upload, because a write's acknowledgements are
793
+ // tiny status packets while each send consumes ~32 KB.
794
+ //
795
+ // See scripts/integration-openssh-large.mjs, which is what caught all of this.
796
+ const PACKET = 32768
797
+ const GRANT = PACKET * 8 // 256 KB per burst, and a multiple of packetSize
798
+ const chan = { sftp: null }
799
+ const fakeClient = {
800
+ _protocol: {
801
+ _remoteIdentRaw: Buffer.from('SSH-2.0-OpenSSH'),
802
+ // Hand the bytes to the pipe and nothing else. Backpressure is expressed
803
+ // through the engine's own window draining (see above); the OS pipe
804
+ // buffer plus Node's write buffer absorb the in-flight remainder.
805
+ channelData(_id, data) { try { child.stdin.write(data) } catch { /* close handles it */ } },
806
+ channelClose() { try { child.stdin.end() } catch {} },
807
+ },
808
+ }
809
+ const chanInfo = {
810
+ type: 'sftp',
811
+ incoming: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
812
+ outgoing: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
813
+ }
814
+ // The stdin pipe can die underneath the engine at any moment (the remote
815
+ // side of the sftp subsystem exits, the link drops — issue #118). Each write
816
+ // after that fails, and without an 'error' listener the failure is an
817
+ // uncaught exception that takes the whole Host down. Registering the guard
818
+ // here, next to the only two places that write to this pipe, keeps the
819
+ // blast radius at "this session is gone": 'close' fires as usual and the
820
+ // cached session is dropped by sftp()'s own handler.
821
+ guardChildStdin(child, () => { try { child.kill() } catch { /* already gone */ } })
822
+ const sftp = new Sftp(fakeClient, chanInfo, {})
823
+ chan.sftp = sftp
824
+
825
+ // The pipe has room again: grant the window back and let the engine flush
826
+ // whatever it buffered while the pipe was full.
827
+ const onStdinDrain = () => {
828
+ if (!chan.sftp) return
829
+ chan.sftp.outgoing.window = GRANT
830
+ if (chan.sftp._waitWindow) {
831
+ chan.sftp._waitWindow = false
832
+ const cb = chan.sftp._chunkcb
833
+ chan.sftp._chunkcb = undefined
834
+ if (typeof cb === 'function') cb.call(chan.sftp)
835
+ }
836
+ }
837
+ child.stdin.on('drain', onStdinDrain)
838
+ // A dead SSH process reports stdin EPIPE asynchronously. Without a stream
839
+ // error listener Node crashes the host before close/drop can reset the
840
+ // cached session (issue #118); kill it so that existing recovery runs.
841
+ child.stdin.on('error', () => { try { child.kill() } catch {} })
842
+
843
+ return new Promise((resolve, reject) => {
844
+ let stderr = ''
845
+ let settled = false
846
+ const done = (err) => {
847
+ if (settled) return
848
+ settled = true
849
+ clearTimeout(timer)
850
+ if (err) { try { child.kill() } catch {} ; reject(err) } else resolve({ child, sftp })
851
+ }
852
+ const timer = setTimeout(() => {
853
+ done(new Error(`sftp session to ${this.destination()} timed out${stderr ? ': ' + stderr.trim() : ''}`))
854
+ }, this.config.commandTimeoutMs)
855
+ child.stderr.on('data', (d) => { stderr += d })
856
+ sftp.on('error', (e) => done(new Error('sftp session failed: ' + ((e && e.message) || e))))
857
+ sftp.on('ready', () => done(null))
858
+ child.on('error', (e) => done(e))
859
+ child.on('close', (code) => done(new Error(`ssh sftp exited (${code})${stderr ? ': ' + stderr.trim() : ''}`)))
860
+ // Inbound is simpler: the local ssh already did the SSH-level window
861
+ // accounting before handing us these bytes, so they just go straight in.
862
+ child.stdout.on('data', (d) => { sftp.push(d) })
863
+ child.stdout.on('end', () => { try { sftp.push(null) } catch { /* already gone */ } })
864
+ sftp._init()
865
+ })
866
+ }
867
+
868
+ /**
869
+ * A persistent SFTP session, kept across calls: the picker and the explorer
870
+ * issue one listing per interaction, and re-handshaking each time would be
871
+ * visibly slow. A session that dies is dropped so the next call reconnects.
872
+ */
873
+ sftp() {
874
+ if (this._sftpSession) return this._sftpSession
875
+ const epoch = this.epoch
876
+ const session = this._openSftpChannel().then(({ child, sftp }) => {
877
+ const drop = () => {
878
+ if (this._sftpSession === session) this._sftpSession = null
879
+ if (this._sftpChild === child) this._sftpChild = null
880
+ }
881
+ child.on('close', drop)
882
+ sftp.on('end', drop)
883
+ sftp.on('error', drop)
884
+ // A target switch during the handshake must not adopt the old host's
885
+ // session (the same generational guard connect() uses).
886
+ if (this.epoch !== epoch) {
887
+ try { child.kill() } catch {}
888
+ throw new Error('ssh target changed while opening sftp')
889
+ }
890
+ this._sftpChild = child
891
+ return buildSftpSurface(sftp, {
892
+ commandTimeoutMs: this.config.commandTimeoutMs,
893
+ onTimeout: () => {
894
+ // A timed-out SFTP session is dead: kill the child and drop the cached
895
+ // session so the next call re-handshakes instead of queueing behind the
896
+ // wedged one (issue #65).
897
+ try { child.kill() } catch { /* already gone */ }
898
+ drop()
899
+ },
900
+ })
901
+ })
902
+ // Never cache a rejected open: the next call must retry rather than get the
903
+ // same error back forever (a failed handshake is usually transient).
904
+ session.catch(() => { if (this._sftpSession === session) this._sftpSession = null })
905
+ this._sftpSession = session
906
+ return session
907
+ }
908
+
909
+ invalidate() {
910
+ this.epoch++
911
+ const client = this.client
912
+ this.client = null
913
+ this.connecting = null
914
+ this._secret = null
915
+ this._secretPromise = null
916
+ if (client) { try { client.close() } catch {} }
917
+ this._dropSftpSession()
918
+ if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
919
+ if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
920
+ }
921
+
922
+ _dropSftpSession() {
923
+ const session = this._sftpSession
924
+ this._sftpSession = null
925
+ if (this._sftpChild) {
926
+ try { this._sftpChild.kill() } catch {}
927
+ this._sftpChild = null
928
+ }
929
+ // Swallow the rejection: nobody awaits a session we are tearing down.
930
+ if (session && typeof session.catch === 'function') session.catch(() => {})
931
+ }
932
+
933
+ close() {
934
+ this.epoch++
935
+ const client = this.client
936
+ this.client = null
937
+ this.connecting = null
938
+ this._secret = null
939
+ this._secretPromise = null
940
+ if (client) { try { client.close() } catch {} }
941
+ this._dropSftpSession()
942
+ if (this.proxyPool) { try { this.proxyPool.close() } catch {} ; this.proxyPool = null }
943
+ if (this.onCloseHook) { try { this.onCloseHook() } catch {} }
944
+ }
945
+ }
946
+
947
+ /** Pick the pool class for a config: 'openssh' backend, else the native pool. */
948
+ export function isSystemOpenSshBackend(config = {}) {
949
+ return String(config.backend || '').toLowerCase() === 'openssh'
950
+ }