dsh-remote 0.8.94 → 1.0.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 (186) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +408 -370
  3. package/README.md +391 -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 +172 -172
  8. package/lib/boot.js +42 -42
  9. package/lib/client.js +5615 -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-reference.js +457 -457
  14. package/lib/forwards.js +258 -258
  15. package/lib/host-api.js +822 -822
  16. package/lib/hostkey.js +108 -108
  17. package/lib/http-transport.js +201 -201
  18. package/lib/ignore.js +202 -202
  19. package/lib/index.js +4564 -4488
  20. package/lib/instructions-dynamic.js +415 -415
  21. package/lib/instructions.js +288 -288
  22. package/lib/open-folder.js +56 -56
  23. package/lib/openssh.js +950 -940
  24. package/lib/paths.js +292 -292
  25. package/lib/pool.js +1029 -1029
  26. package/lib/posix-shell.cjs +34 -34
  27. package/lib/registry.js +296 -296
  28. package/lib/remote-fs.js +173 -173
  29. package/lib/remote-sandbox.js +183 -183
  30. package/lib/remote-shell-child.cjs +413 -397
  31. package/lib/remote-shell.js +697 -697
  32. package/lib/remote-skills.js +312 -312
  33. package/lib/routes-audit.js +58 -58
  34. package/lib/routes-forwards.js +72 -72
  35. package/lib/routes-fs.js +251 -251
  36. package/lib/routes-machines.js +217 -186
  37. package/lib/routes-misc.js +187 -187
  38. package/lib/routes-term.js +169 -169
  39. package/lib/routes-update.js +147 -143
  40. package/lib/routes-web-attach.js +121 -112
  41. package/lib/routes-workspace.js +325 -312
  42. package/lib/search.js +235 -235
  43. package/lib/self-heal.js +130 -130
  44. package/lib/sftp-surface.js +119 -119
  45. package/lib/sshconfig.js +779 -779
  46. package/lib/sync-status.js +31 -0
  47. package/lib/sync.js +350 -350
  48. package/lib/tasks.js +95 -95
  49. package/lib/telemetry.js +247 -247
  50. package/lib/terminal.js +205 -205
  51. package/lib/tui/flow.js +130 -130
  52. package/lib/tui/format.js +380 -380
  53. package/lib/tui/i18n.js +350 -350
  54. package/lib/tui/index.js +531 -531
  55. package/lib/tui/provider.js +344 -344
  56. package/lib/tui/scene.js +986 -986
  57. package/lib/update.js +497 -490
  58. package/lib/web-attach.js +1081 -860
  59. package/lib/workspace-cleanup.js +337 -337
  60. package/node_modules/buildcheck/.eslintrc.js +5 -0
  61. package/node_modules/buildcheck/.github/workflows/ci.yml +88 -0
  62. package/node_modules/buildcheck/.github/workflows/lint.yml +27 -0
  63. package/node_modules/buildcheck/.npmignore +3 -0
  64. package/node_modules/buildcheck/LICENSE +19 -0
  65. package/node_modules/buildcheck/README.md +106 -0
  66. package/node_modules/buildcheck/deps/Find-VisualStudio.cs +250 -0
  67. package/node_modules/buildcheck/lib/findvs.js +361 -0
  68. package/node_modules/buildcheck/lib/index.js +738 -0
  69. package/node_modules/buildcheck/package.json +36 -0
  70. package/node_modules/buildcheck/test/test.js +8 -0
  71. package/node_modules/cpu-features/.eslintrc.js +5 -0
  72. package/node_modules/cpu-features/.github/workflows/ci.yml +74 -0
  73. package/node_modules/cpu-features/.github/workflows/lint.yml +27 -0
  74. package/node_modules/cpu-features/LICENSE +19 -0
  75. package/node_modules/cpu-features/README.md +59 -0
  76. package/node_modules/cpu-features/binding.gyp +16 -0
  77. package/node_modules/cpu-features/buildcheck.js +32 -0
  78. package/node_modules/cpu-features/deps/cpu_features/.clang-format +4 -0
  79. package/node_modules/cpu-features/deps/cpu_features/.dockerignore +31 -0
  80. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile +5 -0
  81. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/aarch64_linux_cmake.yml +30 -0
  82. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_freebsd_cmake.yml +22 -0
  83. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_bazel.yml +26 -0
  84. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_cmake.yml +31 -0
  85. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_macos_cmake.yml +43 -0
  86. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_windows_cmake.yml +25 -0
  87. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/arm_linux_cmake.yml +31 -0
  88. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml +24 -0
  89. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/mips_linux_cmake.yml +30 -0
  90. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/power_linux_cmake.yml +29 -0
  91. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/riscv_linux_cmake.yml +28 -0
  92. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/s390x_linux_cmake.yml +27 -0
  93. package/node_modules/cpu-features/deps/cpu_features/.grenrc.yml +21 -0
  94. package/node_modules/cpu-features/deps/cpu_features/BUILD.bazel +329 -0
  95. package/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt +261 -0
  96. package/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md +23 -0
  97. package/node_modules/cpu-features/deps/cpu_features/LICENSE +230 -0
  98. package/node_modules/cpu-features/deps/cpu_features/README.md +272 -0
  99. package/node_modules/cpu-features/deps/cpu_features/WORKSPACE +19 -0
  100. package/node_modules/cpu-features/deps/cpu_features/bazel/ci/README.md +5 -0
  101. package/node_modules/cpu-features/deps/cpu_features/bazel/platforms.bzl +11 -0
  102. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in +3 -0
  103. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in +3 -0
  104. package/node_modules/cpu-features/deps/cpu_features/cmake/README.md +30 -0
  105. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/Makefile +252 -0
  106. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/README.md +40 -0
  107. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.dot +64 -0
  108. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.svg +312 -0
  109. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/generate_image.sh +7 -0
  110. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/amd64/Dockerfile +48 -0
  111. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/toolchain/Dockerfile +34 -0
  112. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/CMakeLists.txt +22 -0
  113. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/main.cpp +11 -0
  114. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/vagrant/freebsd/Vagrantfile +107 -0
  115. package/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in +15 -0
  116. package/node_modules/cpu-features/deps/cpu_features/cpu_features.gyp +105 -0
  117. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h +54 -0
  118. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h +384 -0
  119. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h +259 -0
  120. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h +121 -0
  121. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h +74 -0
  122. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h +149 -0
  123. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_riscv.h +72 -0
  124. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_s390x.h +108 -0
  125. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h +288 -0
  126. package/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h +40 -0
  127. package/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h +37 -0
  128. package/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h +39 -0
  129. package/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h +240 -0
  130. package/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h +49 -0
  131. package/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h +110 -0
  132. package/node_modules/cpu-features/deps/cpu_features/include/internal/windows_utils.h +70 -0
  133. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt +60 -0
  134. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md +4 -0
  135. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c +205 -0
  136. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h +320 -0
  137. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c +12 -0
  138. package/node_modules/cpu-features/deps/cpu_features/patches/0001-Add-Apple-Silicon-Support.patch +456 -0
  139. package/node_modules/cpu-features/deps/cpu_features/scripts/generate_badges.d +165 -0
  140. package/node_modules/cpu-features/deps/cpu_features/scripts/make_release.sh +75 -0
  141. package/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh +490 -0
  142. package/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh +79 -0
  143. package/node_modules/cpu-features/deps/cpu_features/src/copy.inl +19 -0
  144. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection.inl +86 -0
  145. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection_and_hwcaps.inl +26 -0
  146. package/node_modules/cpu-features/deps/cpu_features/src/equals.inl +22 -0
  147. package/node_modules/cpu-features/deps/cpu_features/src/filesystem.c +62 -0
  148. package/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c +169 -0
  149. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64__base_implementation.inl +88 -0
  150. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_linux_or_android.c +79 -0
  151. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_macos_or_iphone.c +82 -0
  152. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_windows.c +138 -0
  153. package/node_modules/cpu-features/deps/cpu_features/src/impl_arm_linux_or_android.c +212 -0
  154. package/node_modules/cpu-features/deps/cpu_features/src/impl_mips_linux_or_android.c +93 -0
  155. package/node_modules/cpu-features/deps/cpu_features/src/impl_ppc_linux.c +163 -0
  156. package/node_modules/cpu-features/deps/cpu_features/src/impl_riscv_linux.c +111 -0
  157. package/node_modules/cpu-features/deps/cpu_features/src/impl_s390x_linux.c +120 -0
  158. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86__base_implementation.inl +2055 -0
  159. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_freebsd.c +68 -0
  160. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_linux_or_android.c +58 -0
  161. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_macos.c +57 -0
  162. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_windows.c +58 -0
  163. package/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c +132 -0
  164. package/node_modules/cpu-features/deps/cpu_features/src/string_view.c +192 -0
  165. package/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c +461 -0
  166. package/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt +114 -0
  167. package/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc +53 -0
  168. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc +396 -0
  169. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc +384 -0
  170. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc +176 -0
  171. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc +131 -0
  172. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_riscv_test.cc +180 -0
  173. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_s390x_test.cc +82 -0
  174. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc +1729 -0
  175. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc +103 -0
  176. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h +61 -0
  177. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc +52 -0
  178. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h +31 -0
  179. package/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc +132 -0
  180. package/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc +202 -0
  181. package/node_modules/cpu-features/lib/index.js +5 -0
  182. package/node_modules/cpu-features/package.json +40 -0
  183. package/node_modules/cpu-features/src/binding.cc +151 -0
  184. package/node_modules/cpu-features/test/test.js +12 -0
  185. package/node_modules/nan/tools/1to2.js +0 -0
  186. package/package.json +106 -103
package/lib/web-attach.js CHANGED
@@ -1,860 +1,1081 @@
1
- // dsh-remote — "remote DSH web UI" attach sessions (issue #46).
2
- //
3
- // The user's intent behind that issue is "use the local DSH as a CLIENT for a
4
- // DSH running on another machine": they do NOT want the remote to expose an
5
- // inbound listener. DSH makes that impossible anyway — `dsh-web-app` hard-
6
- // rejects `--host 0.0.0.0` (startup.js) because it would put remote code
7
- // execution on the network, and `dsh-host-webserver` only accepts the
8
- // 127.0.0.1/0.0.0.0 literals.
9
- //
10
- // So this module inverts the direction, exactly like the rest of the plugin:
11
- // we SSH OUT, start (or reuse) a loopback-bound `dsh web` on the remote, and
12
- // carry its socket back over our own SSH connection with a local TCP forward.
13
- // The browser then talks to 127.0.0.1:<localPort> on this machine.
14
- //
15
- // Verified end-to-end on a real Linux host (dsh 0.1.5-rc.2): a bare TCP forward
16
- // is sufficient — the SPA, its assets, AND the `/api/remote.mux` WebSocket
17
- // upgrade all transit it (HTTP/1.1 101), with no reverse proxy and no host
18
- // rewriting. That works because DSH binds its auth cookie to the request
19
- // authority, so a cookie minted against `127.0.0.1:<localPort>` is exactly what
20
- // the browser then sends back to that same authority.
21
- //
22
- // Three details drive the design and are worth stating once:
23
- //
24
- // 1. The launch token CANNOT be read from anywhere but stdout. It is a
25
- // `randomBytes` value held in a process-local WeakMap and printed on one
26
- // line (`dsh web: http://127.0.0.1:<port>/?token=…`). No file, no env var.
27
- // Therefore the token is captured by redirecting the remote process's
28
- // output to a log file and parsing that line out of it.
29
- // 2. `--port 0` lets the remote OS pick a free port, and the same printed line
30
- // reports which port it chose — so we never have to guess or probe for a
31
- // free port on the remote.
32
- // 3. The pairing that must survive is (token, port) from ONE launch. Reading
33
- // them from one line is what keeps them consistent.
34
- //
35
- // Everything here is read-only with respect to the remote filesystem except
36
- // the log file it creates under the remote `$HOME`.
37
- import net from 'node:net'
38
- import posixShell from './posix-shell.cjs'
39
-
40
- const { posixViaSh } = posixShell
41
-
42
- /** Execute an INTERNAL POSIX script without depending on the login shell. */
43
- function execPosix(exec, command, opts) {
44
- return exec(posixViaSh(command), opts)
45
- }
46
-
47
- /** Remote log file per attach session; `$HOME` is expanded by the remote shell. */
48
- const LOG_NAME = '.dsh-remote-web'
49
-
50
- /**
51
- * Parse the `dsh web:` startup line out of a remote log.
52
- *
53
- * The line looks like:
54
- * dsh web: http://127.0.0.1:43129/?token=Iy7FKuPSI5qJKJUFDyah4B6i8Ul6_hvspiJhiWufYt8
55
- * and may be followed by a LAN suffix when the remote bound 0.0.0.0 (it never
56
- * will here — we never pass `--host` — but tolerate it rather than break).
57
- *
58
- * @param {string} text - the remote log contents.
59
- * @returns {{url: string, port: number, token: string}|null} parsed facts, or
60
- * null when the line has not appeared yet (still booting) or is malformed.
61
- */
62
- export function parseWebStart(text) {
63
- if (typeof text !== 'string' || text === '') return null
64
- // Take the LAST match: a reused log file may hold an earlier session's line,
65
- // and the newest one is the one this launch produced.
66
- const matches = [...text.matchAll(/dsh web:\s*(http:\/\/[^\s]+)/g)]
67
- if (matches.length === 0) return null
68
- const url = matches[matches.length - 1][1]
69
- let parsed
70
- try {
71
- parsed = new URL(url)
72
- } catch {
73
- return null
74
- }
75
- const port = Number(parsed.port)
76
- const token = parsed.searchParams.get('token') || ''
77
- if (!Number.isInteger(port) || port < 1 || port > 65535) return null
78
- if (!token) return null
79
- return { url, port, token }
80
- }
81
-
82
- /** True when the log proves the remote process died instead of booting. */
83
- export function launchFailed(text) {
84
- return typeof text === 'string' && text.includes(DEAD_MARKER)
85
- }
86
-
87
- /** Marker the remote launcher echoes when the process exits before printing. */
88
- const DEAD_MARKER = '__DSH_REMOTE_DIED__'
89
- /** Marker separating the parsed line from the raw log tail for diagnostics. */
90
- export const TAIL_MARKER = '__DSH_TAIL__'
91
- /** Marker carrying the remote PID so the session can stop its own process. */
92
- export const PID_MARKER = '__DSH_PID__='
93
- /** Random ASCII tag so two attach sessions never share a remote log file. */
94
- function randomTag() {
95
- return Math.random().toString(36).slice(2, 8) + Date.now().toString(36).slice(-4)
96
- }
97
-
98
- /**
99
- * Build the one-shot remote command that launches `dsh web` detached and waits
100
- * for its startup line.
101
- *
102
- * `setsid` + `nohup` + redirected stdio are all required: the SSH channel closes
103
- * as soon as this shell exits, and without detaching the SIGHUP would kill the
104
- * server we just started. The loop is bounded so a wedged remote cannot hang the
105
- * call past the caller's own timeout, and it reports either the parsed line or
106
- * the log tail — never silence.
107
- *
108
- * @param {object} spec - launch parameters.
109
- * @param {boolean} [spec.omitNoOpen] - drop `--no-open`. Older DSH (measured on
110
- * 0.1.0-rc.6) has no such flag and exits with "unknown option '--no-open'";
111
- * the caller retries with this set rather than assuming a flag exists.
112
- * @returns {string} a POSIX shell command line (no newlines, ASCII only).
113
- */
114
- export function buildLaunchCommand({ command, profile, logPath, remotePort = 0, dshHome = '', waitSeconds = 45, omitNoOpen = false }) {
115
- const env = dshHome ? `DSH_HOME="${dshHome}" ` : ''
116
- const noOpen = omitNoOpen ? '' : ' --no-open'
117
- const args = `--profile ${profile} --port ${Number(remotePort) || 0}${noOpen}`
118
- const limit = Number(waitSeconds) || 45
119
- // The loop is ONE shell element: `do` is a keyword and `do;` is a syntax error
120
- // in POSIX sh, so it must be glued to the first command of the body rather
121
- // than separated like the other statements.
122
- const loop = `while [ $i -lt ${limit} ]; do grep -q 'token=' "$LOG" 2>/dev/null && break`
123
- + `; kill -0 $P 2>/dev/null || { echo ${DEAD_MARKER}; break; }`
124
- + `; sleep 1; i=$((i+1)); done`
125
- return [
126
- `LOG="$HOME/${logPath}"`,
127
- `: > "$LOG"`,
128
- // `command -v setsid` guards hosts without util-linux (macOS); plain nohup
129
- // still detaches from the channel's HUP there.
130
- `command -v setsid >/dev/null 2>&1 && SET=setsid || SET=`,
131
- `${env}$SET nohup ${command} ${args} >"$LOG" 2>&1 </dev/null & P=$!`,
132
- `i=0`,
133
- loop,
134
- `echo "${PID_MARKER}$P"`,
135
- `grep -m1 'dsh web:' "$LOG" 2>/dev/null`,
136
- `echo ${TAIL_MARKER}`,
137
- `tail -20 "$LOG" 2>/dev/null`,
138
- ].join('; ')
139
- }
140
-
141
- /** Extract the remote PID from launcher output (0 when absent). */
142
- export function parseRemotePid(output) {
143
- const m = /__DSH_PID__=(\d+)/.exec(String(output || ''))
144
- return m ? Number(m[1]) : 0
145
- }
146
-
147
- /**
148
- * Recognize a known remote-side reason the web surface could not start, and
149
- * return an actionable sentence for it.
150
- *
151
- * The point is to keep an operator from reading "the remote DSH did not report a
152
- * startup token" and concluding the *plugin* is broken. Measured cause: dsh
153
- * ≤ 0.1.0-rc.6 depends on `node-pty@1.1.0`, whose published tarball ships
154
- * darwin/win32 prebuilds but **no `linux-x64`**, so `dsh web` cannot boot on
155
- * Linux at all — it dies loading the native module. 0.1.5-rc.2 moved to
156
- * `node-pty@1.2.0-beta.15`, which does ship Linux builds.
157
- *
158
- * @param {string} output - the remote log tail.
159
- * @returns {string} a hint, or '' when nothing is recognized.
160
- */
161
- export function explainLaunchFailure(output) {
162
- const text = String(output || '')
163
- if (/pty\.node|Failed to load native module/i.test(text)) {
164
- return ' The remote could not load node-pty\'s native module. Known cause: dsh <= 0.1.0-rc.6'
165
- + ' depends on node-pty@1.1.0, which publishes no linux-x64 prebuild, so `dsh web` cannot start'
166
- + ' on Linux at all. Upgrade the remote dsh to 0.1.5-rc.2 or newer (node-pty@1.2.0-beta.15 ships'
167
- + ' the Linux build), or point `webAttachCommand` at a newer dsh installed elsewhere.'
168
- }
169
- if (/is intentionally not supported|--host 0\.0\.0\.0/i.test(text)) {
170
- return ' The remote dsh refused an all-interfaces bind. Attach deliberately never passes `--host`;'
171
- + ' check `webAttachCommand` does not add one.'
172
- }
173
- if (/command not found|No such file or directory|not found/i.test(text)) {
174
- return ' The remote shell could not run the dsh command. If the remote dsh is not on the SSH login'
175
- + ' PATH (a version manager or private prefix), set `webAttachCommand` to its absolute path.'
176
- }
177
- return ''
178
- }
179
-
180
- /**
181
- * Build the command that stops the remote process THIS session started.
182
- *
183
- * Two things make this less obvious than it looks, both found by running it
184
- * against a real host:
185
- * 1. The log path cannot identify the process — it appears only as a shell
186
- * redirect, so it is absent from argv and `pkill -f <logfile>` matches
187
- * nothing (the process survived, verified live).
188
- * 2. The PORT cannot identify it either, because we deliberately launch with
189
- * `--port 0` (the remote picks a free port, and the chosen number is only
190
- * known afterwards). A `--port 0` substring match therefore never fires.
191
- *
192
- * So the recorded PID is the handle, and the kill targets its process GROUP
193
- * (`kill -- -PID`): the launch goes through `setsid`, making the child a
194
- * session/group leader whose PGID equals its PID, so the group contains exactly
195
- * the process tree we started — never a sibling attach session and never the
196
- * user's own DSH. Before signalling, the command re-verifies that the PID still
197
- * exists and still looks like a `dsh` process, so a recycled PID belonging to an
198
- * unrelated program is not killed.
199
- *
200
- * @param {number} pid - the PID reported by the launch.
201
- * @param {string} [logPath] - this session's log file, removed after the kill so
202
- * repeated attaches do not accumulate files in the remote home.
203
- * @returns {string} a POSIX shell command (always exits 0, never throws).
204
- */
205
- export function buildStopCommand(pid, logPath = '') {
206
- const p = Number(pid) || 0
207
- const cleanup = logPath ? `; rm -f "$HOME/${logPath}" 2>/dev/null` : ''
208
- if (p < 1) return `true${cleanup}`
209
- return `P=${p}`
210
- + `; if [ -d "/proc/$P" ]; then`
211
- + ` C=$(tr '\\0' ' ' < "/proc/$P/cmdline" 2>/dev/null);`
212
- + ` case "$C" in *dsh*) kill -- -"$P" 2>/dev/null || kill "$P" 2>/dev/null;; esac;`
213
- + ` fi${cleanup}; true`
214
- }
215
-
216
- /**
217
- * One attached remote DSH Web UI: a local listener whose sockets are carried
218
- * over SSH to the remote's loopback web port.
219
- *
220
- * The listener is a plain `net.Server` + `client.forwardOut` pair — the same
221
- * mechanism `ForwardManager` uses for user-defined forwards. It is implemented
222
- * here rather than through that manager because this tunnel is bound to a
223
- * CHOSEN pool (the machine the user picked), whereas `ForwardManager` is wired
224
- * to the single "active machine" pool; routing an attach through it would send
225
- * the tunnel to whichever machine happened to be active.
226
- */
227
- export class WebAttach {
228
- /**
229
- * @param {object} opts - injected collaborators (all optional in production).
230
- * @param {object} [opts.net] - a `node:net`-compatible module (tests).
231
- * @param {number} [opts.localPortStart] - first local port to try.
232
- * @param {number} [opts.localPortMax] - how many ports to try before failing.
233
- * @param {boolean} [opts.trackPool] - follow the pool across reconnects so a
234
- * dropped SSH connection degrades to "disconnected" and then SELF-HEALS
235
- * instead of being a permanent dead end (issue #54). `true` in production.
236
- */
237
- constructor(opts = {}) {
238
- this.net = opts.net || net
239
- // `??`, not `||`: port 0 is a MEANINGFUL value here (let the OS pick), and
240
- // `0 || 3088` silently turned "let the OS choose" into a bind on a fixed
241
- // port. An explicit 0 now survives, which is also what lets a test ask for a
242
- // port without risking a collision with something really listening.
243
- this.localPortStart = opts.localPortStart ?? 3088
244
- this.localPortMax = opts.localPortMax ?? 50
245
- /** Whether the pool's lifecycle hooks are ours to install. */
246
- this.trackPool = opts.trackPool !== false
247
- /** @type {import('node:net').Server|null} */ this.server = null
248
- /** @type {Set<import('node:net').Socket>} */ this.sockets = new Set()
249
- /** @type {object|null} */ this.client = null
250
- /** The pool this session borrowed its connection from (may be null). */
251
- this.pool = null
252
- /** Pool hooks we installed, so close() can hand them back untouched. */
253
- this.prevOnReady = null
254
- this.prevOnCloseHook = null
255
- this.hookedPool = null
256
- this._installedOnReady = null
257
- this._installedOnClose = null
258
- this.attachedClient = null
259
- /** Bound listener, kept so it can be removed from the client. */
260
- this.onClientClose = null
261
- this.localPort = 0
262
- this.remotePort = 0
263
- this.token = ''
264
- this.tag = ''
265
- this.logPath = ''
266
- this.remotePid = 0
267
- this.machineId = ''
268
- this.command = ''
269
- this.startedAt = 0
270
- /** Launch knobs remembered so a restart after a drop uses the same ones. */
271
- this.waitSeconds = 0
272
- this.omittedNoOpen = false
273
- /** True while a reconnect-triggered re-resolve is in flight. */
274
- this._resolving = false
275
- /** True once the borrowed connection has been lost (drives recovery). */
276
- this.connectionLost = false
277
- /** undefined = "not asked yet"; false = the remote process is provably gone. */
278
- this._remoteAlive = undefined
279
- /** Set by close(): nothing may re-arm the tunnel afterwards. */
280
- this.closed = false
281
- /** Set once the borrowed connection has gone away (see _clientLost). */
282
- this.lastError = ''
283
- /**
284
- * A listener that throws EARNS an 'error' event on the emitting object, and
285
- * an 'error' with no listener is itself fatal — the very crash this module
286
- * exists to prevent. Nothing here is expected to throw, but a lifecycle
287
- * callback running on someone else's event loop must never be the reason
288
- * the host process dies, so both hooks are wrapped.
289
- */
290
- this._onReady = (client) => { try { this._attach(client) } catch { /* never fatal */ } }
291
- this._onPoolClose = () => { try { this._clientLost('ssh connection closed') } catch { /* never fatal */ } }
292
- }
293
-
294
- /** Whether the tunnel is currently listening. */
295
- get active() {
296
- return this.server !== null
297
- }
298
-
299
- /**
300
- * Attach to a remote DSH Web UI.
301
- *
302
- * @param {object} spec - the attach request.
303
- * @param {object} spec.pool - the SshPool for the chosen machine.
304
- * @param {string} spec.machineId - machine id, for bookkeeping.
305
- * @param {string} [spec.command] - remote dsh executable (default `dsh`).
306
- * @param {string} [spec.profile] - DSH profile to boot (default `web`).
307
- * @param {string} [spec.existingUrl] - attach to an ALREADY running remote
308
- * web UI instead of starting one: its `http://127.0.0.1:<port>/?token=…`.
309
- * @param {(cmd: string, opts?: object) => Promise<{stdout: string, code: number}>} [spec.exec]
310
- * - remote exec, defaulting to `pool.exec`.
311
- * @returns {Promise<{url: string, localPort: number, remotePort: number}>}
312
- */
313
- async open(spec) {
314
- const {
315
- pool, machineId = '', command = 'dsh', profile = 'web',
316
- existingUrl = '', dshHome = '', waitSeconds = 45,
317
- } = spec || {}
318
- if (!pool) throw new Error('web-attach: a machine pool is required')
319
- this.machineId = String(machineId || '')
320
- this.command = command
321
- this.waitSeconds = Number(waitSeconds) || 45
322
-
323
- const exec = spec.exec || ((cmd, opts) => pool.exec(cmd, opts))
324
- // Connecting first also surfaces credential/host-key problems BEFORE we
325
- // start a remote process we would then have to clean up. `_attach` (rather
326
- // than a bare assignment) is what subscribes to the connection's 'close',
327
- // so the loss is noticed the moment it happens instead of on the next
328
- // request — which is when the old code let ssh2 throw 'Not connected' from
329
- // inside a socket callback and take the host process with it (issue #54).
330
- this._attach(await pool.connect())
331
- this._followPool(pool)
332
-
333
- if (existingUrl) {
334
- const parsed = parseWebStart(`dsh web: ${existingUrl}`)
335
- if (!parsed) {
336
- throw new Error('web-attach: existing URL must look like http://127.0.0.1:<port>/?token=<token>')
337
- }
338
- this.remotePort = parsed.port
339
- this.token = parsed.token
340
- } else {
341
- this.tag = randomTag()
342
- const logPath = `${LOG_NAME}-${this.tag}.log`
343
- this.logPath = logPath
344
- const timeoutMs = Math.max(30000, (waitSeconds + 20) * 1000)
345
- let out = String(await this._launch(exec, { command, profile, logPath, dshHome, waitSeconds, timeoutMs }, false))
346
- // Older DSH (0.1.0-rc.6) has no `--no-open` and exits on the unknown flag
347
- // before doing anything. Retry once without it: `--no-open` is a nicety
348
- // (it stops the REMOTE from opening its own browser), not a requirement,
349
- // and a bounded single retry is safe because the first attempt provably
350
- // never started a server.
351
- if (launchFailed(out) && /unknown option/i.test(out) && /--no-open/.test(out)) {
352
- out = String(await this._launch(exec, { command, profile, logPath, dshHome, waitSeconds, timeoutMs }, true))
353
- this.omittedNoOpen = true
354
- }
355
- this.remotePid = parseRemotePid(out)
356
- const tail = out.split(TAIL_MARKER).slice(1).join(TAIL_MARKER).trim()
357
- // Both failure shapes carry the same diagnostics: the process either died
358
- // (its output is the whole story) or is still booting after the deadline.
359
- if (launchFailed(out)) {
360
- // The remote process is already gone — nothing to clean up.
361
- throw new Error('web-attach: the remote DSH exited during startup.'
362
- + explainLaunchFailure(tail || out)
363
- + ` ${tail || 'no output'}`)
364
- }
365
- const parsed = parseWebStart(out)
366
- if (!parsed) {
367
- // A timed-out launch may STILL be booting: the deadline expiring is not
368
- // evidence the process died. Kill it before throwing, or every retry
369
- // leaks another remote server (measured: three leftover `dsh --port 0`
370
- // processes after three failed attaches). A PID of 0 means the launcher
371
- // could not report one — nothing to target.
372
- if (this.remotePid > 0) {
373
- try {
374
- await execPosix(exec, buildStopCommand(this.remotePid, logPath), { timeoutMs: 20000 })
375
- this.remotePid = 0
376
- } catch { /* the process may already be gone; a leftover is worse than a failed kill attempt only if it repeats, and the next attach replaces this session */ }
377
- }
378
- throw new Error(
379
- `web-attach: the remote DSH did not report a startup token within ${waitSeconds}s.`
380
- + ` Check that \`${command}\` exists on the remote and can boot a web profile.`
381
- + explainLaunchFailure(tail || out)
382
- + (tail ? ` Remote output: ${tail}` : ''),
383
- )
384
- }
385
- this.remotePort = parsed.port
386
- this.token = parsed.token
387
- }
388
-
389
- await this._listen()
390
- this.startedAt = Date.now()
391
- return this.describe()
392
- }
393
-
394
- /**
395
- * Run one launch attempt and return its raw output.
396
- *
397
- * @param {(cmd: string, opts?: object) => Promise<{stdout: string}>} exec - remote exec.
398
- * @param {object} d - launch parameters plus the exec timeout.
399
- * @param {boolean} omitNoOpen - drop `--no-open` for old DSH.
400
- * @returns {Promise<string>} the launcher's stdout.
401
- */
402
- async _launch(exec, d, omitNoOpen) {
403
- const cmd = buildLaunchCommand({ ...d, omitNoOpen })
404
- const res = await execPosix(exec, cmd, { timeoutMs: d.timeoutMs })
405
- return String(res && res.stdout ? res.stdout : '')
406
- }
407
-
408
- /** Bind the local listener, advancing past ports already in use. */
409
- async _listen() {
410
- let lastError = null
411
- for (let i = 0; i < this.localPortMax; i++) {
412
- const port = this.localPortStart + i
413
- try {
414
- await this._listenOn(port)
415
- this.localPort = port
416
- return
417
- } catch (err) {
418
- lastError = err
419
- // Only a taken port is worth retrying; anything else (permissions,
420
- // an unusable interface) will not be fixed by the next number.
421
- if (err && err.code !== 'EADDRINUSE') break
422
- }
423
- }
424
- throw new Error(
425
- `web-attach: no free local port in ${this.localPortStart}..${this.localPortStart + this.localPortMax - 1}`
426
- + (lastError ? ` (${lastError.code || lastError.message})` : ''),
427
- )
428
- }
429
-
430
- _listenOn(port) {
431
- return new Promise((resolve, reject) => {
432
- const server = this.net.createServer((socket) => this._pipe(socket))
433
- const onError = (err) => {
434
- server.removeListener('listening', onListening)
435
- try { server.close() } catch { /* never listened */ }
436
- reject(err)
437
- }
438
- const onListening = () => {
439
- server.removeListener('error', onError)
440
- // A post-bind error must not crash the host process: report and drop
441
- // the tunnel so the UI can show "disconnected" instead of dying.
442
- server.on('error', (err) => {
443
- this.server = null
444
- this.lastError = String((err && err.message) || err)
445
- })
446
- this.server = server
447
- resolve()
448
- }
449
- server.once('error', onError)
450
- server.once('listening', onListening)
451
- // Loopback only: this endpoint reaches a full remote harness, so it must
452
- // never be reachable from the network even on a LAN-facing machine.
453
- server.listen(port, '127.0.0.1')
454
- })
455
- }
456
-
457
- /**
458
- * Borrow the given connection AND subscribe to its lifecycle.
459
- *
460
- * Idempotent for the same client (open() calls it once, the pool's `onReady`
461
- * calls it again on every reconnect), and it always drops the previous
462
- * client's listener first, so one session never accumulates listeners.
463
- *
464
- * @param {object|null} client - the live ssh2 client / OpenSshConnection.
465
- */
466
- _attach(client) {
467
- if (!client) return
468
- if (this.attachedClient && this.attachedClient !== client && this.onClientClose) {
469
- // A different client replaced the one we borrowed (pool reconnect). Stop
470
- // listening to the old one; its own 'close' has either fired already or
471
- // belongs to a connection nobody uses any more.
472
- try { this.attachedClient.removeListener('close', this.onClientClose) } catch { /* already gone */ }
473
- }
474
- this.client = client
475
- if (this.attachedClient === client) return
476
- this.attachedClient = client
477
- this.onClientClose = () => { this._clientLost('ssh connection closed') }
478
- // Without this, the object keeps handing out a connection that is already
479
- // closed, and `forwardOut` then throws SYNCHRONOUSLY (issue #54).
480
- try { client.on('close', this.onClientClose) } catch { /* not an emitter: nothing to watch */ }
481
- }
482
-
483
- /** The borrowed connection is gone: keep the session, drop the dead handle. */
484
- _clientLost(reason) {
485
- this.client = null
486
- this.connectionLost = true
487
- this.lastError = String(reason || 'ssh connection closed')
488
- }
489
-
490
- /**
491
- * Register lifecycle hooks on the chosen pool so this tunnel follows it.
492
- *
493
- * The pool is the one place that both NOTICES a dead connection and later
494
- * obtains a fresh one, and it exposes exactly two hooks for that:
495
- * • `onCloseHook` — fires from `close()` and `invalidate()` (the latter is
496
- * the "channel open failed, the pooled connection died server-side"
497
- * self-heal path, which is the likeliest trigger);
498
- * • `onReady` — fires after a successful (re)connect.
499
- *
500
- * Both are SINGLE-SLOT properties that the plugin already uses for
501
- * `ForwardManager` (index.js), so this session CHAINS them rather than
502
- * clobbering the forwards manager, and `_detachPool()` restores exactly what
503
- * was there — the plugin may legitimately have none, one, or both.
504
- *
505
- * A real reconnect is the only way the remote port can move, so once the pool
506
- * reports a new connection we must re-resolve (token, port) from the remote
507
- * log. `onReady` itself cannot await: the pool fires it with the client in
508
- * hand, so the re-resolve is kicked off and its failure is recorded rather
509
- * than thrown into the pool's callback.
510
- *
511
- * @param {object} pool - the pool this session attached through.
512
- */
513
- _followPool(pool) {
514
- if (!this.trackPool || this.closed || !pool || this.hookedPool === pool) return
515
- this._detachPool()
516
- this.pool = pool
517
- this.hookedPool = pool
518
- const prevReady = typeof pool.onReady === 'function' ? pool.onReady : null
519
- const prevClose = typeof pool.onCloseHook === 'function' ? pool.onCloseHook : null
520
- this.prevOnReady = prevReady
521
- this.prevOnCloseHook = prevClose
522
- const installedReady = (client) => {
523
- this._attach(client)
524
- if (prevReady) { try { prevReady(client) } catch { /* the forwards manager's problem, not ours */ } }
525
- // A reconnect lands on a NEW remote process only if the old one died with
526
- // the machine; re-read the log to find out which. The re-resolve runs off
527
- // the event loop because the pool cannot await it — a hook that throws
528
- // would earn an 'error' event on the pool, and an unhandled rejection
529
- // would be fatal.
530
- if (!this.closed && this.remotePort && !this._resolving) {
531
- this._resolving = true
532
- Promise.resolve()
533
- .then(() => this._refreshRemotePort())
534
- .catch((err) => { this.lastError = String((err && err.message) || err) })
535
- .then(() => { this._resolving = false })
536
- }
537
- }
538
- const installedClose = () => {
539
- this._clientLost('ssh connection closed')
540
- if (prevClose) { try { prevClose() } catch { /* never mask our own report */ } }
541
- }
542
- this._installedOnReady = installedReady
543
- this._installedOnClose = installedClose
544
- pool.onReady = installedReady
545
- pool.onCloseHook = installedClose
546
- }
547
-
548
- /**
549
- * Hand the pool's hooks back.
550
- *
551
- * Each slot is restored ONLY when it still holds the wrapper this session
552
- * installed. The pool's hooks are single-slot, so if something else has taken
553
- * the slot over in the meantime, putting a stale callback back would be worse
554
- * than leaving it alone — it would silently disconnect a newer owner.
555
- */
556
- _detachPool() {
557
- const pool = this.hookedPool
558
- const mineReady = this._installedOnReady
559
- const mineClose = this._installedOnClose
560
- this.hookedPool = null
561
- this._installedOnReady = null
562
- this._installedOnClose = null
563
- if (!pool) return
564
- if (mineReady && pool.onReady === mineReady) pool.onReady = this.prevOnReady
565
- if (mineClose && pool.onCloseHook === mineClose) pool.onCloseHook = this.prevOnCloseHook
566
- this.prevOnReady = null
567
- this.prevOnCloseHook = null
568
- }
569
-
570
- /**
571
- * True when the borrowed connection was LOST and this is a session we can
572
- * recover: we launched the remote process ourselves (so we hold its PID and
573
- * log) and the tunnel is listening (so clients can actually be served).
574
- *
575
- * The `connectionLost` flag is deliberately separate from `this.client`: the
576
- * pool's `onReady` re-attaches the new client BEFORE the re-resolve runs, so a
577
- * check on `!this.client` would be false by then and recovery would never
578
- * happen.
579
- */
580
- get _needsReResolve() {
581
- return !!(this.connectionLost && !this.closed && this.logPath && this.remotePid && this.localPort)
582
- }
583
-
584
- /**
585
- * Re-resolve the remote port after a reconnect, restarting the remote `dsh web`
586
- * when it did not survive.
587
- *
588
- * Reaching a remote process needs a live SSH connection, so this reconnects
589
- * through the pool first — the pool reports `onReady` for that same client in
590
- * production, and in a test double the callback simply never fires.
591
- */
592
- async _refreshRemotePort() {
593
- if (!this._needsReResolve) return
594
- const pool = this.pool
595
- if (!pool || (typeof pool.connect !== 'function' && typeof pool.exec !== 'function')) return
596
- const exec = (cmd, opts) => (typeof pool.exec === 'function'
597
- ? pool.exec(cmd, opts)
598
- : Promise.reject(new Error('web-attach: the pool cannot run commands')))
599
- if (!this.client) await pool.connect()
600
- const match = await this._resolveRemotePort(exec)
601
- this.remotePort = match.port
602
- if (match.token) this.token = match.token
603
- this.connectionLost = false
604
- this.lastError = ''
605
- }
606
-
607
- /**
608
- * Read this session's remote log and decide which port is live.
609
- *
610
- * The startup line is the ONLY source of the port (the launch deliberately
611
- * uses `--port 0`), so after the remote process died and was restarted the log
612
- * holds BOTH lines — the dead one and the new one — and neither position
613
- * identifies the live one. Evidence decides:
614
- * • a process that is still alive on the remote is probed first, and when
615
- * the port it is LISTENING on is one of the logged ports, that is the
616
- * answer (the `dsh web: …` line names its own port, so this is a
617
- * confirmation rather than a second guess);
618
- * • otherwise the newest logged port wins, which is right in every
619
- * single-process case and is the best available answer while the remote is
620
- * still booting (the next reconnect retries).
621
- *
622
- * @param {(cmd: string, opts?: object) => Promise<{stdout: string}>} exec - remote exec.
623
- * @returns {Promise<{port: number, token: string, restarted: boolean}>}
624
- */
625
- async _resolveRemotePort(exec) {
626
- this._remoteAlive = await this._remoteProcessAlive(exec)
627
- if (!this._remoteAlive) return this._restartRemote(exec)
628
-
629
- let out = ''
630
- try {
631
- const res = await execPosix(exec, `cat "$HOME/${this.logPath}" 2>/dev/null`, { timeoutMs: 15000 })
632
- out = String((res && res.stdout) || '')
633
- } catch { /* an unreadable log: the listening probe below is the fallback */ }
634
- const lines = [...out.matchAll(/dsh web:\s*(http:\/\/[^\s]+)/g)]
635
- .map((m) => parseWebStart(`dsh web: ${m[1]}`))
636
- .filter(Boolean)
637
-
638
- // What the recorded process actually listens on beats any guess from the
639
- // log, because a killed-and-restarted remote leaves BOTH startup lines in
640
- // the log and neither position says which one is live.
641
- const listening = await this._listeningRemotePort(exec)
642
- if (listening) {
643
- const match = lines.find((l) => l.port === listening)
644
- return { port: listening, token: (match && match.token) || this.token, restarted: false }
645
- }
646
- if (lines.length) {
647
- const newest = lines[lines.length - 1]
648
- return { port: newest.port, token: newest.token, restarted: false }
649
- }
650
- // Alive but silent and not listening yet: the remote is booting. Keep the
651
- // last known port and let the next reconnect re-resolve.
652
- return { port: this.remotePort, token: this.token, restarted: false }
653
- }
654
-
655
- /**
656
- * Whether the remote process THIS session started still exists.
657
- *
658
- * Verified through `/proc`, which is Linux-only; a host that cannot answer (or
659
- * a failed probe) is treated as ALIVE on purpose. Restarting a server that was
660
- * never dead would spawn a second one and leak a port, whereas assuming life
661
- * merely retries a port that turns out to be stale.
662
- *
663
- * @param {(cmd: string, opts?: object) => Promise<{stdout: string}>} exec - remote exec.
664
- * @returns {Promise<boolean>}
665
- */
666
- async _remoteProcessAlive(exec) {
667
- const pid = Number(this.remotePid) || 0
668
- if (pid < 1) return true
669
- try {
670
- const res = await execPosix(
671
- exec,
672
- `if [ -d /proc ]; then { [ -d /proc/${pid} ] && echo ALIVE; } || echo GONE; else echo ALIVE; fi`,
673
- { timeoutMs: 15000 },
674
- )
675
- return !/GONE/.test(String((res && res.stdout) || ''))
676
- } catch { return true }
677
- }
678
-
679
- /**
680
- * Ask the remote which loopback port the recorded PID listens on (0 = none).
681
- *
682
- * Two `/proc` reads are needed because a TCP listener appears in a socket
683
- * table (`/proc/net/tcp{,6}`), not in that process's link list: the fd
684
- * symlinks give the socket INODE, and the table maps that inode to a port.
685
- * Matching on the inode rather than the port is what makes this an
686
- * observation instead of a second guess.
687
- */
688
- async _listeningRemotePort(exec) {
689
- const pid = Number(this.remotePid) || 0
690
- if (pid < 1) return 0
691
- let inodes = ''
692
- try {
693
- // `ls -l` on a process's own fds needs no privileges for the same uid.
694
- const res = await execPosix(
695
- exec,
696
- `ls -l /proc/${pid}/fd 2>/dev/null | sed -n 's/.*socket:\\[\\([0-9]*\\)\\].*/\\1/p' | sort -u | tr '\\n' ' '`,
697
- { timeoutMs: 15000 },
698
- )
699
- inodes = String((res && res.stdout) || '').trim()
700
- } catch { return 0 }
701
- if (!inodes) return 0
702
- const want = new Set(inodes.split(/\s+/).filter(Boolean))
703
- // `/proc/net/tcp` addresses are little-endian hex, so loopback is
704
- // `0100007F` (v4) and `00000000000000000000000001000000` (v6 `::1`).
705
- const LOOPBACK = new Set(['0100007F', '00000000000000000000000001000000'])
706
- for (const file of ['/proc/net/tcp', '/proc/net/tcp6']) {
707
- let text = ''
708
- try {
709
- const res = await execPosix(exec, `cat ${file} 2>/dev/null`, { timeoutMs: 15000 })
710
- text = String((res && res.stdout) || '')
711
- } catch { continue }
712
- for (const line of text.split('\n').slice(1)) {
713
- const cols = line.trim().split(/\s+/)
714
- // sl local_address rem_address st tx:rx tr:tm->when retrnsmt uid timeout inode
715
- if (cols.length < 10) continue
716
- if (cols[3] !== '0A') continue // TCP_LISTEN
717
- if (!want.has(cols[9])) continue
718
- const [addr, portHex] = String(cols[1]).split(':')
719
- if (!LOOPBACK.has(String(addr).toUpperCase())) continue
720
- const port = parseInt(portHex, 16)
721
- if (Number.isInteger(port) && port > 0 && port < 65536) return port
722
- }
723
- }
724
- return 0
725
- }
726
-
727
- /**
728
- * Relaunch the remote `dsh web` because the previous process is gone.
729
- *
730
- * A restart CANNOT change the listening port locally, and a caller holding a
731
- * stale port silently talks to the wrong place at worst and hangs at best, so
732
- * the two facts the caller needs are checked: this is a session that launched
733
- * its own process (an attach onto someone else's DSH stays hands-off and can
734
- * never restart it), and recovery is possible at all (`_refreshRemotePort`
735
- * has already returned early when it is not).
736
- */
737
- async _restartRemote(exec) {
738
- const command = this.command || 'dsh'
739
- const waitSeconds = this.waitSeconds || 45
740
- const timeoutMs = Math.max(30000, (waitSeconds + 20) * 1000)
741
- let out = String(await this._launch(exec, { command, profile: 'web', logPath: this.logPath, waitSeconds, timeoutMs }, this.omittedNoOpen === true))
742
- if (launchFailed(out) && /unknown option/i.test(out) && /--no-open/.test(out)) {
743
- out = String(await this._launch(exec, { command, profile: 'web', logPath: this.logPath, waitSeconds, timeoutMs }, true))
744
- this.omittedNoOpen = true
745
- }
746
- this.remotePid = parseRemotePid(out) || this.remotePid
747
- const parsed = parseWebStart(out)
748
- if (!parsed) {
749
- const tail = out.split(TAIL_MARKER).slice(1).join(TAIL_MARKER).trim()
750
- throw new Error('web-attach: the remote DSH could not be restarted after the SSH'
751
- + ' connection dropped.' + explainLaunchFailure(tail || out) + (tail ? ` Remote output: ${tail}` : ''))
752
- }
753
- return { port: parsed.port, token: parsed.token, restarted: true }
754
- }
755
-
756
- /** Carry one local socket to the remote web port over SSH. */
757
- _pipe(socket) {
758
- if (!this.client) { try { socket.destroy() } catch { /* already gone */ } return }
759
- // ssh2's forwardOut does NOT report a dead connection through its callback:
760
- // when the socket is gone it THROWS 'Not connected' synchronously
761
- // (ssh2/lib/client.js: `if (!this._sock || !isWritable(this._sock)) throw`)
762
- // and the callback below is never reached — so `if (err)` cannot guard this
763
- // path. Uncaught, that throw travels net.Server → TCP.onconnection and kills
764
- // the whole host process (issue #54: every page refresh after the pooled
765
- // connection dropped took the session, the browser and the remote orphan
766
- // down with it). A dead tunnel is a UI state, not a reason to exit.
767
- try {
768
- this.client.forwardOut('127.0.0.1', 0, '127.0.0.1', this.remotePort, (err, channel) => {
769
- if (err) { try { socket.destroy() } catch { /* already gone */ } return }
770
- this.sockets.add(socket)
771
- socket.pipe(channel)
772
- channel.pipe(socket)
773
- const kill = () => {
774
- try { socket.destroy() } catch { /* already gone */ }
775
- try { channel.close() } catch { /* already closed */ }
776
- this.sockets.delete(socket)
777
- }
778
- socket.on('error', kill)
779
- channel.on('error', kill)
780
- socket.on('close', kill)
781
- channel.on('close', kill)
782
- })
783
- } catch (err) {
784
- this._clientLost(String((err && err.message) || err))
785
- try { socket.destroy() } catch { /* already gone */ }
786
- }
787
- }
788
-
789
- /**
790
- * The URL to open, carrying the one-time launch token.
791
- *
792
- * The token is a credential, so it stays on loopback and is never sent
793
- * anywhere; DSH exchanges it for a 30-day signed cookie on the first request
794
- * and redirects to a clean `/`.
795
- */
796
- get url() {
797
- return `http://127.0.0.1:${this.localPort}/?token=${this.token}`
798
- }
799
-
800
- /** The clean URL (no token) — what the address bar shows after the exchange. */
801
- get cleanUrl() {
802
- return `http://127.0.0.1:${this.localPort}/`
803
- }
804
-
805
- /** Serializable status for the settings UI. */
806
- describe() {
807
- return {
808
- machineId: this.machineId,
809
- url: this.url,
810
- cleanUrl: this.cleanUrl,
811
- token: this.token,
812
- localPort: this.localPort,
813
- remotePort: this.remotePort,
814
- active: this.active,
815
- startedAt: this.startedAt,
816
- // Only a process we launched can be stopped by us; an attach onto the
817
- // user's own running instance is deliberately hands-off.
818
- managed: this.remotePid > 0,
819
- error: this.lastError || '',
820
- }
821
- }
822
-
823
- /**
824
- * Tear the tunnel down. The remote process is left running by default: the
825
- * user may be using that DSH elsewhere, and silently killing a process we did
826
- * not start is worse than a leftover one. `stopRemote` opts in.
827
- *
828
- * @param {object} [opts] - close options.
829
- * @param {boolean} [opts.stopRemote] - also terminate the remote process.
830
- * @param {(cmd: string) => Promise<unknown>} [opts.exec] - remote exec.
831
- */
832
- async close({ stopRemote = false, exec } = {}) {
833
- // Stop following the pool BEFORE any await: a reconnect landing mid-teardown
834
- // must not re-arm the tunnel this call is in the middle of closing.
835
- this._detachPool()
836
- if (this.attachedClient && this.onClientClose) {
837
- try { this.attachedClient.removeListener('close', this.onClientClose) } catch { /* already gone */ }
838
- }
839
- this.attachedClient = null
840
- this.onClientClose = null
841
- this.pool = null
842
- for (const socket of [...this.sockets]) {
843
- try { socket.destroy() } catch { /* already gone */ }
844
- }
845
- this.sockets.clear()
846
- const server = this.server
847
- this.server = null
848
- if (server) await new Promise((resolve) => server.close(() => resolve()))
849
- // Only a process we started has a recorded PID; an attach to the user's own
850
- // running instance must never signal anything.
851
- if (stopRemote && exec && this.remotePid) {
852
- await Promise.resolve(execPosix(exec, buildStopCommand(this.remotePid, this.logPath))).catch(() => {})
853
- }
854
- this.client = null
855
- // The recorded PID and log path are FACTS about this session (the UI shows
856
- // them, and `stopRemote` addresses them), so they survive; `closed` is what
857
- // stops recovery work from being re-armed after teardown.
858
- this.closed = true
859
- }
860
- }
1
+ // dsh-remote — "remote DSH web UI" attach sessions (issue #46).
2
+ //
3
+ // The user's intent behind that issue is "use the local DSH as a CLIENT for a
4
+ // DSH running on another machine": they do NOT want the remote to expose an
5
+ // inbound listener. DSH makes that impossible anyway — `dsh-web-app` hard-
6
+ // rejects `--host 0.0.0.0` (startup.js) because it would put remote code
7
+ // execution on the network, and `dsh-host-webserver` only accepts the
8
+ // 127.0.0.1/0.0.0.0 literals.
9
+ //
10
+ // So this module inverts the direction, exactly like the rest of the plugin:
11
+ // we SSH OUT, start (or reuse) a loopback-bound `dsh web` on the remote, and
12
+ // carry its socket back over our own SSH connection with a local TCP forward.
13
+ // The browser then talks to 127.0.0.1:<localPort> on this machine.
14
+ //
15
+ // Verified end-to-end on a real Linux host (dsh 0.1.5-rc.2): a bare TCP forward
16
+ // is sufficient — the SPA, its assets, AND the `/api/remote.mux` WebSocket
17
+ // upgrade all transit it (HTTP/1.1 101), with no reverse proxy and no host
18
+ // rewriting. That works because DSH binds its auth cookie to the request
19
+ // authority, so a cookie minted against `127.0.0.1:<localPort>` is exactly what
20
+ // the browser then sends back to that same authority.
21
+ //
22
+ // Three details drive the design and are worth stating once:
23
+ //
24
+ // 1. The launch token CANNOT be read from anywhere but stdout. It is a
25
+ // `randomBytes` value held in a process-local WeakMap and printed on one
26
+ // line (`dsh web: http://127.0.0.1:<port>/?token=…`). No file, no env var.
27
+ // Therefore the token is captured by redirecting the remote process's
28
+ // output to a log file and parsing that line out of it.
29
+ // 2. `--port 0` lets the remote OS pick a free port, and the same printed line
30
+ // reports which port it chose — so we never have to guess or probe for a
31
+ // free port on the remote.
32
+ // 3. The pairing that must survive is (token, port) from ONE launch. Reading
33
+ // them from one line is what keeps them consistent.
34
+ //
35
+ // Everything here is read-only with respect to the remote filesystem except
36
+ // the log file it creates under the remote `$HOME`.
37
+ import net from 'node:net'
38
+ import posixShell from './posix-shell.cjs'
39
+
40
+ const { posixViaSh } = posixShell
41
+
42
+ /** Execute an INTERNAL POSIX script without depending on the login shell. */
43
+ function execPosix(exec, command, opts) {
44
+ return exec(posixViaSh(command), opts)
45
+ }
46
+
47
+ /** Remote log file per attach session; `$HOME` is expanded by the remote shell. */
48
+ const LOG_NAME = '.dsh-remote-web'
49
+
50
+ /**
51
+ * Parse the `dsh web:` startup line out of a remote log.
52
+ *
53
+ * The line looks like:
54
+ * dsh web: http://127.0.0.1:43129/?token=Iy7FKuPSI5qJKJUFDyah4B6i8Ul6_hvspiJhiWufYt8
55
+ * and may be followed by a LAN suffix when the remote bound 0.0.0.0 (it never
56
+ * will here — we never pass `--host` — but tolerate it rather than break).
57
+ *
58
+ * @param {string} text - the remote log contents.
59
+ * @returns {{url: string, port: number, token: string}|null} parsed facts, or
60
+ * null when the line has not appeared yet (still booting) or is malformed.
61
+ */
62
+ export function parseWebStart(text) {
63
+ if (typeof text !== 'string' || text === '') return null
64
+ // Take the LAST match: a reused log file may hold an earlier session's line,
65
+ // and the newest one is the one this launch produced.
66
+ const matches = [...text.matchAll(/dsh web:\s*(http:\/\/[^\s]+)/g)]
67
+ if (matches.length === 0) return null
68
+ const url = matches[matches.length - 1][1]
69
+ let parsed
70
+ try {
71
+ parsed = new URL(url)
72
+ } catch {
73
+ return null
74
+ }
75
+ const port = Number(parsed.port)
76
+ const token = parsed.searchParams.get('token') || ''
77
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null
78
+ if (!token) return null
79
+ return { url, port, token }
80
+ }
81
+
82
+ /** True when the log proves the remote process died instead of booting. */
83
+ export function launchFailed(text) {
84
+ return typeof text === 'string' && text.includes(DEAD_MARKER)
85
+ }
86
+
87
+ /** Marker the remote launcher echoes when the process exits before printing. */
88
+ const DEAD_MARKER = '__DSH_REMOTE_DIED__'
89
+ /** Marker separating the parsed line from the raw log tail for diagnostics. */
90
+ export const TAIL_MARKER = '__DSH_TAIL__'
91
+ /** Marker carrying the remote PID so the session can stop its own process. */
92
+ export const PID_MARKER = '__DSH_PID__='
93
+
94
+ /**
95
+ * Budget for the issue #125 discovery step. Asking "is one already running?"
96
+ * must never delay a spawn by more than a few seconds, so the default sits
97
+ * well under the launch wait; a slower answer is treated as "no answer".
98
+ */
99
+ export const DISCOVER_TIMEOUT_MS = 8000
100
+ /** Budget for the post-discovery liveness probe (see _probeRemoteWeb). */
101
+ export const PROBE_TIMEOUT_MS = 4000
102
+
103
+ /**
104
+ * Parse the URL a discover command printed (issue #125).
105
+ *
106
+ * The discovery contract is deliberately lenient — the command is user-written
107
+ * glue (a systemd status scrape, a saved URL file, a PowerShell one-liner) and
108
+ * may print banner noise around the answer. Scan for `http(s)://` lines from
109
+ * the END backwards and take the first one that pins a real port AND a token —
110
+ * the same two facts a launch line provides. Walking past invalid matches (a
111
+ * trailing "see https://…" trailer) is what keeps noise from defeating an
112
+ * otherwise correct command. Anything less than a port+token pair is not a
113
+ * discoverable instance and degrades to "miss", so the caller falls back to
114
+ * spawning.
115
+ *
116
+ * @param {string} text - the discover command's stdout.
117
+ * @returns {{url: string, port: number, token: string}|null}
118
+ */
119
+ export function parseDiscoveredUrl(text) {
120
+ if (typeof text !== 'string' || text === '') return null
121
+ const lines = text.split('\n')
122
+ for (let i = lines.length - 1; i >= 0; i--) {
123
+ const m = /https?:\/\/[^\s"']+/.exec(lines[i])
124
+ if (!m) continue
125
+ let parsed
126
+ try {
127
+ parsed = new URL(m[0])
128
+ } catch {
129
+ continue
130
+ }
131
+ const port = Number(parsed.port)
132
+ const token = parsed.searchParams.get('token') || ''
133
+ if (!Number.isInteger(port) || port < 1 || port > 65535) continue
134
+ if (!token) continue
135
+ // The tunnel always targets the remote LOOPBACK. Refuse a non-loopback
136
+ // claim rather than sending its token to an unrelated local port that may
137
+ // happen to answer HTTP (the launch/existingUrl contract is loopback too).
138
+ if (parsed.hostname !== '127.0.0.1' && parsed.hostname !== 'localhost' && parsed.hostname !== '[::1]') continue
139
+ return { url: m[0], port, token }
140
+ }
141
+ return null
142
+ }
143
+ /** Random ASCII tag so two attach sessions never share a remote log file. */
144
+ function randomTag() {
145
+ return Math.random().toString(36).slice(2, 8) + Date.now().toString(36).slice(-4)
146
+ }
147
+
148
+ /**
149
+ * Build the one-shot remote command that launches `dsh web` detached and waits
150
+ * for its startup line.
151
+ *
152
+ * `setsid` + `nohup` + redirected stdio are all required: the SSH channel closes
153
+ * as soon as this shell exits, and without detaching the SIGHUP would kill the
154
+ * server we just started. The loop is bounded so a wedged remote cannot hang the
155
+ * call past the caller's own timeout, and it reports either the parsed line or
156
+ * the log tail — never silence.
157
+ *
158
+ * @param {object} spec - launch parameters.
159
+ * @param {boolean} [spec.omitNoOpen] - drop `--no-open`. Older DSH (measured on
160
+ * 0.1.0-rc.6) has no such flag and exits with "unknown option '--no-open'";
161
+ * the caller retries with this set rather than assuming a flag exists.
162
+ * @returns {string} a POSIX shell command line (no newlines, ASCII only).
163
+ */
164
+ export function buildLaunchCommand({ command, profile, logPath, remotePort = 0, dshHome = '', waitSeconds = 45, omitNoOpen = false }) {
165
+ const env = dshHome ? `DSH_HOME="${dshHome}" ` : ''
166
+ const noOpen = omitNoOpen ? '' : ' --no-open'
167
+ const args = `--profile ${profile} --port ${Number(remotePort) || 0}${noOpen}`
168
+ const limit = Number(waitSeconds) || 45
169
+ // The loop is ONE shell element: `do` is a keyword and `do;` is a syntax error
170
+ // in POSIX sh, so it must be glued to the first command of the body rather
171
+ // than separated like the other statements.
172
+ const loop = `while [ $i -lt ${limit} ]; do grep -q 'token=' "$LOG" 2>/dev/null && break`
173
+ + `; kill -0 $P 2>/dev/null || { echo ${DEAD_MARKER}; break; }`
174
+ + `; sleep 1; i=$((i+1)); done`
175
+ return [
176
+ `LOG="$HOME/${logPath}"`,
177
+ `: > "$LOG"`,
178
+ // `command -v setsid` guards hosts without util-linux (macOS); plain nohup
179
+ // still detaches from the channel's HUP there.
180
+ `command -v setsid >/dev/null 2>&1 && SET=setsid || SET=`,
181
+ `${env}$SET nohup ${command} ${args} >"$LOG" 2>&1 </dev/null & P=$!`,
182
+ `i=0`,
183
+ loop,
184
+ `echo "${PID_MARKER}$P"`,
185
+ `grep -m1 'dsh web:' "$LOG" 2>/dev/null`,
186
+ `echo ${TAIL_MARKER}`,
187
+ `tail -20 "$LOG" 2>/dev/null`,
188
+ ].join('; ')
189
+ }
190
+
191
+ /** Extract the remote PID from launcher output (0 when absent). */
192
+ export function parseRemotePid(output) {
193
+ const m = /__DSH_PID__=(\d+)/.exec(String(output || ''))
194
+ return m ? Number(m[1]) : 0
195
+ }
196
+
197
+ /**
198
+ * Recognize a known remote-side reason the web surface could not start, and
199
+ * return an actionable sentence for it.
200
+ *
201
+ * The point is to keep an operator from reading "the remote DSH did not report a
202
+ * startup token" and concluding the *plugin* is broken. Measured cause: dsh
203
+ * ≤ 0.1.0-rc.6 depends on `node-pty@1.1.0`, whose published tarball ships
204
+ * darwin/win32 prebuilds but **no `linux-x64`**, so `dsh web` cannot boot on
205
+ * Linux at all — it dies loading the native module. 0.1.5-rc.2 moved to
206
+ * `node-pty@1.2.0-beta.15`, which does ship Linux builds.
207
+ *
208
+ * @param {string} output - the remote log tail.
209
+ * @returns {string} a hint, or '' when nothing is recognized.
210
+ */
211
+ export function explainLaunchFailure(output) {
212
+ const text = String(output || '')
213
+ if (/pty\.node|Failed to load native module/i.test(text)) {
214
+ return ' The remote could not load node-pty\'s native module. Known cause: dsh <= 0.1.0-rc.6'
215
+ + ' depends on node-pty@1.1.0, which publishes no linux-x64 prebuild, so `dsh web` cannot start'
216
+ + ' on Linux at all. Upgrade the remote dsh to 0.1.5-rc.2 or newer (node-pty@1.2.0-beta.15 ships'
217
+ + ' the Linux build), or point `webAttachCommand` at a newer dsh installed elsewhere.'
218
+ }
219
+ if (/is intentionally not supported|--host 0\.0\.0\.0/i.test(text)) {
220
+ return ' The remote dsh refused an all-interfaces bind. Attach deliberately never passes `--host`;'
221
+ + ' check `webAttachCommand` does not add one.'
222
+ }
223
+ if (/command not found|No such file or directory|not found/i.test(text)) {
224
+ return ' The remote shell could not run the dsh command. If the remote dsh is not on the SSH login'
225
+ + ' PATH (a version manager or private prefix), set `webAttachCommand` to its absolute path.'
226
+ }
227
+ return ''
228
+ }
229
+
230
+ /**
231
+ * Build the command that stops the remote process THIS session started.
232
+ *
233
+ * Two things make this less obvious than it looks, both found by running it
234
+ * against a real host:
235
+ * 1. The log path cannot identify the process — it appears only as a shell
236
+ * redirect, so it is absent from argv and `pkill -f <logfile>` matches
237
+ * nothing (the process survived, verified live).
238
+ * 2. The PORT cannot identify it either, because we deliberately launch with
239
+ * `--port 0` (the remote picks a free port, and the chosen number is only
240
+ * known afterwards). A `--port 0` substring match therefore never fires.
241
+ *
242
+ * So the recorded PID is the handle, and the kill targets its process GROUP
243
+ * (`kill -- -PID`): the launch goes through `setsid`, making the child a
244
+ * session/group leader whose PGID equals its PID, so the group contains exactly
245
+ * the process tree we started — never a sibling attach session and never the
246
+ * user's own DSH. Before signalling, the command re-verifies that the PID still
247
+ * exists and still looks like a `dsh` process, so a recycled PID belonging to an
248
+ * unrelated program is not killed.
249
+ *
250
+ * @param {number} pid - the PID reported by the launch.
251
+ * @param {string} [logPath] - this session's log file, removed after the kill so
252
+ * repeated attaches do not accumulate files in the remote home.
253
+ * @returns {string} a POSIX shell command (always exits 0, never throws).
254
+ */
255
+ export function buildStopCommand(pid, logPath = '') {
256
+ const p = Number(pid) || 0
257
+ const cleanup = logPath ? `; rm -f "$HOME/${logPath}" 2>/dev/null` : ''
258
+ if (p < 1) return `true${cleanup}`
259
+ return `P=${p}`
260
+ + `; if [ -d "/proc/$P" ]; then`
261
+ + ` C=$(tr '\\0' ' ' < "/proc/$P/cmdline" 2>/dev/null);`
262
+ + ` case "$C" in *dsh*) kill -- -"$P" 2>/dev/null || kill "$P" 2>/dev/null;; esac;`
263
+ + ` fi${cleanup}; true`
264
+ }
265
+
266
+ /**
267
+ * One attached remote DSH Web UI: a local listener whose sockets are carried
268
+ * over SSH to the remote's loopback web port.
269
+ *
270
+ * The listener is a plain `net.Server` + `client.forwardOut` pair — the same
271
+ * mechanism `ForwardManager` uses for user-defined forwards. It is implemented
272
+ * here rather than through that manager because this tunnel is bound to a
273
+ * CHOSEN pool (the machine the user picked), whereas `ForwardManager` is wired
274
+ * to the single "active machine" pool; routing an attach through it would send
275
+ * the tunnel to whichever machine happened to be active.
276
+ */
277
+ export class WebAttach {
278
+ /**
279
+ * @param {object} opts - injected collaborators (all optional in production).
280
+ * @param {object} [opts.net] - a `node:net`-compatible module (tests).
281
+ * @param {number} [opts.localPortStart] - first local port to try.
282
+ * @param {number} [opts.localPortMax] - how many ports to try before failing.
283
+ * @param {boolean} [opts.trackPool] - follow the pool across reconnects so a
284
+ * dropped SSH connection degrades to "disconnected" and then SELF-HEALS
285
+ * instead of being a permanent dead end (issue #54). `true` in production.
286
+ */
287
+ constructor(opts = {}) {
288
+ this.net = opts.net || net
289
+ // `??`, not `||`: port 0 is a MEANINGFUL value here (let the OS pick), and
290
+ // `0 || 3088` silently turned "let the OS choose" into a bind on a fixed
291
+ // port. An explicit 0 now survives, which is also what lets a test ask for a
292
+ // port without risking a collision with something really listening.
293
+ this.localPortStart = opts.localPortStart ?? 3088
294
+ this.localPortMax = opts.localPortMax ?? 50
295
+ /** Whether the pool's lifecycle hooks are ours to install. */
296
+ this.trackPool = opts.trackPool !== false
297
+ /** Issue #125 discovery budgets (injectable so tests need not wait 8s). */
298
+ this.discoverTimeoutMs = opts.discoverTimeoutMs ?? DISCOVER_TIMEOUT_MS
299
+ this.probeTimeoutMs = opts.probeTimeoutMs ?? PROBE_TIMEOUT_MS
300
+ /** @type {import('node:net').Server|null} */ this.server = null
301
+ /** @type {Set<import('node:net').Socket>} */ this.sockets = new Set()
302
+ /** @type {object|null} */ this.client = null
303
+ /** The pool this session borrowed its connection from (may be null). */
304
+ this.pool = null
305
+ /** Pool hooks we installed, so close() can hand them back untouched. */
306
+ this.prevOnReady = null
307
+ this.prevOnCloseHook = null
308
+ this.hookedPool = null
309
+ this._installedOnReady = null
310
+ this._installedOnClose = null
311
+ this.attachedClient = null
312
+ /** Bound listener, kept so it can be removed from the client. */
313
+ this.onClientClose = null
314
+ this.localPort = 0
315
+ this.remotePort = 0
316
+ this.token = ''
317
+ this.tag = ''
318
+ this.logPath = ''
319
+ this.remotePid = 0
320
+ this.machineId = ''
321
+ this.command = ''
322
+ this.startedAt = 0
323
+ /**
324
+ * Issue #125 outcome of the discovery step: '' when no discover command
325
+ * was configured (or an explicit existingUrl bypassed it); otherwise
326
+ * 'hit' (a live resident instance was adopted), 'miss', 'timeout',
327
+ * 'error', or 'probe-failed' — the last four all mean "fell back to
328
+ * spawning" and differ only in WHY, which the UI relays to the user.
329
+ */
330
+ this.discovery = ''
331
+ /** Launch knobs remembered so a restart after a drop uses the same ones. */
332
+ this.waitSeconds = 0
333
+ this.omittedNoOpen = false
334
+ /** True while a reconnect-triggered re-resolve is in flight. */
335
+ this._resolving = false
336
+ /** True once the borrowed connection has been lost (drives recovery). */
337
+ this.connectionLost = false
338
+ /** undefined = "not asked yet"; false = the remote process is provably gone. */
339
+ this._remoteAlive = undefined
340
+ /** Set by close(): nothing may re-arm the tunnel afterwards. */
341
+ this.closed = false
342
+ /** Set once the borrowed connection has gone away (see _clientLost). */
343
+ this.lastError = ''
344
+ /**
345
+ * A listener that throws EARNS an 'error' event on the emitting object, and
346
+ * an 'error' with no listener is itself fatal — the very crash this module
347
+ * exists to prevent. Nothing here is expected to throw, but a lifecycle
348
+ * callback running on someone else's event loop must never be the reason
349
+ * the host process dies, so both hooks are wrapped.
350
+ */
351
+ this._onReady = (client) => { try { this._attach(client) } catch { /* never fatal */ } }
352
+ this._onPoolClose = () => { try { this._clientLost('ssh connection closed') } catch { /* never fatal */ } }
353
+ }
354
+
355
+ /** Whether the tunnel is currently listening. */
356
+ get active() {
357
+ return this.server !== null
358
+ }
359
+
360
+ /**
361
+ * Attach to a remote DSH Web UI.
362
+ *
363
+ * @param {object} spec - the attach request.
364
+ * @param {object} spec.pool - the SshPool for the chosen machine.
365
+ * @param {string} spec.machineId - machine id, for bookkeeping.
366
+ * @param {string} [spec.command] - remote dsh executable (default `dsh`).
367
+ * @param {string} [spec.profile] - DSH profile to boot (default `web`).
368
+ * @param {string} [spec.existingUrl] - attach to an ALREADY running remote
369
+ * web UI instead of starting one: its `http://127.0.0.1:<port>/?token=…`.
370
+ * @param {string} [spec.discoverCommand] - issue #125: run this on the remote
371
+ * FIRST; when it prints the URL of an already-running instance (and that
372
+ * instance answers a probe), attach to it instead of spawning. Every
373
+ * failure shape (no output, non-zero exit, timeout, dead instance) falls
374
+ * back to the normal launch, with `this.discovery` saying which happened.
375
+ * @param {(cmd: string, opts?: object) => Promise<{stdout: string, code: number}>} [spec.exec]
376
+ * - remote exec, defaulting to `pool.exec`.
377
+ * @returns {Promise<{url: string, localPort: number, remotePort: number}>}
378
+ */
379
+ async open(spec) {
380
+ const {
381
+ pool, machineId = '', command = 'dsh', profile = 'web',
382
+ existingUrl = '', dshHome = '', waitSeconds = 45,
383
+ discoverCommand = '',
384
+ } = spec || {}
385
+ if (!pool) throw new Error('web-attach: a machine pool is required')
386
+ this.machineId = String(machineId || '')
387
+ this.command = command
388
+ this.waitSeconds = Number(waitSeconds) || 45
389
+
390
+ const exec = spec.exec || ((cmd, opts) => pool.exec(cmd, opts))
391
+ // Connecting first also surfaces credential/host-key problems BEFORE we
392
+ // start a remote process we would then have to clean up. `_attach` (rather
393
+ // than a bare assignment) is what subscribes to the connection's 'close',
394
+ // so the loss is noticed the moment it happens instead of on the next
395
+ // request — which is when the old code let ssh2 throw 'Not connected' from
396
+ // inside a socket callback and take the host process with it (issue #54).
397
+ this._attach(await pool.connect())
398
+ this._followPool(pool)
399
+
400
+ if (existingUrl) {
401
+ const parsed = parseWebStart(`dsh web: ${existingUrl}`)
402
+ if (!parsed) {
403
+ throw new Error('web-attach: existing URL must look like http://127.0.0.1:<port>/?token=<token>')
404
+ }
405
+ this.remotePort = parsed.port
406
+ this.token = parsed.token
407
+ } else {
408
+ // Issue #125: with a discover command configured, ask the remote whether
409
+ // a resident instance already runs BEFORE spawning a twin that would
410
+ // share its DSH_HOME. A hit adopts the existing-instance posture
411
+ // (hands-off: no PID of ours, nothing to stop on close); every other
412
+ // outcome falls through to the normal launch.
413
+ if (String(discoverCommand || '').trim()) {
414
+ // pool.exec normally pipes commands through Git Bash on a Windows
415
+ // remote that has it. That is right for the plugin's POSIX scripts but
416
+ // wrong for a USER discover command, whose whole point is that it may
417
+ // be PowerShell. Use the pool's unwrapped exec for this one command.
418
+ const discoverExec = spec.exec || await this._loginShellExec(pool, exec)
419
+ await this._discoverFirst(discoverExec, String(discoverCommand).trim())
420
+ }
421
+ if (this.discovery !== 'hit') {
422
+ this.tag = randomTag()
423
+ const logPath = `${LOG_NAME}-${this.tag}.log`
424
+ this.logPath = logPath
425
+ const timeoutMs = Math.max(30000, (waitSeconds + 20) * 1000)
426
+ let out = String(await this._launch(exec, { command, profile, logPath, dshHome, waitSeconds, timeoutMs }, false))
427
+ // Older DSH (0.1.0-rc.6) has no `--no-open` and exits on the unknown flag
428
+ // before doing anything. Retry once without it: `--no-open` is a nicety
429
+ // (it stops the REMOTE from opening its own browser), not a requirement,
430
+ // and a bounded single retry is safe because the first attempt provably
431
+ // never started a server.
432
+ if (launchFailed(out) && /unknown option/i.test(out) && /--no-open/.test(out)) {
433
+ out = String(await this._launch(exec, { command, profile, logPath, dshHome, waitSeconds, timeoutMs }, true))
434
+ this.omittedNoOpen = true
435
+ }
436
+ this.remotePid = parseRemotePid(out)
437
+ const tail = out.split(TAIL_MARKER).slice(1).join(TAIL_MARKER).trim()
438
+ // Both failure shapes carry the same diagnostics: the process either died
439
+ // (its output is the whole story) or is still booting after the deadline.
440
+ if (launchFailed(out)) {
441
+ // The remote process is already gone — nothing to clean up.
442
+ throw new Error('web-attach: the remote DSH exited during startup.'
443
+ + explainLaunchFailure(tail || out)
444
+ + ` ${tail || 'no output'}`)
445
+ }
446
+ const parsed = parseWebStart(out)
447
+ if (!parsed) {
448
+ // A timed-out launch may STILL be booting: the deadline expiring is not
449
+ // evidence the process died. Kill it before throwing, or every retry
450
+ // leaks another remote server (measured: three leftover `dsh --port 0`
451
+ // processes after three failed attaches). A PID of 0 means the launcher
452
+ // could not report one — nothing to target.
453
+ if (this.remotePid > 0) {
454
+ try {
455
+ await execPosix(exec, buildStopCommand(this.remotePid, logPath), { timeoutMs: 20000 })
456
+ this.remotePid = 0
457
+ } catch { /* the process may already be gone; a leftover is worse than a failed kill attempt only if it repeats, and the next attach replaces this session */ }
458
+ }
459
+ throw new Error(
460
+ `web-attach: the remote DSH did not report a startup token within ${waitSeconds}s.`
461
+ + ` Check that \`${command}\` exists on the remote and can boot a web profile.`
462
+ + explainLaunchFailure(tail || out)
463
+ + (tail ? ` Remote output: ${tail}` : ''),
464
+ )
465
+ }
466
+ this.remotePort = parsed.port
467
+ this.token = parsed.token
468
+ }
469
+ }
470
+
471
+ await this._listen()
472
+ this.startedAt = Date.now()
473
+ return this.describe()
474
+ }
475
+
476
+ /**
477
+ * Run one launch attempt and return its raw output.
478
+ *
479
+ * @param {(cmd: string, opts?: object) => Promise<{stdout: string}>} exec - remote exec.
480
+ * @param {object} d - launch parameters plus the exec timeout.
481
+ * @param {boolean} omitNoOpen - drop `--no-open` for old DSH.
482
+ * @returns {Promise<string>} the launcher's stdout.
483
+ */
484
+ async _launch(exec, d, omitNoOpen) {
485
+ const cmd = buildLaunchCommand({ ...d, omitNoOpen })
486
+ const res = await execPosix(exec, cmd, { timeoutMs: d.timeoutMs })
487
+ return String(res && res.stdout ? res.stdout : '')
488
+ }
489
+
490
+ /**
491
+ * Resolve an exec that preserves the remote LOGIN shell for a user command.
492
+ *
493
+ * SshPool.exec transparently pipes every command to Git Bash when a Windows
494
+ * remote has it (so the plugin's own POSIX scripts work there). Discovery is
495
+ * different: the operator supplies the command specifically for that host's
496
+ * shell, e.g. `powershell -NoProfile …`. `_execRaw` is the pool's documented
497
+ * no-detection/no-wrapper path. A test-injected exec is left untouched.
498
+ *
499
+ * @param {object} pool - the selected machine's pool.
500
+ * @param {(cmd: string, opts?: object) => Promise<object>} fallback - pool.exec.
501
+ */
502
+ async _loginShellExec(pool, fallback) {
503
+ if (!pool || typeof pool.detect !== 'function' || typeof pool._execRaw !== 'function') return fallback
504
+ try { await pool.detect() } catch { return fallback }
505
+ if (pool.platform === 'windows' && pool.gitBashPath) {
506
+ return (cmd, opts) => pool._execRaw(cmd, opts)
507
+ }
508
+ return fallback
509
+ }
510
+
511
+ /**
512
+ * The issue #125 discovery step: adopt a resident instance when one answers,
513
+ * otherwise record WHY not and let open() fall back to launching.
514
+ *
515
+ * A printed URL is a CLAIM, not evidence — the instance may have died after
516
+ * the discover command's source learned the address (a stale URL file, a
517
+ * crashed-but-never-cleaned supervisor record). Attaching to that corpse
518
+ * would hand the user a dead tab, so the hit only stands when the address
519
+ * also answers a cheap HTTP probe; a failed probe demotes to
520
+ * 'probe-failed', which is a spawn outcome.
521
+ *
522
+ * @param {(cmd: string, opts?: object) => Promise<{stdout: string}>} exec
523
+ * @param {string} command - the user-supplied discover command.
524
+ */
525
+ async _discoverFirst(exec, command) {
526
+ const found = await this._discoverRunning(exec, command)
527
+ this.discovery = found.status
528
+ if (!found.parsed) return
529
+ if (await this._probeRemoteWeb(found.parsed.port)) {
530
+ this.remotePort = found.parsed.port
531
+ this.token = found.parsed.token
532
+ this.discovery = 'hit'
533
+ } else {
534
+ this.discovery = 'probe-failed'
535
+ }
536
+ }
537
+
538
+ /**
539
+ * Run the user-supplied discover command and classify what came back.
540
+ *
541
+ * The command goes through the pool's RAW exec — NOT {@link execPosix}: it is
542
+ * written for the remote's OWN shell (that is exactly what makes PowerShell
543
+ * one-liners on Windows remotes usable), with the same semantics as an
544
+ * rw_exec line. Three deliberate properties:
545
+ * • bounded — the exec carries a hard timeout (default 8s): discovery may
546
+ * delay a spawn by seconds, never hang it;
547
+ * • quiet — every failure shape resolves to a status string; nothing here
548
+ * throws, because "no resident instance" is a normal answer, not an
549
+ * exceptional one;
550
+ * • hygienic — the result NEVER carries stdout/stderr: a discovered URL
551
+ * bears a live login token, and this outcome travels onwards as the
552
+ * `discovery` diagnostic (responses, audit context). Only the parsed
553
+ * (port, token) facts survive.
554
+ *
555
+ * @returns {Promise<{status: 'hit'|'miss'|'timeout'|'error', parsed?: object, reason?: string}>}
556
+ */
557
+ async _discoverRunning(exec, command) {
558
+ let res
559
+ try {
560
+ res = await exec(command, { timeoutMs: this.discoverTimeoutMs })
561
+ } catch (err) {
562
+ return { status: 'error', reason: String((err && err.message) || err) }
563
+ }
564
+ // pool.exec RESOLVES deadlines and caller aborts (code -1 + signal name)
565
+ // instead of rejecting — both mean "no answer within the budget".
566
+ if (res && (res.signal === 'TIMEOUT' || res.signal === 'ABORTED')) return { status: 'timeout' }
567
+ const parsed = parseDiscoveredUrl(res && res.stdout)
568
+ if (parsed) return { status: 'hit', parsed }
569
+ // No URL printed. A non-zero exit here is usually a "nothing found" answer
570
+ // (pgrep/test/grep all exit 1 on absence) — a MISS. Only the shell's own
571
+ // "cannot run this" codes (126 not-executable / 127 not-found) say the
572
+ // command itself is broken, which the operator should see as an error
573
+ // rather than as "no resident instance".
574
+ const code = res && typeof res.code === 'number' ? res.code : 0
575
+ if (code === 126 || code === 127) return { status: 'error', reason: `the discover command itself failed (exit ${code})` }
576
+ return { status: 'miss' }
577
+ }
578
+
579
+ /**
580
+ * Speak one minimal HTTP request to the claimed remote port — through the
581
+ * SAME forwardOut path real traffic will use — and accept any HTTP status
582
+ * line as "alive": 200, a redirect, even a 401 all prove a listening server,
583
+ * while a refused, hung or non-HTTP socket proves none. The token is NOT
584
+ * sent: liveness does not need it, and keeping it out of the probe keeps it
585
+ * out of the remote server's request log.
586
+ *
587
+ * @param {number} port - the claimed remote loopback port.
588
+ * @returns {Promise<boolean>}
589
+ */
590
+ _probeRemoteWeb(port) {
591
+ return new Promise((resolve) => {
592
+ let settled = false
593
+ let channel = null
594
+ let timer = null
595
+ const finish = (ok) => {
596
+ if (settled) return
597
+ settled = true
598
+ clearTimeout(timer)
599
+ if (channel) {
600
+ try { if (typeof channel.close === 'function') channel.close() } catch { /* already gone */ }
601
+ try { if (typeof channel.destroy === 'function') channel.destroy() } catch { /* already gone */ }
602
+ }
603
+ resolve(ok)
604
+ }
605
+ timer = setTimeout(() => finish(false), this.probeTimeoutMs)
606
+ const client = this.client
607
+ if (!client || typeof client.forwardOut !== 'function') return finish(false)
608
+ try {
609
+ // ssh2 throws SYNCHRONOUSLY on a dead connection instead of calling
610
+ // back (see _pipe), so this call itself sits inside the try.
611
+ client.forwardOut('127.0.0.1', 0, '127.0.0.1', port, (err, ch) => {
612
+ if (err || !ch) return finish(false)
613
+ channel = ch
614
+ ch.on('error', () => finish(false))
615
+ // A close before any answer means the server spoke nothing HTTP.
616
+ ch.on('close', () => finish(false))
617
+ ch.on('data', (buf) => finish(/^HTTP\/1\.[01] \d{3}/.test(String(buf))))
618
+ try {
619
+ ch.write(`GET / HTTP/1.0\r\nHost: 127.0.0.1:${port}\r\nUser-Agent: dsh-remote-discover\r\n\r\n`)
620
+ } catch { finish(false) }
621
+ })
622
+ } catch { finish(false) }
623
+ })
624
+ }
625
+
626
+ /** Bind the local listener, advancing past ports already in use. */
627
+ async _listen() {
628
+ let lastError = null
629
+ for (let i = 0; i < this.localPortMax; i++) {
630
+ const port = this.localPortStart + i
631
+ try {
632
+ await this._listenOn(port)
633
+ this.localPort = port
634
+ return
635
+ } catch (err) {
636
+ lastError = err
637
+ // Only a taken port is worth retrying; anything else (permissions,
638
+ // an unusable interface) will not be fixed by the next number.
639
+ if (err && err.code !== 'EADDRINUSE') break
640
+ }
641
+ }
642
+ throw new Error(
643
+ `web-attach: no free local port in ${this.localPortStart}..${this.localPortStart + this.localPortMax - 1}`
644
+ + (lastError ? ` (${lastError.code || lastError.message})` : ''),
645
+ )
646
+ }
647
+
648
+ _listenOn(port) {
649
+ return new Promise((resolve, reject) => {
650
+ const server = this.net.createServer((socket) => this._pipe(socket))
651
+ const onError = (err) => {
652
+ server.removeListener('listening', onListening)
653
+ try { server.close() } catch { /* never listened */ }
654
+ reject(err)
655
+ }
656
+ const onListening = () => {
657
+ server.removeListener('error', onError)
658
+ // A post-bind error must not crash the host process: report and drop
659
+ // the tunnel so the UI can show "disconnected" instead of dying.
660
+ server.on('error', (err) => {
661
+ this.server = null
662
+ this.lastError = String((err && err.message) || err)
663
+ })
664
+ this.server = server
665
+ resolve()
666
+ }
667
+ server.once('error', onError)
668
+ server.once('listening', onListening)
669
+ // Loopback only: this endpoint reaches a full remote harness, so it must
670
+ // never be reachable from the network even on a LAN-facing machine.
671
+ server.listen(port, '127.0.0.1')
672
+ })
673
+ }
674
+
675
+ /**
676
+ * Borrow the given connection AND subscribe to its lifecycle.
677
+ *
678
+ * Idempotent for the same client (open() calls it once, the pool's `onReady`
679
+ * calls it again on every reconnect), and it always drops the previous
680
+ * client's listener first, so one session never accumulates listeners.
681
+ *
682
+ * @param {object|null} client - the live ssh2 client / OpenSshConnection.
683
+ */
684
+ _attach(client) {
685
+ if (!client) return
686
+ if (this.attachedClient && this.attachedClient !== client && this.onClientClose) {
687
+ // A different client replaced the one we borrowed (pool reconnect). Stop
688
+ // listening to the old one; its own 'close' has either fired already or
689
+ // belongs to a connection nobody uses any more.
690
+ try { this.attachedClient.removeListener('close', this.onClientClose) } catch { /* already gone */ }
691
+ }
692
+ this.client = client
693
+ if (this.attachedClient === client) return
694
+ this.attachedClient = client
695
+ this.onClientClose = () => { this._clientLost('ssh connection closed') }
696
+ // Without this, the object keeps handing out a connection that is already
697
+ // closed, and `forwardOut` then throws SYNCHRONOUSLY (issue #54).
698
+ try { client.on('close', this.onClientClose) } catch { /* not an emitter: nothing to watch */ }
699
+ }
700
+
701
+ /** The borrowed connection is gone: keep the session, drop the dead handle. */
702
+ _clientLost(reason) {
703
+ this.client = null
704
+ this.connectionLost = true
705
+ this.lastError = String(reason || 'ssh connection closed')
706
+ }
707
+
708
+ /**
709
+ * Register lifecycle hooks on the chosen pool so this tunnel follows it.
710
+ *
711
+ * The pool is the one place that both NOTICES a dead connection and later
712
+ * obtains a fresh one, and it exposes exactly two hooks for that:
713
+ * • `onCloseHook` — fires from `close()` and `invalidate()` (the latter is
714
+ * the "channel open failed, the pooled connection died server-side"
715
+ * self-heal path, which is the likeliest trigger);
716
+ * • `onReady` — fires after a successful (re)connect.
717
+ *
718
+ * Both are SINGLE-SLOT properties that the plugin already uses for
719
+ * `ForwardManager` (index.js), so this session CHAINS them rather than
720
+ * clobbering the forwards manager, and `_detachPool()` restores exactly what
721
+ * was there — the plugin may legitimately have none, one, or both.
722
+ *
723
+ * A real reconnect is the only way the remote port can move, so once the pool
724
+ * reports a new connection we must re-resolve (token, port) from the remote
725
+ * log. `onReady` itself cannot await: the pool fires it with the client in
726
+ * hand, so the re-resolve is kicked off and its failure is recorded rather
727
+ * than thrown into the pool's callback.
728
+ *
729
+ * @param {object} pool - the pool this session attached through.
730
+ */
731
+ _followPool(pool) {
732
+ if (!this.trackPool || this.closed || !pool || this.hookedPool === pool) return
733
+ this._detachPool()
734
+ this.pool = pool
735
+ this.hookedPool = pool
736
+ const prevReady = typeof pool.onReady === 'function' ? pool.onReady : null
737
+ const prevClose = typeof pool.onCloseHook === 'function' ? pool.onCloseHook : null
738
+ this.prevOnReady = prevReady
739
+ this.prevOnCloseHook = prevClose
740
+ const installedReady = (client) => {
741
+ this._attach(client)
742
+ if (prevReady) { try { prevReady(client) } catch { /* the forwards manager's problem, not ours */ } }
743
+ // A reconnect lands on a NEW remote process only if the old one died with
744
+ // the machine; re-read the log to find out which. The re-resolve runs off
745
+ // the event loop because the pool cannot await it — a hook that throws
746
+ // would earn an 'error' event on the pool, and an unhandled rejection
747
+ // would be fatal.
748
+ if (!this.closed && this.remotePort && !this._resolving) {
749
+ this._resolving = true
750
+ Promise.resolve()
751
+ .then(() => this._refreshRemotePort())
752
+ .catch((err) => { this.lastError = String((err && err.message) || err) })
753
+ .then(() => { this._resolving = false })
754
+ }
755
+ }
756
+ const installedClose = () => {
757
+ this._clientLost('ssh connection closed')
758
+ if (prevClose) { try { prevClose() } catch { /* never mask our own report */ } }
759
+ }
760
+ this._installedOnReady = installedReady
761
+ this._installedOnClose = installedClose
762
+ pool.onReady = installedReady
763
+ pool.onCloseHook = installedClose
764
+ }
765
+
766
+ /**
767
+ * Hand the pool's hooks back.
768
+ *
769
+ * Each slot is restored ONLY when it still holds the wrapper this session
770
+ * installed. The pool's hooks are single-slot, so if something else has taken
771
+ * the slot over in the meantime, putting a stale callback back would be worse
772
+ * than leaving it alone — it would silently disconnect a newer owner.
773
+ */
774
+ _detachPool() {
775
+ const pool = this.hookedPool
776
+ const mineReady = this._installedOnReady
777
+ const mineClose = this._installedOnClose
778
+ this.hookedPool = null
779
+ this._installedOnReady = null
780
+ this._installedOnClose = null
781
+ if (!pool) return
782
+ if (mineReady && pool.onReady === mineReady) pool.onReady = this.prevOnReady
783
+ if (mineClose && pool.onCloseHook === mineClose) pool.onCloseHook = this.prevOnCloseHook
784
+ this.prevOnReady = null
785
+ this.prevOnCloseHook = null
786
+ }
787
+
788
+ /**
789
+ * True when the borrowed connection was LOST and this is a session we can
790
+ * recover: we launched the remote process ourselves (so we hold its PID and
791
+ * log) and the tunnel is listening (so clients can actually be served).
792
+ *
793
+ * The `connectionLost` flag is deliberately separate from `this.client`: the
794
+ * pool's `onReady` re-attaches the new client BEFORE the re-resolve runs, so a
795
+ * check on `!this.client` would be false by then and recovery would never
796
+ * happen.
797
+ */
798
+ get _needsReResolve() {
799
+ return !!(this.connectionLost && !this.closed && this.logPath && this.remotePid && this.localPort)
800
+ }
801
+
802
+ /**
803
+ * Re-resolve the remote port after a reconnect, restarting the remote `dsh web`
804
+ * when it did not survive.
805
+ *
806
+ * Reaching a remote process needs a live SSH connection, so this reconnects
807
+ * through the pool first — the pool reports `onReady` for that same client in
808
+ * production, and in a test double the callback simply never fires.
809
+ */
810
+ async _refreshRemotePort() {
811
+ if (!this._needsReResolve) return
812
+ const pool = this.pool
813
+ if (!pool || (typeof pool.connect !== 'function' && typeof pool.exec !== 'function')) return
814
+ const exec = (cmd, opts) => (typeof pool.exec === 'function'
815
+ ? pool.exec(cmd, opts)
816
+ : Promise.reject(new Error('web-attach: the pool cannot run commands')))
817
+ if (!this.client) await pool.connect()
818
+ const match = await this._resolveRemotePort(exec)
819
+ this.remotePort = match.port
820
+ if (match.token) this.token = match.token
821
+ this.connectionLost = false
822
+ this.lastError = ''
823
+ }
824
+
825
+ /**
826
+ * Read this session's remote log and decide which port is live.
827
+ *
828
+ * The startup line is the ONLY source of the port (the launch deliberately
829
+ * uses `--port 0`), so after the remote process died and was restarted the log
830
+ * holds BOTH lines — the dead one and the new one — and neither position
831
+ * identifies the live one. Evidence decides:
832
+ * • a process that is still alive on the remote is probed first, and when
833
+ * the port it is LISTENING on is one of the logged ports, that is the
834
+ * answer (the `dsh web: …` line names its own port, so this is a
835
+ * confirmation rather than a second guess);
836
+ * • otherwise the newest logged port wins, which is right in every
837
+ * single-process case and is the best available answer while the remote is
838
+ * still booting (the next reconnect retries).
839
+ *
840
+ * @param {(cmd: string, opts?: object) => Promise<{stdout: string}>} exec - remote exec.
841
+ * @returns {Promise<{port: number, token: string, restarted: boolean}>}
842
+ */
843
+ async _resolveRemotePort(exec) {
844
+ this._remoteAlive = await this._remoteProcessAlive(exec)
845
+ if (!this._remoteAlive) return this._restartRemote(exec)
846
+
847
+ let out = ''
848
+ try {
849
+ const res = await execPosix(exec, `cat "$HOME/${this.logPath}" 2>/dev/null`, { timeoutMs: 15000 })
850
+ out = String((res && res.stdout) || '')
851
+ } catch { /* an unreadable log: the listening probe below is the fallback */ }
852
+ const lines = [...out.matchAll(/dsh web:\s*(http:\/\/[^\s]+)/g)]
853
+ .map((m) => parseWebStart(`dsh web: ${m[1]}`))
854
+ .filter(Boolean)
855
+
856
+ // What the recorded process actually listens on beats any guess from the
857
+ // log, because a killed-and-restarted remote leaves BOTH startup lines in
858
+ // the log and neither position says which one is live.
859
+ const listening = await this._listeningRemotePort(exec)
860
+ if (listening) {
861
+ const match = lines.find((l) => l.port === listening)
862
+ return { port: listening, token: (match && match.token) || this.token, restarted: false }
863
+ }
864
+ if (lines.length) {
865
+ const newest = lines[lines.length - 1]
866
+ return { port: newest.port, token: newest.token, restarted: false }
867
+ }
868
+ // Alive but silent and not listening yet: the remote is booting. Keep the
869
+ // last known port and let the next reconnect re-resolve.
870
+ return { port: this.remotePort, token: this.token, restarted: false }
871
+ }
872
+
873
+ /**
874
+ * Whether the remote process THIS session started still exists.
875
+ *
876
+ * Verified through `/proc`, which is Linux-only; a host that cannot answer (or
877
+ * a failed probe) is treated as ALIVE on purpose. Restarting a server that was
878
+ * never dead would spawn a second one and leak a port, whereas assuming life
879
+ * merely retries a port that turns out to be stale.
880
+ *
881
+ * @param {(cmd: string, opts?: object) => Promise<{stdout: string}>} exec - remote exec.
882
+ * @returns {Promise<boolean>}
883
+ */
884
+ async _remoteProcessAlive(exec) {
885
+ const pid = Number(this.remotePid) || 0
886
+ if (pid < 1) return true
887
+ try {
888
+ const res = await execPosix(
889
+ exec,
890
+ `if [ -d /proc ]; then { [ -d /proc/${pid} ] && echo ALIVE; } || echo GONE; else echo ALIVE; fi`,
891
+ { timeoutMs: 15000 },
892
+ )
893
+ return !/GONE/.test(String((res && res.stdout) || ''))
894
+ } catch { return true }
895
+ }
896
+
897
+ /**
898
+ * Ask the remote which loopback port the recorded PID listens on (0 = none).
899
+ *
900
+ * Two `/proc` reads are needed because a TCP listener appears in a socket
901
+ * table (`/proc/net/tcp{,6}`), not in that process's link list: the fd
902
+ * symlinks give the socket INODE, and the table maps that inode to a port.
903
+ * Matching on the inode rather than the port is what makes this an
904
+ * observation instead of a second guess.
905
+ */
906
+ async _listeningRemotePort(exec) {
907
+ const pid = Number(this.remotePid) || 0
908
+ if (pid < 1) return 0
909
+ let inodes = ''
910
+ try {
911
+ // `ls -l` on a process's own fds needs no privileges for the same uid.
912
+ const res = await execPosix(
913
+ exec,
914
+ `ls -l /proc/${pid}/fd 2>/dev/null | sed -n 's/.*socket:\\[\\([0-9]*\\)\\].*/\\1/p' | sort -u | tr '\\n' ' '`,
915
+ { timeoutMs: 15000 },
916
+ )
917
+ inodes = String((res && res.stdout) || '').trim()
918
+ } catch { return 0 }
919
+ if (!inodes) return 0
920
+ const want = new Set(inodes.split(/\s+/).filter(Boolean))
921
+ // `/proc/net/tcp` addresses are little-endian hex, so loopback is
922
+ // `0100007F` (v4) and `00000000000000000000000001000000` (v6 `::1`).
923
+ const LOOPBACK = new Set(['0100007F', '00000000000000000000000001000000'])
924
+ for (const file of ['/proc/net/tcp', '/proc/net/tcp6']) {
925
+ let text = ''
926
+ try {
927
+ const res = await execPosix(exec, `cat ${file} 2>/dev/null`, { timeoutMs: 15000 })
928
+ text = String((res && res.stdout) || '')
929
+ } catch { continue }
930
+ for (const line of text.split('\n').slice(1)) {
931
+ const cols = line.trim().split(/\s+/)
932
+ // sl local_address rem_address st tx:rx tr:tm->when retrnsmt uid timeout inode
933
+ if (cols.length < 10) continue
934
+ if (cols[3] !== '0A') continue // TCP_LISTEN
935
+ if (!want.has(cols[9])) continue
936
+ const [addr, portHex] = String(cols[1]).split(':')
937
+ if (!LOOPBACK.has(String(addr).toUpperCase())) continue
938
+ const port = parseInt(portHex, 16)
939
+ if (Number.isInteger(port) && port > 0 && port < 65536) return port
940
+ }
941
+ }
942
+ return 0
943
+ }
944
+
945
+ /**
946
+ * Relaunch the remote `dsh web` because the previous process is gone.
947
+ *
948
+ * A restart CANNOT change the listening port locally, and a caller holding a
949
+ * stale port silently talks to the wrong place at worst and hangs at best, so
950
+ * the two facts the caller needs are checked: this is a session that launched
951
+ * its own process (an attach onto someone else's DSH stays hands-off and can
952
+ * never restart it), and recovery is possible at all (`_refreshRemotePort`
953
+ * has already returned early when it is not).
954
+ */
955
+ async _restartRemote(exec) {
956
+ const command = this.command || 'dsh'
957
+ const waitSeconds = this.waitSeconds || 45
958
+ const timeoutMs = Math.max(30000, (waitSeconds + 20) * 1000)
959
+ let out = String(await this._launch(exec, { command, profile: 'web', logPath: this.logPath, waitSeconds, timeoutMs }, this.omittedNoOpen === true))
960
+ if (launchFailed(out) && /unknown option/i.test(out) && /--no-open/.test(out)) {
961
+ out = String(await this._launch(exec, { command, profile: 'web', logPath: this.logPath, waitSeconds, timeoutMs }, true))
962
+ this.omittedNoOpen = true
963
+ }
964
+ this.remotePid = parseRemotePid(out) || this.remotePid
965
+ const parsed = parseWebStart(out)
966
+ if (!parsed) {
967
+ const tail = out.split(TAIL_MARKER).slice(1).join(TAIL_MARKER).trim()
968
+ throw new Error('web-attach: the remote DSH could not be restarted after the SSH'
969
+ + ' connection dropped.' + explainLaunchFailure(tail || out) + (tail ? ` Remote output: ${tail}` : ''))
970
+ }
971
+ return { port: parsed.port, token: parsed.token, restarted: true }
972
+ }
973
+
974
+ /** Carry one local socket to the remote web port over SSH. */
975
+ _pipe(socket) {
976
+ if (!this.client) { try { socket.destroy() } catch { /* already gone */ } return }
977
+ // ssh2's forwardOut does NOT report a dead connection through its callback:
978
+ // when the socket is gone it THROWS 'Not connected' synchronously
979
+ // (ssh2/lib/client.js: `if (!this._sock || !isWritable(this._sock)) throw`)
980
+ // and the callback below is never reached — so `if (err)` cannot guard this
981
+ // path. Uncaught, that throw travels net.Server → TCP.onconnection and kills
982
+ // the whole host process (issue #54: every page refresh after the pooled
983
+ // connection dropped took the session, the browser and the remote orphan
984
+ // down with it). A dead tunnel is a UI state, not a reason to exit.
985
+ try {
986
+ this.client.forwardOut('127.0.0.1', 0, '127.0.0.1', this.remotePort, (err, channel) => {
987
+ if (err) { try { socket.destroy() } catch { /* already gone */ } return }
988
+ this.sockets.add(socket)
989
+ socket.pipe(channel)
990
+ channel.pipe(socket)
991
+ const kill = () => {
992
+ try { socket.destroy() } catch { /* already gone */ }
993
+ try { channel.close() } catch { /* already closed */ }
994
+ this.sockets.delete(socket)
995
+ }
996
+ socket.on('error', kill)
997
+ channel.on('error', kill)
998
+ socket.on('close', kill)
999
+ channel.on('close', kill)
1000
+ })
1001
+ } catch (err) {
1002
+ this._clientLost(String((err && err.message) || err))
1003
+ try { socket.destroy() } catch { /* already gone */ }
1004
+ }
1005
+ }
1006
+
1007
+ /**
1008
+ * The URL to open, carrying the one-time launch token.
1009
+ *
1010
+ * The token is a credential, so it stays on loopback and is never sent
1011
+ * anywhere; DSH exchanges it for a 30-day signed cookie on the first request
1012
+ * and redirects to a clean `/`.
1013
+ */
1014
+ get url() {
1015
+ return `http://127.0.0.1:${this.localPort}/?token=${this.token}`
1016
+ }
1017
+
1018
+ /** The clean URL (no token) — what the address bar shows after the exchange. */
1019
+ get cleanUrl() {
1020
+ return `http://127.0.0.1:${this.localPort}/`
1021
+ }
1022
+
1023
+ /** Serializable status for the settings UI. */
1024
+ describe() {
1025
+ return {
1026
+ machineId: this.machineId,
1027
+ url: this.url,
1028
+ cleanUrl: this.cleanUrl,
1029
+ token: this.token,
1030
+ localPort: this.localPort,
1031
+ remotePort: this.remotePort,
1032
+ active: this.active,
1033
+ startedAt: this.startedAt,
1034
+ // Only a process we launched can be stopped by us; an attach onto the
1035
+ // user's own running instance is deliberately hands-off.
1036
+ managed: this.remotePid > 0,
1037
+ // Issue #125: '' = discovery not attempted; otherwise the outcome the
1038
+ // UI relays ("未发现常驻实例,已新起一个" / "复用了常驻实例").
1039
+ discovery: this.discovery || '',
1040
+ error: this.lastError || '',
1041
+ }
1042
+ }
1043
+
1044
+ /**
1045
+ * Tear the tunnel down. The remote process is left running by default: the
1046
+ * user may be using that DSH elsewhere, and silently killing a process we did
1047
+ * not start is worse than a leftover one. `stopRemote` opts in.
1048
+ *
1049
+ * @param {object} [opts] - close options.
1050
+ * @param {boolean} [opts.stopRemote] - also terminate the remote process.
1051
+ * @param {(cmd: string) => Promise<unknown>} [opts.exec] - remote exec.
1052
+ */
1053
+ async close({ stopRemote = false, exec } = {}) {
1054
+ // Stop following the pool BEFORE any await: a reconnect landing mid-teardown
1055
+ // must not re-arm the tunnel this call is in the middle of closing.
1056
+ this._detachPool()
1057
+ if (this.attachedClient && this.onClientClose) {
1058
+ try { this.attachedClient.removeListener('close', this.onClientClose) } catch { /* already gone */ }
1059
+ }
1060
+ this.attachedClient = null
1061
+ this.onClientClose = null
1062
+ this.pool = null
1063
+ for (const socket of [...this.sockets]) {
1064
+ try { socket.destroy() } catch { /* already gone */ }
1065
+ }
1066
+ this.sockets.clear()
1067
+ const server = this.server
1068
+ this.server = null
1069
+ if (server) await new Promise((resolve) => server.close(() => resolve()))
1070
+ // Only a process we started has a recorded PID; an attach to the user's own
1071
+ // running instance must never signal anything.
1072
+ if (stopRemote && exec && this.remotePid) {
1073
+ await Promise.resolve(execPosix(exec, buildStopCommand(this.remotePid, this.logPath))).catch(() => {})
1074
+ }
1075
+ this.client = null
1076
+ // The recorded PID and log path are FACTS about this session (the UI shows
1077
+ // them, and `stopRemote` addresses them), so they survive; `closed` is what
1078
+ // stops recovery work from being re-armed after teardown.
1079
+ this.closed = true
1080
+ }
1081
+ }