dsh-remote 0.8.91 → 0.8.92

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 (139) hide show
  1. package/README.en.md +1 -0
  2. package/README.md +1 -0
  3. package/lib/client.js +161 -64
  4. package/lib/credential.js +7 -0
  5. package/lib/index.js +125 -31
  6. package/lib/openssh.js +60 -1
  7. package/lib/pool.js +127 -68
  8. package/lib/posix-shell.cjs +34 -0
  9. package/lib/remote-shell-child.cjs +8 -11
  10. package/lib/remote-skills.js +312 -0
  11. package/lib/routes-fs.js +6 -0
  12. package/lib/routes-misc.js +38 -1
  13. package/lib/web-attach.js +17 -7
  14. package/package.json +11 -8
  15. package/node_modules/buildcheck/.eslintrc.js +0 -5
  16. package/node_modules/buildcheck/.github/workflows/ci.yml +0 -88
  17. package/node_modules/buildcheck/.github/workflows/lint.yml +0 -27
  18. package/node_modules/buildcheck/.npmignore +0 -3
  19. package/node_modules/buildcheck/LICENSE +0 -19
  20. package/node_modules/buildcheck/README.md +0 -106
  21. package/node_modules/buildcheck/deps/Find-VisualStudio.cs +0 -250
  22. package/node_modules/buildcheck/lib/findvs.js +0 -361
  23. package/node_modules/buildcheck/lib/index.js +0 -738
  24. package/node_modules/buildcheck/package.json +0 -36
  25. package/node_modules/buildcheck/test/test.js +0 -8
  26. package/node_modules/cpu-features/.eslintrc.js +0 -5
  27. package/node_modules/cpu-features/.github/workflows/ci.yml +0 -74
  28. package/node_modules/cpu-features/.github/workflows/lint.yml +0 -27
  29. package/node_modules/cpu-features/LICENSE +0 -19
  30. package/node_modules/cpu-features/README.md +0 -59
  31. package/node_modules/cpu-features/binding.gyp +0 -16
  32. package/node_modules/cpu-features/buildcheck.js +0 -32
  33. package/node_modules/cpu-features/deps/cpu_features/.clang-format +0 -4
  34. package/node_modules/cpu-features/deps/cpu_features/.dockerignore +0 -31
  35. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile +0 -5
  36. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/aarch64_linux_cmake.yml +0 -30
  37. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_freebsd_cmake.yml +0 -22
  38. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_bazel.yml +0 -26
  39. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_cmake.yml +0 -31
  40. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_macos_cmake.yml +0 -43
  41. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_windows_cmake.yml +0 -25
  42. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/arm_linux_cmake.yml +0 -31
  43. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml +0 -24
  44. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/mips_linux_cmake.yml +0 -30
  45. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/power_linux_cmake.yml +0 -29
  46. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/riscv_linux_cmake.yml +0 -28
  47. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/s390x_linux_cmake.yml +0 -27
  48. package/node_modules/cpu-features/deps/cpu_features/.grenrc.yml +0 -21
  49. package/node_modules/cpu-features/deps/cpu_features/BUILD.bazel +0 -329
  50. package/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt +0 -261
  51. package/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md +0 -23
  52. package/node_modules/cpu-features/deps/cpu_features/LICENSE +0 -230
  53. package/node_modules/cpu-features/deps/cpu_features/README.md +0 -272
  54. package/node_modules/cpu-features/deps/cpu_features/WORKSPACE +0 -19
  55. package/node_modules/cpu-features/deps/cpu_features/bazel/ci/README.md +0 -5
  56. package/node_modules/cpu-features/deps/cpu_features/bazel/platforms.bzl +0 -11
  57. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in +0 -3
  58. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in +0 -3
  59. package/node_modules/cpu-features/deps/cpu_features/cmake/README.md +0 -30
  60. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/Makefile +0 -252
  61. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/README.md +0 -40
  62. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.dot +0 -64
  63. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.svg +0 -312
  64. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/generate_image.sh +0 -7
  65. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/amd64/Dockerfile +0 -48
  66. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/toolchain/Dockerfile +0 -34
  67. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/CMakeLists.txt +0 -22
  68. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/main.cpp +0 -11
  69. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/vagrant/freebsd/Vagrantfile +0 -107
  70. package/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in +0 -15
  71. package/node_modules/cpu-features/deps/cpu_features/cpu_features.gyp +0 -105
  72. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h +0 -54
  73. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h +0 -384
  74. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h +0 -259
  75. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h +0 -121
  76. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h +0 -74
  77. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h +0 -149
  78. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_riscv.h +0 -72
  79. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_s390x.h +0 -108
  80. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h +0 -288
  81. package/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h +0 -40
  82. package/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h +0 -37
  83. package/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h +0 -39
  84. package/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h +0 -240
  85. package/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h +0 -49
  86. package/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h +0 -110
  87. package/node_modules/cpu-features/deps/cpu_features/include/internal/windows_utils.h +0 -70
  88. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt +0 -60
  89. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md +0 -4
  90. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c +0 -205
  91. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h +0 -320
  92. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c +0 -12
  93. package/node_modules/cpu-features/deps/cpu_features/patches/0001-Add-Apple-Silicon-Support.patch +0 -456
  94. package/node_modules/cpu-features/deps/cpu_features/scripts/generate_badges.d +0 -165
  95. package/node_modules/cpu-features/deps/cpu_features/scripts/make_release.sh +0 -75
  96. package/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh +0 -490
  97. package/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh +0 -79
  98. package/node_modules/cpu-features/deps/cpu_features/src/copy.inl +0 -19
  99. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection.inl +0 -86
  100. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection_and_hwcaps.inl +0 -26
  101. package/node_modules/cpu-features/deps/cpu_features/src/equals.inl +0 -22
  102. package/node_modules/cpu-features/deps/cpu_features/src/filesystem.c +0 -62
  103. package/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c +0 -169
  104. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64__base_implementation.inl +0 -88
  105. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_linux_or_android.c +0 -79
  106. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_macos_or_iphone.c +0 -82
  107. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_windows.c +0 -138
  108. package/node_modules/cpu-features/deps/cpu_features/src/impl_arm_linux_or_android.c +0 -212
  109. package/node_modules/cpu-features/deps/cpu_features/src/impl_mips_linux_or_android.c +0 -93
  110. package/node_modules/cpu-features/deps/cpu_features/src/impl_ppc_linux.c +0 -163
  111. package/node_modules/cpu-features/deps/cpu_features/src/impl_riscv_linux.c +0 -111
  112. package/node_modules/cpu-features/deps/cpu_features/src/impl_s390x_linux.c +0 -120
  113. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86__base_implementation.inl +0 -2055
  114. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_freebsd.c +0 -68
  115. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_linux_or_android.c +0 -58
  116. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_macos.c +0 -57
  117. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_windows.c +0 -58
  118. package/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c +0 -132
  119. package/node_modules/cpu-features/deps/cpu_features/src/string_view.c +0 -192
  120. package/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c +0 -461
  121. package/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt +0 -114
  122. package/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc +0 -53
  123. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc +0 -396
  124. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc +0 -384
  125. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc +0 -176
  126. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc +0 -131
  127. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_riscv_test.cc +0 -180
  128. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_s390x_test.cc +0 -82
  129. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc +0 -1729
  130. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc +0 -103
  131. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h +0 -61
  132. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc +0 -52
  133. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h +0 -31
  134. package/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc +0 -132
  135. package/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc +0 -202
  136. package/node_modules/cpu-features/lib/index.js +0 -5
  137. package/node_modules/cpu-features/package.json +0 -40
  138. package/node_modules/cpu-features/src/binding.cc +0 -151
  139. package/node_modules/cpu-features/test/test.js +0 -12
package/lib/openssh.js CHANGED
@@ -164,6 +164,41 @@ export function askpassEnv(secret) {
164
164
  }
165
165
  }
166
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
+
167
202
  /** Is `ssh` runnable? Used to fail with an actionable message, not ENOENT. */
168
203
  export function sshBinaryAvailable(binary) {
169
204
  if (binary.includes('/') || binary.includes('\\')) {
@@ -257,6 +292,11 @@ export class OpenSshConnection extends EventEmitter {
257
292
  })
258
293
  this.children.add(child)
259
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)
260
300
  child.on('close', reap)
261
301
  child.on('error', reap)
262
302
  if (tty) { /* no pty support through the CLI without a tty helper */ }
@@ -377,7 +417,10 @@ export class OpenSshConnection extends EventEmitter {
377
417
  export class SystemOpenSshPool {
378
418
  constructor(config, opts = {}) {
379
419
  this.config = config
380
- this._knownHostsFile = opts.knownHostsFile
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
381
424
  this.client = null
382
425
  this.connecting = null
383
426
  this.proxyPool = null
@@ -540,6 +583,10 @@ export class SystemOpenSshPool {
540
583
  } catch (err) {
541
584
  return resolve({ code: -1, signal: 'SPAWN_FAILED', stdout: '', stderr: String((err && err.message) || err) })
542
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)
543
590
  let stdout = ''
544
591
  let stderr = ''
545
592
  let settled = false
@@ -754,6 +801,14 @@ export class SystemOpenSshPool {
754
801
  incoming: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
755
802
  outgoing: { id: 0, window: GRANT, packetSize: PACKET, state: 'open' },
756
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 */ } })
757
812
  const sftp = new Sftp(fakeClient, chanInfo, {})
758
813
  chan.sftp = sftp
759
814
 
@@ -770,6 +825,10 @@ export class SystemOpenSshPool {
770
825
  }
771
826
  }
772
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 {} })
773
832
 
774
833
  return new Promise((resolve, reject) => {
775
834
  let stderr = ''
package/lib/pool.js CHANGED
@@ -256,6 +256,11 @@ export class SshPool {
256
256
  this.onCloseHook = null
257
257
  /** Consecutive SFTP subchannel-open timeouts (issue #65). */
258
258
  this._sftpTimeouts = 0
259
+ /** One SFTP session per live client/epoch (issue #121). */
260
+ this._sftpSession = null
261
+ this._sftpRaw = null
262
+ this._sftpClient = null
263
+ this._sftpEpoch = -1
259
264
  }
260
265
 
261
266
  resolveKeyPath() {
@@ -420,7 +425,10 @@ export class SshPool {
420
425
  })
421
426
  client.on('error', (e) => rejectOnce(e))
422
427
  client.on('close', () => {
423
- if (isCurrent() && this.client === client) this.client = null
428
+ if (isCurrent() && this.client === client) {
429
+ this.client = null
430
+ this._dropSftpSession()
431
+ }
424
432
  rejectOnce(new Error('ssh connection closed'))
425
433
  })
426
434
 
@@ -820,86 +828,123 @@ export class SshPool {
820
828
  )
821
829
  }
822
830
 
823
- /** Resolve a promisified SFTP client. All paths normalized via toSftpPath(). */
824
- sftp() {
825
- return this.connect().then(
831
+ /**
832
+ * Resolve the shared promisified SFTP client for the CURRENT connection.
833
+ * Keeping one channel per client/epoch avoids leaking a channel per tool call
834
+ * into sshd's MaxSessions limit (issue #121).
835
+ */
836
+ sftp() { return this._sftp(false) }
837
+
838
+ _sftp(isRetry) {
839
+ const staleClient = this._sftpClient && this.client && this._sftpClient !== this.client
840
+ if (this._sftpSession && (this._sftpEpoch !== this.epoch || staleClient)) this._dropSftpSession()
841
+ if (this._sftpSession) return this._sftpSession
842
+
843
+ const epoch = this.epoch
844
+ const connected = isRetry
845
+ ? this.connect().catch((e) => { throw new Error('ssh sftp failed (reconnect): ' + ((e && e.message) || e)) })
846
+ : this.connect()
847
+ const session = connected.then(
826
848
  (client) =>
827
849
  new Promise((resolve, reject) => {
828
- let retried = false
829
- const runOn = (c) => {
830
- // Bound the subchannel open itself, per attempt. Without this, a
831
- // remote whose sftp subsystem is unresponsive (overloaded sshd,
832
- // exceeded MaxSessions, half-open TCP) leaves `c.sftp(cb)` parked
833
- // forever with no callback — issue #44 point 3. ssh2 only calls back
834
- // on success or on a channel error, and a wedged peer produces
835
- // neither.
836
- //
837
- // The timer must be created per attempt, not once outside: the
838
- // callback clears it, so a single outer timer would leave the retry
839
- // (below) with no timeout at all.
840
- let timedOut = false
841
- const attemptTimer = setTimeout(() => {
842
- timedOut = true
843
- reject(new Error(`ssh sftp open timed out after ${this.config.commandTimeoutMs}ms`))
844
- }, this.config.commandTimeoutMs)
845
- // ★ 这里**不能 unref**。
846
- //
847
- // 这个定时器是"本次 await 的 sftp 打开"的**唯一结算者**:要么它超时 reject,
848
- // 要么 ssh2 回调 resolve。若把它 unref,而进程此刻没有别的 pending 句柄,
849
- // Node 会认为无事可做而**直接退出**,调用方永远等不到结果。
850
- // 实测症状:CI 上该用例之后的 4 个用例被标记 `cancelledByParent`
851
- // (同文件子进程提前退出),而本地因运行器恰好持着句柄而侥幸通过。
852
- // 注意与上面 exec() 的超时定时器保持一致 —— 那个本来就没有 unref。
853
- // 下面的 hardClose 仍然 unref,因为它只做清理、不负责结算。
854
- const clearAttempt = () => { clearTimeout(attemptTimer) }
855
- try {
856
- c.sftp((err, sftp) => {
857
- clearAttempt()
858
- if (timedOut) return
859
- if (err) {
860
- // Same dead-connection recovery as exec(): a channel open
861
- // failure — or a session termination (remote closed the
862
- // SFTP subchannel, e.g. transient network blip / sshd idle
863
- // drop) — means the pooled connection is stale: drop it and
864
- // retry ONCE on a fresh connection.
865
- if (!retried && /channel open failure|open failed|unexpected sftp session termination|session termination|disconnect/i.test(String((err && err.message) || err))) {
866
- retried = true
867
- this.invalidate()
868
- return this.connect().then(
869
- (fresh) => runOn(fresh),
870
- (e2) => reject(new Error('ssh sftp failed (reconnect): ' + ((e2 && e2.message) || e2))),
871
- )
872
- }
873
- return reject(new Error('ssh sftp failed: ' + ((err && err.message) || err)))
850
+ // Bound the subchannel open itself, per attempt. Without this, a
851
+ // remote whose sftp subsystem is unresponsive (overloaded sshd,
852
+ // exceeded MaxSessions, half-open TCP) leaves `client.sftp(cb)` parked
853
+ // forever with no callback — issue #44 point 3.
854
+ let timedOut = false
855
+ const attemptTimer = setTimeout(() => {
856
+ timedOut = true
857
+ reject(new Error(`ssh sftp open timed out after ${this.config.commandTimeoutMs}ms`))
858
+ }, this.config.commandTimeoutMs)
859
+ // ★ 这里**不能 unref**。
860
+ //
861
+ // 这个定时器是"本次 await 的 sftp 打开"的**唯一结算者**:要么它超时 reject,
862
+ // 要么 ssh2 回调 resolve。若把它 unref,而进程此刻没有别的 pending 句柄,
863
+ // Node 会认为无事可做而**直接退出**,调用方永远等不到结果。
864
+ // 实测症状:CI 上该用例之后的 4 个用例被标记 `cancelledByParent`
865
+ // (同文件子进程提前退出),而本地因运行器恰好持着句柄而侥幸通过。
866
+ // 注意与上面 exec() 的超时定时器保持一致 —— 那个本来就没有 unref。
867
+ const clearAttempt = () => { clearTimeout(attemptTimer) }
868
+ try {
869
+ client.sftp((err, sftp) => {
870
+ clearAttempt()
871
+ // A late success after the watchdog rejected still owns a real
872
+ // channel. Close it, and never adopt it into the cache.
873
+ if (timedOut) {
874
+ if (!err && sftp) { try { sftp.end() } catch { /* already gone */ } }
875
+ return
876
+ }
877
+ const wrongClient = this.client && this.client !== client
878
+ if (this.epoch !== epoch || this._sftpSession !== session || wrongClient) {
879
+ if (!err && sftp) { try { sftp.end() } catch { /* already gone */ } }
880
+ return reject(new Error('ssh target changed while opening sftp'))
881
+ }
882
+ if (err) {
883
+ // Same dead-connection recovery as before: retry ONCE on a fresh
884
+ // connection. The new session has its own epoch and is adopted by
885
+ // callers of this promise; isRetry prevents recursive reconnects.
886
+ if (!isRetry && /channel open failure|open failed|unexpected sftp session termination|session termination|disconnect/i.test(String((err && err.message) || err))) {
887
+ this.invalidate()
888
+ return resolve(this._sftp(true))
874
889
  }
875
- // A successful open proves the connection healthy: the strike
876
- // counter counts CONSECUTIVE timeouts, so it resets here —
877
- // two unrelated transient blips hours apart must not tear down
878
- // a fine connection.
879
- this._sftpTimeouts = 0
880
- // The promisified surface (timeouts, dead-channel fail-fast,
881
- // range reads) is shared verbatim with the system-OpenSSH
882
- // backend — see lib/sftp-surface.js for the rules it encodes.
890
+ return reject(new Error('ssh sftp failed: ' + ((err && err.message) || err)))
891
+ }
892
+
893
+ const drop = () => {
894
+ if (this._sftpSession === session) {
895
+ this._sftpSession = null
896
+ this._sftpEpoch = -1
897
+ }
898
+ if (this._sftpRaw === sftp) {
899
+ this._sftpRaw = null
900
+ this._sftpClient = null
901
+ }
902
+ }
903
+ if (typeof sftp.on === 'function') {
904
+ sftp.on('end', drop)
905
+ sftp.on('close', drop)
906
+ sftp.on('error', drop)
907
+ }
908
+ this._sftpRaw = sftp
909
+ this._sftpClient = client
910
+ // A successful open proves the connection healthy: reset the
911
+ // consecutive-timeout strike counter (issue #65).
912
+ this._sftpTimeouts = 0
913
+ try {
883
914
  resolve(buildSftpSurface(sftp, {
884
915
  commandTimeoutMs: this.config.commandTimeoutMs,
885
916
  onTimeout: () => {
886
- // A timed-out SFTP subchannel is dead: close it so the next
887
- // operation does not queue behind the wedged one, and count
888
- // the strike so a second consecutive timeout tears down the
889
- // whole pooled connection (issue #65).
917
+ // A timed-out channel is dead: close AND forget it so the
918
+ // next call reopens instead of returning a dead surface.
890
919
  try { sftp.end() } catch { /* already gone */ }
920
+ drop()
891
921
  this._noteSftpTimeout()
892
922
  },
893
923
  }))
894
- })
895
- } catch (e) {
896
- clearAttempt()
897
- reject(new Error('ssh sftp failed: ' + ((e && e.message) || e)))
898
- }
924
+ } catch (e) {
925
+ drop()
926
+ try { sftp.end() } catch { /* already gone */ }
927
+ reject(new Error('ssh sftp failed: ' + ((e && e.message) || e)))
928
+ }
929
+ })
930
+ } catch (e) {
931
+ clearAttempt()
932
+ reject(new Error('ssh sftp failed: ' + ((e && e.message) || e)))
899
933
  }
900
- runOn(client)
901
934
  }),
902
935
  )
936
+ // Never cache a rejected open: the next call must retry rather than get the
937
+ // same error back forever. Raw fields are only set after a successful open.
938
+ session.catch(() => {
939
+ if (this._sftpSession === session) {
940
+ this._sftpSession = null
941
+ this._sftpEpoch = -1
942
+ this._sftpClient = null
943
+ }
944
+ })
945
+ this._sftpSession = session
946
+ this._sftpEpoch = epoch
947
+ return session
903
948
  }
904
949
 
905
950
  /**
@@ -912,6 +957,18 @@ export class SshPool {
912
957
  if (this._sftpTimeouts >= 2) this.invalidate()
913
958
  }
914
959
 
960
+ _dropSftpSession() {
961
+ const session = this._sftpSession
962
+ const raw = this._sftpRaw
963
+ this._sftpSession = null
964
+ this._sftpRaw = null
965
+ this._sftpClient = null
966
+ this._sftpEpoch = -1
967
+ if (raw) { try { raw.end() } catch { /* already gone */ } }
968
+ // Swallow the rejection: nobody awaits a session we are tearing down.
969
+ if (session && typeof session.catch === 'function') session.catch(() => {})
970
+ }
971
+
915
972
  /**
916
973
  * Drop the cached client and force a fresh connection on the next call.
917
974
  * Called when a channel open fails (e.g. "Channel open failure: open
@@ -924,6 +981,7 @@ export class SshPool {
924
981
  this.epoch++
925
982
  const client = this.client
926
983
  this.client = null
984
+ this._dropSftpSession()
927
985
  const pending = this.connecting
928
986
  this.connecting = null
929
987
  if (pending && typeof pending.catch === 'function') {
@@ -949,6 +1007,7 @@ export class SshPool {
949
1007
  this.epoch++
950
1008
  const client = this.client
951
1009
  this.client = null
1010
+ this._dropSftpSession()
952
1011
  const pending = this.connecting
953
1012
  this.connecting = null
954
1013
  if (pending && typeof pending.catch === 'function') {
@@ -0,0 +1,34 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * Quote one string for a POSIX shell using single quotes only.
5
+ *
6
+ * A single quote inside the value is emitted as the three-step sequence
7
+ * close-quote, escaped-quote, reopen-quote. The result preserves the value
8
+ * literally, including newlines, dollar signs, backticks and double quotes.
9
+ *
10
+ * @param {unknown} value
11
+ * @returns {string}
12
+ */
13
+ function quotePosix(value) {
14
+ return "'" + String(value).replace(/'/g, "'\\''") + "'"
15
+ }
16
+
17
+ /**
18
+ * Run a generated POSIX script through `sh` instead of the remote login shell.
19
+ *
20
+ * sshd gives an exec request to the user's login shell. That shell may be fish,
21
+ * csh or another non-POSIX implementation, while this package's internal launch
22
+ * and probe scripts are deliberately POSIX. The outer shell only has to parse
23
+ * the simple `sh -c '<quoted script>'` invocation; `sh` then parses the actual
24
+ * script. Generic rw_exec commands are NOT routed through this helper, so users
25
+ * retain their login-shell semantics.
26
+ *
27
+ * @param {string} command
28
+ * @returns {string}
29
+ */
30
+ function posixViaSh(command) {
31
+ return `sh -c ${quotePosix(command)}`
32
+ }
33
+
34
+ module.exports = { posixViaSh, quotePosix }
@@ -17,6 +17,7 @@
17
17
  const { spawn } = require('node:child_process')
18
18
  const { existsSync, fstatSync, readFileSync } = require('node:fs')
19
19
  const path = require('node:path')
20
+ const { posixViaSh, quotePosix } = require('./posix-shell.cjs')
20
21
 
21
22
  /** Name of the marker the host half writes into every local mirror root. */
22
23
  const META_FILE = '.dsh-remote-meta.json'
@@ -84,15 +85,8 @@ function matchMachine(meta, registry) {
84
85
  && Number(m.port || 22) === port)
85
86
  }
86
87
 
87
- /**
88
- * Quote one path for a POSIX shell, single quotes only.
89
- * @param {string} value
90
- * @returns {string}
91
- */
92
- function quotePosix(value) {
93
- return "'" + String(value).replace(/'/g, "'\\''") + "'"
94
- }
95
-
88
+ // Paths and the outer sh -c boundary share the same POSIX quoting rules.
89
+ // WebAttach uses this same helper so both generated command paths quote identically.
96
90
  /**
97
91
  * Build the `cd` half of the remote command, keeping `~` for the *remote* shell
98
92
  * to expand: the local home is not the remote home, so expanding it here would
@@ -113,13 +107,16 @@ function remoteCd(remotePath) {
113
107
  *
114
108
  * `exec` keeps the pty attached to a single interactive shell, so the exit code
115
109
  * the terminal sees is the shell's own, and a deleted workspace falls back to
116
- * `$HOME` instead of leaving a broken terminal.
110
+ * `$HOME` instead of leaving a broken terminal. The POSIX script goes through
111
+ * `sh -c` because sshd otherwise hands it to a possibly non-POSIX login shell
112
+ * (fish/csh); the final interactive shell is still the user's own `$SHELL`.
117
113
  *
118
114
  * @param {string} remotePath
119
115
  * @returns {string}
120
116
  */
121
117
  function remoteCommand(remotePath) {
122
- return `${remoteCd(remotePath)} 2>/dev/null || cd "$HOME"; exec "\${SHELL:-/bin/bash}" -l`
118
+ const script = `${remoteCd(remotePath)} 2>/dev/null || cd "$HOME"; exec "\${SHELL:-/bin/bash}" -l`
119
+ return posixViaSh(script)
123
120
  }
124
121
 
125
122
  /** Absolute Windows path: `D:\x`, `D:/x`, or a `\\server\share` UNC path.