dsh-remote 0.8.91 → 0.8.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +369 -368
  3. package/README.md +354 -353
  4. package/cordis.patch.yml +9 -9
  5. package/lib/audit.js +45 -45
  6. package/lib/binding.js +172 -172
  7. package/lib/client.js +4647 -4550
  8. package/lib/credential.js +270 -263
  9. package/lib/errors.js +141 -141
  10. package/lib/exec-job.js +242 -242
  11. package/lib/file-reference.js +457 -457
  12. package/lib/forwards.js +258 -258
  13. package/lib/host-api.js +822 -822
  14. package/lib/hostkey.js +108 -108
  15. package/lib/http-transport.js +201 -201
  16. package/lib/ignore.js +202 -202
  17. package/lib/index.js +4488 -4394
  18. package/lib/instructions-dynamic.js +415 -415
  19. package/lib/instructions.js +288 -288
  20. package/lib/open-folder.js +56 -56
  21. package/lib/openssh.js +940 -881
  22. package/lib/paths.js +292 -292
  23. package/lib/pool.js +1029 -970
  24. package/lib/posix-shell.cjs +34 -0
  25. package/lib/registry.js +296 -296
  26. package/lib/remote-fs.js +173 -173
  27. package/lib/remote-sandbox.js +183 -183
  28. package/lib/remote-shell-child.cjs +397 -400
  29. package/lib/remote-shell.js +697 -697
  30. package/lib/remote-skills.js +312 -0
  31. package/lib/routes-audit.js +58 -58
  32. package/lib/routes-forwards.js +72 -72
  33. package/lib/routes-fs.js +251 -245
  34. package/lib/routes-machines.js +186 -186
  35. package/lib/routes-misc.js +187 -150
  36. package/lib/routes-term.js +169 -169
  37. package/lib/routes-update.js +143 -143
  38. package/lib/routes-web-attach.js +112 -112
  39. package/lib/routes-workspace.js +312 -312
  40. package/lib/search.js +235 -235
  41. package/lib/sftp-surface.js +119 -119
  42. package/lib/sshconfig.js +779 -779
  43. package/lib/sync.js +350 -350
  44. package/lib/tasks.js +95 -95
  45. package/lib/telemetry.js +247 -247
  46. package/lib/terminal.js +205 -205
  47. package/lib/tui/flow.js +130 -130
  48. package/lib/tui/format.js +380 -380
  49. package/lib/tui/i18n.js +350 -350
  50. package/lib/tui/index.js +531 -531
  51. package/lib/tui/provider.js +344 -344
  52. package/lib/tui/scene.js +986 -986
  53. package/lib/update.js +490 -472
  54. package/lib/web-attach.js +860 -850
  55. package/lib/workspace-cleanup.js +337 -337
  56. package/package.json +103 -100
  57. package/node_modules/buildcheck/.eslintrc.js +0 -5
  58. package/node_modules/buildcheck/.github/workflows/ci.yml +0 -88
  59. package/node_modules/buildcheck/.github/workflows/lint.yml +0 -27
  60. package/node_modules/buildcheck/.npmignore +0 -3
  61. package/node_modules/buildcheck/LICENSE +0 -19
  62. package/node_modules/buildcheck/README.md +0 -106
  63. package/node_modules/buildcheck/deps/Find-VisualStudio.cs +0 -250
  64. package/node_modules/buildcheck/lib/findvs.js +0 -361
  65. package/node_modules/buildcheck/lib/index.js +0 -738
  66. package/node_modules/buildcheck/package.json +0 -36
  67. package/node_modules/buildcheck/test/test.js +0 -8
  68. package/node_modules/cpu-features/.eslintrc.js +0 -5
  69. package/node_modules/cpu-features/.github/workflows/ci.yml +0 -74
  70. package/node_modules/cpu-features/.github/workflows/lint.yml +0 -27
  71. package/node_modules/cpu-features/LICENSE +0 -19
  72. package/node_modules/cpu-features/README.md +0 -59
  73. package/node_modules/cpu-features/binding.gyp +0 -16
  74. package/node_modules/cpu-features/buildcheck.js +0 -32
  75. package/node_modules/cpu-features/deps/cpu_features/.clang-format +0 -4
  76. package/node_modules/cpu-features/deps/cpu_features/.dockerignore +0 -31
  77. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile +0 -5
  78. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/aarch64_linux_cmake.yml +0 -30
  79. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_freebsd_cmake.yml +0 -22
  80. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_bazel.yml +0 -26
  81. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_cmake.yml +0 -31
  82. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_macos_cmake.yml +0 -43
  83. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_windows_cmake.yml +0 -25
  84. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/arm_linux_cmake.yml +0 -31
  85. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml +0 -24
  86. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/mips_linux_cmake.yml +0 -30
  87. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/power_linux_cmake.yml +0 -29
  88. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/riscv_linux_cmake.yml +0 -28
  89. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/s390x_linux_cmake.yml +0 -27
  90. package/node_modules/cpu-features/deps/cpu_features/.grenrc.yml +0 -21
  91. package/node_modules/cpu-features/deps/cpu_features/BUILD.bazel +0 -329
  92. package/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt +0 -261
  93. package/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md +0 -23
  94. package/node_modules/cpu-features/deps/cpu_features/LICENSE +0 -230
  95. package/node_modules/cpu-features/deps/cpu_features/README.md +0 -272
  96. package/node_modules/cpu-features/deps/cpu_features/WORKSPACE +0 -19
  97. package/node_modules/cpu-features/deps/cpu_features/bazel/ci/README.md +0 -5
  98. package/node_modules/cpu-features/deps/cpu_features/bazel/platforms.bzl +0 -11
  99. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in +0 -3
  100. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in +0 -3
  101. package/node_modules/cpu-features/deps/cpu_features/cmake/README.md +0 -30
  102. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/Makefile +0 -252
  103. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/README.md +0 -40
  104. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.dot +0 -64
  105. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.svg +0 -312
  106. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/generate_image.sh +0 -7
  107. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/amd64/Dockerfile +0 -48
  108. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/toolchain/Dockerfile +0 -34
  109. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/CMakeLists.txt +0 -22
  110. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/main.cpp +0 -11
  111. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/vagrant/freebsd/Vagrantfile +0 -107
  112. package/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in +0 -15
  113. package/node_modules/cpu-features/deps/cpu_features/cpu_features.gyp +0 -105
  114. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h +0 -54
  115. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h +0 -384
  116. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h +0 -259
  117. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h +0 -121
  118. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h +0 -74
  119. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h +0 -149
  120. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_riscv.h +0 -72
  121. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_s390x.h +0 -108
  122. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h +0 -288
  123. package/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h +0 -40
  124. package/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h +0 -37
  125. package/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h +0 -39
  126. package/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h +0 -240
  127. package/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h +0 -49
  128. package/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h +0 -110
  129. package/node_modules/cpu-features/deps/cpu_features/include/internal/windows_utils.h +0 -70
  130. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt +0 -60
  131. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md +0 -4
  132. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c +0 -205
  133. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h +0 -320
  134. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c +0 -12
  135. package/node_modules/cpu-features/deps/cpu_features/patches/0001-Add-Apple-Silicon-Support.patch +0 -456
  136. package/node_modules/cpu-features/deps/cpu_features/scripts/generate_badges.d +0 -165
  137. package/node_modules/cpu-features/deps/cpu_features/scripts/make_release.sh +0 -75
  138. package/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh +0 -490
  139. package/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh +0 -79
  140. package/node_modules/cpu-features/deps/cpu_features/src/copy.inl +0 -19
  141. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection.inl +0 -86
  142. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection_and_hwcaps.inl +0 -26
  143. package/node_modules/cpu-features/deps/cpu_features/src/equals.inl +0 -22
  144. package/node_modules/cpu-features/deps/cpu_features/src/filesystem.c +0 -62
  145. package/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c +0 -169
  146. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64__base_implementation.inl +0 -88
  147. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_linux_or_android.c +0 -79
  148. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_macos_or_iphone.c +0 -82
  149. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_windows.c +0 -138
  150. package/node_modules/cpu-features/deps/cpu_features/src/impl_arm_linux_or_android.c +0 -212
  151. package/node_modules/cpu-features/deps/cpu_features/src/impl_mips_linux_or_android.c +0 -93
  152. package/node_modules/cpu-features/deps/cpu_features/src/impl_ppc_linux.c +0 -163
  153. package/node_modules/cpu-features/deps/cpu_features/src/impl_riscv_linux.c +0 -111
  154. package/node_modules/cpu-features/deps/cpu_features/src/impl_s390x_linux.c +0 -120
  155. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86__base_implementation.inl +0 -2055
  156. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_freebsd.c +0 -68
  157. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_linux_or_android.c +0 -58
  158. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_macos.c +0 -57
  159. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_windows.c +0 -58
  160. package/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c +0 -132
  161. package/node_modules/cpu-features/deps/cpu_features/src/string_view.c +0 -192
  162. package/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c +0 -461
  163. package/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt +0 -114
  164. package/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc +0 -53
  165. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc +0 -396
  166. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc +0 -384
  167. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc +0 -176
  168. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc +0 -131
  169. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_riscv_test.cc +0 -180
  170. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_s390x_test.cc +0 -82
  171. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc +0 -1729
  172. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc +0 -103
  173. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h +0 -61
  174. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc +0 -52
  175. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h +0 -31
  176. package/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc +0 -132
  177. package/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc +0 -202
  178. package/node_modules/cpu-features/lib/index.js +0 -5
  179. package/node_modules/cpu-features/package.json +0 -40
  180. package/node_modules/cpu-features/src/binding.cc +0 -151
  181. package/node_modules/cpu-features/test/test.js +0 -12
@@ -1,697 +1,697 @@
1
- /**
2
- * Remote terminal as a shell choice — the host terminal's own option list.
3
- *
4
- * The built-in terminal is a *local* pty whose program comes from
5
- * `dsh-api-terminal-controller`'s verified shell list (`shellCandidates`). A
6
- * plugin cannot hand that pty a command line, but it CAN contribute one entry
7
- * to that list: an absolute path to a launcher we generate. The pty then runs
8
- * our launcher as a local process, and the launcher execs `ssh` with inherited
9
- * stdio — which is exactly how the terminal should behave. Resizing, key
10
- * binding, scrollback and color all stay the host's job; nothing is re-implemented
11
- * here.
12
- *
13
- * The launcher itself is dumb (find node, run the child script). The child
14
- * (`remote-shell-child.cjs`) resolves the remote target from the checkout it is
15
- * started in and replaces itself with `ssh`.
16
- *
17
- * @module dsh-remote/remote-shell
18
- */
19
-
20
- import { chmodSync, existsSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'
21
- import path from 'node:path'
22
-
23
- /** Label shown in the terminal's shell menu.
24
- *
25
- * Windows needs a real `.cmd` on disk (ConPTY cannot start an extensionless
26
- * file), but the label does not have to advertise it: the menu shows the
27
- * candidate's basename, and `shellCandidate` contributes the bare name so the
28
- * host resolves it through `PATH` + `PATHEXT`. The suffix is therefore an
29
- * implementation detail of the file on disk, not of the menu entry. */
30
- export const SHELL_OPTION_NAME = 'remote ssh'
31
-
32
- /** Absolute path of the generated launcher for this platform. */
33
- export function shellLauncherPath(dir, platform = process.platform) {
34
- return path.join(dir, platform === 'win32' ? SHELL_OPTION_NAME + '.cmd' : SHELL_OPTION_NAME)
35
- }
36
-
37
- /** Default `PATHEXT`, used when the environment does not carry one. */
38
- const DEFAULT_PATH_EXT = '.COM;.EXE;.BAT;.CMD'
39
-
40
- /**
41
- * The value to contribute to `shellCandidates`.
42
- *
43
- * The menu label is `executableName(candidate)` — the candidate's basename, with
44
- * no extension stripped — while the path that actually runs is whatever the host
45
- * resolves. Those are two different things, and the gap is the only way to get a
46
- * clean label on Windows.
47
- *
48
- * A file path would be shown as `remote ssh.cmd`, because the terminal has to
49
- * start a real `.cmd` and ConPTY refuses anything else (a file with no extension
50
- * dies with 193, `ERROR_BAD_EXE_FORMAT`). So on Windows the *bare* name is
51
- * contributed instead: the host resolves it through `PATH` + `PATHEXT`, lands on
52
- * `remote ssh.cmd`, and the label stays `remote ssh`. That is exactly the rule
53
- * `resolveExecutable` documents — an absolute path is checked as-is with no
54
- * extension guessing, a bare name is looked up per `PATHEXT`.
55
- *
56
- * Two consequences, both handled by the caller: the launcher's directory has to
57
- * be on `PATH` (see `appendPathEntry`), and the name must contain no dot, since
58
- * a bare name is only extended when `extname()` is empty.
59
- *
60
- * POSIX has no such rule — the file is directly executable — so the absolute
61
- * path is contributed as-is.
62
- *
63
- * @param {string} platform
64
- * @param {string} launcherPath
65
- * @returns {string} candidate value for the shell list
66
- */
67
- export function shellCandidate(platform, launcherPath) {
68
- if (platform !== 'win32') return launcherPath
69
- return path.basename(launcherPath).replace(/\.cmd$/i, '')
70
- }
71
-
72
- /**
73
- * Resolve a bare command name the way the host does, without spawning anything.
74
- *
75
- * A mirror of `subprocess-local`'s `executableCandidates` + `resolveExecutable`:
76
- * directory-major order over `PATH`, extension-minor over `PATHEXT`, and
77
- * extensions only when the name has none of its own. Used to decide whether the
78
- * bare-name contribution will actually resolve; if it will not, the caller falls
79
- * back to the absolute path and accepts the `.cmd` in the label.
80
- *
81
- * @param {string} name
82
- * @param {{ platform?: string, pathEnv?: string, pathExt?: string, cwd?: string,
83
- * fs?: { existsSync: (p: string) => boolean } }} [deps]
84
- * @returns {string} resolved path, or '' when nothing matches
85
- */
86
- export function resolveThroughPath(name, deps = {}) {
87
- const platform = deps.platform || process.platform
88
- const fs = deps.fs || { existsSync }
89
- const pathEnv = deps.pathEnv === undefined ? (process.env.PATH || '') : deps.pathEnv
90
- const pathExt = deps.pathExt === undefined
91
- ? (process.env.PATHEXT || DEFAULT_PATH_EXT)
92
- : deps.pathExt
93
- const cwd = deps.cwd || process.cwd()
94
- // The platform being MODELED owns the path semantics, not the platform this
95
- // process runs on: a win32 lookup splits PATH on ';' and understands drive
96
- // letters, which the runtime `path` only does when the host is Windows. On a
97
- // real host the two coincide, so this changes nothing outside tests.
98
- const pathApi = platform === 'win32' ? path.win32 : path.posix
99
- const extensions = platform === 'win32' && pathApi.extname(name) === ''
100
- ? pathExt.split(';').filter(Boolean)
101
- : ['']
102
- const delimiter = platform === 'win32' ? ';' : ':'
103
- for (const directory of pathEnv.split(delimiter)) {
104
- if (!directory) continue
105
- for (const extension of extensions) {
106
- const candidate = pathApi.resolve(cwd, directory, name + extension)
107
- try {
108
- if (fs.existsSync(candidate)) return candidate
109
- } catch { /* an unreadable directory is simply skipped */ }
110
- }
111
- }
112
- return ''
113
- }
114
-
115
- /** Per-environment ownership of the entries this module added. */
116
- const pathEntries = new WeakMap()
117
-
118
- /**
119
- * Append a directory to the process `PATH`, idempotently and ref-counted.
120
- *
121
- * Appended, never prepended: a plugin has no business shadowing a program the
122
- * user already has, and the launcher's name cannot collide by accident.
123
- *
124
- * The entry is ref-counted per environment object because the contribution can
125
- * be installed more than once in a process lifetime — a reload disposes the old
126
- * effect and installs a new one, and the two callbacks may interleave. A plain
127
- * "set/clear" pair would let the first disposal strip the entry out from under
128
- * the still-live registration, which only shows up much later as the menu entry
129
- * silently vanishing (the host cannot resolve a bare name that is no longer on
130
- * PATH).
131
- *
132
- * A directory that was already on `PATH` before we touched it is marked as
133
- * externally owned and is never removed by us.
134
- *
135
- * @param {string} dir - absolute directory to expose
136
- * @param {object} [env] - environment object; defaults to `process.env`
137
- * @returns {() => void} undo, safe to call more than once
138
- * @throws {Error} when the variable cannot be written
139
- */
140
- export function appendPathEntry(dir, env = process.env) {
141
- const absolute = path.resolve(dir)
142
- const key = Object.keys(env).find((name) => name.toUpperCase() === 'PATH') || 'PATH'
143
- let owned = pathEntries.get(env)
144
- if (!owned) {
145
- owned = new Map()
146
- pathEntries.set(env, owned)
147
- }
148
- const count = owned.get(absolute)
149
- if (count === undefined) {
150
- const current = env[key] || ''
151
- const parts = current.split(path.delimiter).filter(Boolean)
152
- if (parts.some((entry) => path.resolve(entry) === absolute)) {
153
- owned.set(absolute, 0) // pre-existing: ours to use, not ours to remove
154
- } else {
155
- env[key] = current === '' ? dir : current + path.delimiter + dir
156
- owned.set(absolute, 1)
157
- }
158
- } else if (count > 0) {
159
- owned.set(absolute, count + 1)
160
- }
161
- return () => {
162
- const live = owned.get(absolute)
163
- if (live === undefined || live <= 0) return
164
- if (live > 1) {
165
- owned.set(absolute, live - 1)
166
- return
167
- }
168
- owned.delete(absolute)
169
- const kept = (env[key] || '')
170
- .split(path.delimiter)
171
- .filter((entry) => entry !== '' && path.resolve(entry) !== absolute)
172
- env[key] = kept.join(path.delimiter)
173
- }
174
- }
175
-
176
- /**
177
- * Node interpreters worth baking into the launcher, most specific first.
178
- *
179
- * The desktop host does not put its bundled node on a child's PATH (by design),
180
- * so an absolute path is the only reliable option; `where node` is a last
181
- * resort. When no node is found the launcher falls back to re-entering the
182
- * Electron binary with `ELECTRON_RUN_AS_NODE`, which needs no second runtime.
183
- *
184
- * Electron puts its resources beside the executable on Windows and Linux, but
185
- * under `Contents/Resources` on macOS, so the path derived from `execPath` has
186
- * to follow the platform; the `resourcesPath` candidate already does.
187
- *
188
- * The runtime directory itself moved once already: DSH NEXT 2.x nests it under
189
- * an architecture segment (`resources/runtime/x64/primary-runtime/…`) where
190
- * older builds kept it directly under `resources/runtime` (issue #91). The
191
- * exact arch is tried first, the pre-2.x layout second, and any other
192
- * single-level directory under `runtime/` last, so a renamed arch segment
193
- * still resolves instead of falling through to the Electron masquerade.
194
- *
195
- * @param {{ execPath?: string, resourcesPath?: string, platform?: string, arch?: string,
196
- * env?: object, electron?: boolean }} deps
197
- * @returns {string[]} existing interpreter candidates, in preference order
198
- */
199
- export function runtimeNodeCandidates(deps = {}) {
200
- const platform = deps.platform || process.platform
201
- const env = deps.env || process.env
202
- const arch = deps.arch || process.arch
203
- // `undefined` means "ask the process", `''` means "this host has no such
204
- // executable" — callers that model another platform rely on the difference.
205
- const execPath = deps.execPath === undefined ? (process.execPath || '') : deps.execPath
206
- const exe = platform === 'win32' ? 'node.exe' : 'node'
207
- const suffix = ['primary-runtime', 'dependencies', 'node', 'bin', exe]
208
- const out = []
209
- const push = (value) => { if (value && !out.includes(value)) out.push(value) }
210
- const pushFrom = (resourcesDir) => {
211
- if (!resourcesDir) return
212
- push(path.join(resourcesDir, 'runtime', arch, ...suffix))
213
- push(path.join(resourcesDir, 'runtime', ...suffix))
214
- let entries = []
215
- try { entries = readdirSync(path.join(resourcesDir, 'runtime')) } catch { /* no runtime dir */ }
216
- for (const entry of entries) {
217
- if (entry !== arch) push(path.join(resourcesDir, 'runtime', entry, ...suffix))
218
- }
219
- }
220
- push(env.DSH_REMOTE_TERMINAL_NODE)
221
- pushFrom(deps.resourcesPath)
222
- if (execPath) {
223
- const here = path.dirname(execPath)
224
- pushFrom(platform === 'darwin' ? path.join(here, '..', 'Resources') : path.join(here, 'resources'))
225
- // A plain node install: execPath IS the interpreter.
226
- if (!deps.electron && path.basename(execPath).toLowerCase() === exe) push(execPath)
227
- }
228
- return out.filter((candidate) => {
229
- try { return existsSync(candidate) } catch { return false }
230
- })
231
- }
232
-
233
- /**
234
- * Body of the generated launcher. Pure so it can be asserted without touching
235
- * the filesystem.
236
- *
237
- * @param {{ platform?: string, nodePath?: string, electronPath?: string, childPath: string, machinesFile: string }} spec
238
- * @returns {string} launcher source, runnable as-is
239
- */
240
- export function launcherSource(spec) {
241
- const platform = spec.platform || process.platform
242
- const child = spec.childPath
243
- const machines = spec.machinesFile
244
- if (platform === 'win32') {
245
- const node = spec.nodePath || ''
246
- const electron = spec.electronPath || ''
247
- const lines = [
248
- '@echo off',
249
- 'rem Generated by dsh-remote - do not edit; rewritten on every load.',
250
- 'setlocal',
251
- `set "DSH_CHILD=${child}"`,
252
- `set "DSH_MACHINES=${machines}"`,
253
- // Where the askpass helper + credential-bridge payload live (this .cmd's
254
- // own directory); the child reads it to decide whether password auth can
255
- // be bridged (see remote-shell-child.cjs askpassEnv).
256
- 'set "DSH_TERM_DIR=%~dp0"',
257
- `set "DSH_NODE=${node}"`,
258
- 'if defined DSH_NODE if exist "%DSH_NODE%" goto :run',
259
- 'set "DSH_NODE="',
260
- 'for /f "delims=" %%N in (\'where node 2^>nul\') do if not defined DSH_NODE set "DSH_NODE=%%N"',
261
- 'if defined DSH_NODE goto :run',
262
- ]
263
- // Re-entering the Electron binary as node only makes sense when this host
264
- // IS an Electron app; a plain node install has nothing to re-enter.
265
- if (electron) {
266
- lines.push(
267
- // The hint must run BEFORE the fallback: anything after `exit /b` is
268
- // dead code, which is exactly how the deaf-terminal hint used to be
269
- // unreachable precisely in the configuration that needed it (issue #91).
270
- 'echo [dsh-remote] no standalone node found; falling back to the bundled runtime. 1>&2',
271
- 'echo [dsh-remote] if this terminal shows output but ignores input, set DSH_REMOTE_TERMINAL_NODE to an absolute node.exe path. 1>&2',
272
- 'set "ELECTRON_RUN_AS_NODE=1"',
273
- `"${electron}" "%DSH_CHILD%" --machines "%DSH_MACHINES%"`,
274
- 'exit /b %ERRORLEVEL%',
275
- )
276
- }
277
- lines.push(
278
- 'echo [dsh-remote] no node interpreter found for the remote terminal. 1>&2',
279
- 'echo [dsh-remote] set DSH_REMOTE_TERMINAL_NODE to an absolute node.exe path, or reinstall dsh-remote. 1>&2',
280
- 'exit /b 127',
281
- ':run',
282
- '"%DSH_NODE%" "%DSH_CHILD%" --machines "%DSH_MACHINES%"',
283
- 'exit /b %ERRORLEVEL%',
284
- '',
285
- )
286
- return lines.join('\r\n')
287
- }
288
- const node = spec.nodePath || ''
289
- return [
290
- '#!/bin/sh',
291
- '# Generated by dsh-remote - do not edit; rewritten on every load.',
292
- `DSH_CHILD=${shqPosix(child)}`,
293
- `DSH_MACHINES=${shqPosix(machines)}`,
294
- // Physical directory of this script: the askpass helper + payload live here.
295
- 'DSH_TERM_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
296
- node ? `DSH_NODE=${shqPosix(node)}` : 'DSH_NODE=',
297
- 'if [ -n "$DSH_NODE" ] && [ -x "$DSH_NODE" ]; then exec "$DSH_NODE" "$DSH_CHILD" --machines "$DSH_MACHINES"; fi',
298
- 'if command -v node >/dev/null 2>&1; then exec node "$DSH_CHILD" --machines "$DSH_MACHINES"; fi',
299
- 'echo "[dsh-remote] no node interpreter found for the remote terminal." >&2',
300
- 'exit 127',
301
- '',
302
- ].join('\n')
303
- }
304
-
305
- /** POSIX single-quote, for paths baked into a shell script. */
306
- export function shqPosix(value) {
307
- return "'" + String(value).replace(/'/g, "'\\''") + "'"
308
- }
309
-
310
- // ── the credential bridge helper (saved-password terminal auth) ─────────────
311
- //
312
- // The `remote ssh` terminal spawns the OS ssh, which knows keys and agents but
313
- // has no way to receive the password the plugin saved (plaintext registry or OS
314
- // keychain). The bridge: ssh (with SSH_ASKPASS_REQUIRE=force) calls this
315
- // helper, the helper POSTs the machine identity to the RUNNING plugin's
316
- // loopback route `/dsh-remote/term-secret` with a per-boot bearer token, and
317
- // the host answers through the same credential chain a real connect uses.
318
- // The token + URL live in `term-secret.json` next to the launcher (0600); the
319
- // helper itself carries no secret.
320
-
321
- /** Absolute path of the askpass wrapper for the platform. */
322
- export function askpassWrapperPath(dir, platform = process.platform) {
323
- return path.join(dir, platform === 'win32' ? 'term-askpass.cmd' : 'term-askpass')
324
- }
325
-
326
- /** Body of term-askpass.cjs — plain CJS, no dependencies, no secrets. */
327
- export function askpassHelperSource() {
328
- return [
329
- '#!/usr/bin/env node',
330
- '// Generated by dsh-remote - do not edit; rewritten on every load.',
331
- '// ssh askpass helper: fetch the saved password for DSH_TS_* (host/port/',
332
- '// username) from the running dsh-remote host, print it on stdout.',
333
- '// Exit nonzero without output when the bridge cannot answer - ssh then',
334
- '// fails authentication (SSH_ASKPASS_REQUIRE=force trades the tty prompt',
335
- '// for the bridge; the child only enables it when a credential exists).',
336
- "'use strict'",
337
- 'const { readFileSync } = require("node:fs")',
338
- 'const { join } = require("node:path")',
339
- 'const http = require("node:http")',
340
- 'function main() {',
341
- ' let cfg',
342
- ' try { cfg = JSON.parse(readFileSync(join(__dirname, "term-secret.json"), "utf8")) } catch { process.exit(2) }',
343
- ' const body = JSON.stringify({',
344
- ' host: process.env.DSH_TS_HOST || "",',
345
- ' port: Number(process.env.DSH_TS_PORT) || 22,',
346
- ' username: process.env.DSH_TS_USERNAME || "",',
347
- ' alias: process.env.DSH_TS_ALIAS || "",',
348
- ' })',
349
- ' const base = String(cfg.url || "").replace(/\\/+$/, "")',
350
- ' if (!cfg.token || !base) process.exit(2)',
351
- ' const url = new URL(base + "/dsh-remote/term-secret")',
352
- ' const req = http.request({',
353
- ' method: "POST", host: url.hostname, port: url.port, path: url.pathname,',
354
- ' headers: {',
355
- ' "content-type": "application/json",',
356
- ' authorization: "Bearer " + cfg.token,',
357
- ' "content-length": Buffer.byteLength(body),',
358
- ' },',
359
- ' timeout: 5000,',
360
- ' }, (res) => {',
361
- ' let buf = ""',
362
- ' res.on("data", (chunk) => { buf += chunk })',
363
- ' res.on("end", () => {',
364
- ' try {',
365
- ' const parsed = JSON.parse(buf)',
366
- ' if (res.statusCode === 200 && parsed && parsed.ok && typeof parsed.password === "string" && parsed.password.length > 0) {',
367
- ' process.stdout.write(parsed.password + "\\n")',
368
- ' return',
369
- ' }',
370
- ' } catch { /* malformed answer */ }',
371
- ' process.exit(3)',
372
- ' })',
373
- ' })',
374
- ' req.on("timeout", () => { req.destroy(); process.exit(4) })',
375
- ' req.on("error", () => process.exit(5))',
376
- ' req.end(body)',
377
- '}',
378
- 'main()',
379
- '',
380
- ].join('\n')
381
- }
382
-
383
- /**
384
- * Write the askpass helper + its platform wrapper next to the launcher.
385
- * Called from writeLauncher so an upgrade rewrites both in one place.
386
- * Carries NO secret: URL + per-boot token land in term-secret.json, written by
387
- * the host half once the webserver origin is known (and deleted on boot when
388
- * the composition has no webserver, so a stale bridge can never hijack the
389
- * prompt on Desktop).
390
- *
391
- * @param {{ dir: string, platform?: string, nodePath?: string, fs?: object }} spec
392
- */
393
- export function writeTermSecretHelpers(spec) {
394
- const platform = spec.platform || process.platform
395
- const fs = spec.fs || { writeFileSync, chmodSync }
396
- const node = spec.nodePath || 'node'
397
- fs.writeFileSync(path.join(spec.dir, 'term-askpass.cjs'), askpassHelperSource(), 'utf8')
398
- const wrapper = askpassWrapperPath(spec.dir, platform)
399
- if (platform === 'win32') {
400
- fs.writeFileSync(wrapper, [
401
- '@echo off',
402
- 'rem Generated by dsh-remote - do not edit; rewritten on every load.',
403
- `"${node}" "%~dp0term-askpass.cjs" %*`,
404
- '',
405
- ].join('\r\n'), 'utf8')
406
- } else {
407
- fs.writeFileSync(wrapper, [
408
- '#!/bin/sh',
409
- '# Generated by dsh-remote - do not edit; rewritten on every load.',
410
- `exec ${shqPosix(node)} "$(dirname -- "$0")/term-askpass.cjs" "$@"`,
411
- '',
412
- ].join('\n'), 'utf8')
413
- try { fs.chmodSync(wrapper, 0o755) } catch { /* mode-less fs */ }
414
- }
415
- return { wrapper, helper: path.join(spec.dir, 'term-askpass.cjs') }
416
- }
417
-
418
- /**
419
- * Remove a launcher left on disk under another spelling of the same name.
420
- *
421
- * The menu label IS the file name, so renaming the option renames the file. On
422
- * a case-insensitive volume (NTFS, and APFS by default) writing the new spelling
423
- * lands in the OLD directory entry and the menu keeps showing the previous
424
- * name; on a case-sensitive one the old file would simply linger and, having
425
- * been registered before, could still appear. Deleting the stale entry first
426
- * makes a rename take effect on both.
427
- *
428
- * Best effort throughout: a launcher that cannot be cleaned up must not stop
429
- * the new one from being written.
430
- *
431
- * @param {string} dir
432
- * @param {string} keepName - basename that must survive
433
- * @param {object} fs
434
- */
435
- function removeStaleLauncher(dir, keepName, fs) {
436
- if (typeof fs.readdirSync !== 'function' || typeof fs.unlinkSync !== 'function') return
437
- let entries
438
- try {
439
- entries = fs.readdirSync(dir)
440
- } catch {
441
- return // first run: the directory does not exist yet
442
- }
443
- for (const entry of entries) {
444
- if (entry === keepName || entry.toLowerCase() !== keepName.toLowerCase()) continue
445
- try { fs.unlinkSync(path.join(dir, entry)) } catch { /* keep going */ }
446
- }
447
- }
448
-
449
- /**
450
- * Write (or refresh) the launcher. Idempotent and cheap: the content is a pure
451
- * function of this install's paths, so a plugin upgrade that moves the package
452
- * rewrites the same file with the new child path.
453
- *
454
- * @param {{ dir: string, platform?: string, childPath: string, machinesFile: string, nodePath?: string, electronPath?: string, fs?: object }} spec
455
- * @returns {{ path: string, source: string }}
456
- */
457
- export function writeLauncher(spec) {
458
- const platform = spec.platform || process.platform
459
- const fs = spec.fs || { mkdirSync, writeFileSync, chmodSync, readdirSync, unlinkSync }
460
- fs.mkdirSync(spec.dir, { recursive: true })
461
- const file = shellLauncherPath(spec.dir, platform)
462
- // Before writing: on a case-insensitive filesystem the new name would
463
- // otherwise be absorbed into the old entry.
464
- removeStaleLauncher(spec.dir, path.basename(file), fs)
465
- const source = launcherSource({ ...spec, platform })
466
- fs.writeFileSync(file, source, 'utf8')
467
- if (platform !== 'win32') {
468
- try { fs.chmodSync(file, 0o755) } catch { /* a no-op on filesystems without modes */ }
469
- }
470
- // The credential-bridge helper travels with the launcher (same rewrite
471
- // cadence, same directory the launcher exports as DSH_TERM_DIR).
472
- const helpers = writeTermSecretHelpers({ dir: spec.dir, platform, nodePath: spec.nodePath || '', fs })
473
- return { path: file, source, askpass: helpers.wrapper }
474
- }
475
-
476
- /**
477
- * Add one entry to the host terminal's shell list.
478
- *
479
- * `shellCandidates` is the exact array `discoverShells` reads on every `shells()`
480
- * call, so appending to it is live: the next time the user opens the shell menu
481
- * the entry is there, and `spawn()` accepts the matching `shellPath` because it
482
- * looks the path up in that same list. Removing it on dispose keeps the menu
483
- * truthful when the plugin is unloaded.
484
- *
485
- * A host without the field (older line, or a controller rebuilt to hide the
486
- * array) is not an error: the plugin simply contributes no shell. A host that
487
- * HAS the field but refuses the write is a different story — that throws, so the
488
- * caller can say why the option never appeared instead of leaving the user to
489
- * guess.
490
- *
491
- * @param {object} controller - the `terminalController` service
492
- * @param {string} candidate - absolute launcher path
493
- * @returns {(() => void) | null} undo, or null when there is nothing to undo
494
- * @throws {TypeError} when the host exposes a shell list that cannot be written
495
- */
496
- export function addShellCandidate(controller, candidate) {
497
- const config = controller && controller.config
498
- const list = config && config.shellCandidates
499
- if (!Array.isArray(list)) return null
500
- if (list.includes(candidate)) return null
501
- list.push(candidate)
502
- return () => {
503
- const at = list.indexOf(candidate)
504
- if (at >= 0) list.splice(at, 1)
505
- }
506
- }
507
-
508
- /** Human-readable reason from anything thrown. */
509
- function reason(err) {
510
- return String((err && err.message) || err)
511
- }
512
-
513
- /** Read an environment variable case-insensitively, as Windows does. */
514
- function envValue(env, name) {
515
- if (!env) return undefined
516
- if (env[name] !== undefined) return env[name]
517
- const match = Object.keys(env).find((key) => key.toUpperCase() === name.toUpperCase())
518
- return match === undefined ? undefined : env[match]
519
- }
520
-
521
- /**
522
- * Claim the terminal's default shell slot when nobody else holds it.
523
- *
524
- * `config.shell` is what `discoverShells` puts FIRST and what a terminal spawn
525
- * without an explicit shellPath resolves to — i.e. where a bare "open
526
- * terminal" click lands. Pointing it at our launcher makes the default
527
- * terminal SMART: the child script ssh'es into the remote workspace when the
528
- * session cwd is a mirror and falls back to a local shell when it is not.
529
- * A user-configured shell (config.shell already set) is never touched, and an
530
- * explicit pick from the shell menu still wins (the client's remembered
531
- * preference beats the first list entry).
532
- *
533
- * @param {object} controller - the terminalController service
534
- * @param {string} launcherPath - absolute launcher path
535
- * @returns {(() => void) | undefined} undo that only fires while the claim is still ours
536
- */
537
- function claimDefaultShell(controller, launcherPath) {
538
- const config = controller && controller.config
539
- if (!config || typeof config !== 'object') return undefined
540
- if (config.shell !== undefined) return undefined
541
- const ours = { path: launcherPath, name: SHELL_OPTION_NAME, args: [] }
542
- config.shell = ours
543
- return () => {
544
- // Someone else (host settings, another plugin) took the slot since:
545
- // restoring `undefined` would clobber THEIR choice.
546
- if (config.shell === ours) config.shell = undefined
547
- }
548
- }
549
-
550
- /**
551
- * Write the launcher and put it in the terminal's shell menu.
552
- *
553
- * Kept out of the plugin entry so the whole contribution — write, publish,
554
- * withdraw — can be exercised without booting the host. Every way this can
555
- * fail to produce a visible menu entry is reported through `logger.warn`,
556
- * because the failure mode that matters is silent: a launcher on disk plus no
557
- * option in the menu is indistinguishable from "the feature was never built".
558
- *
559
- * @param {object} ctx - plugin context; only `effect`, `get('logger')` are used
560
- * @param {object} controller - the resolved `terminalController` *service*
561
- * @param {{ dir: string, childPath: string, machinesFile: string, platform?: string,
562
- * nodePath?: string, electronPath?: string, electron?: boolean, logger?: object,
563
- * env?: object, fs?: { existsSync: (p: string) => boolean },
564
- * claimDefault?: boolean }} spec - `claimDefault: false` keeps the
565
- * launcher menu-only (never touches `config.shell`)
566
- * @returns {boolean} whether the option is (or already was) in the menu
567
- */
568
- export function installTerminalShell(ctx, controller, spec = {}) {
569
- const logger = spec.logger !== undefined
570
- ? spec.logger
571
- : (ctx && typeof ctx.get === 'function' ? ctx.get('logger') : undefined)
572
- const warn = (message) => {
573
- try {
574
- if (logger && typeof logger.warn === 'function') logger.warn(`dsh-remote: ${message}`)
575
- } catch { /* a logger failure must not change the outcome */ }
576
- }
577
-
578
- const platform = spec.platform || process.platform
579
- const electron = spec.electron === undefined
580
- ? Boolean(process.versions && process.versions.electron)
581
- : spec.electron
582
- const nodePath = spec.nodePath === undefined
583
- ? (runtimeNodeCandidates({
584
- platform,
585
- resourcesPath: process.resourcesPath,
586
- execPath: process.execPath,
587
- env: process.env,
588
- electron,
589
- })[0] || '')
590
- : spec.nodePath
591
- const electronPath = spec.electronPath === undefined
592
- ? (electron ? process.execPath : '')
593
- : spec.electronPath
594
-
595
- let launcher
596
- try {
597
- launcher = writeLauncher({
598
- dir: spec.dir,
599
- platform,
600
- childPath: spec.childPath,
601
- machinesFile: spec.machinesFile,
602
- nodePath,
603
- electronPath,
604
- })
605
- } catch (err) {
606
- // A read-only DSH_HOME must not take the plugin down: the terminal just
607
- // keeps offering the shells it already had.
608
- warn(`cannot write the remote terminal launcher: ${reason(err)}`)
609
- return false
610
- }
611
-
612
- if (controller === undefined || controller === null) {
613
- warn('the terminal controller is unavailable; the remote ssh option is unavailable')
614
- return false
615
- }
616
- const list = controller.config && controller.config.shellCandidates
617
- if (!Array.isArray(list)) {
618
- // Either an older host, or the wrong object was passed in — the service is
619
- // reached with `ctx.get('terminalController')`, not with the inject callback
620
- // argument itself. Say which one it looks like.
621
- const looksLikeContext = typeof controller.get === 'function' || typeof controller.inject === 'function'
622
- warn(looksLikeContext
623
- ? 'the terminal controller was not resolved (a plugin context was passed instead); the remote ssh option is unavailable'
624
- : 'the terminal controller exposes no shellCandidates list; the remote ssh option is unavailable')
625
- return false
626
- }
627
-
628
- // On Windows the label is the candidate's basename, so contributing a file
629
- // path would show `remote ssh.cmd`. Contributing the bare name keeps the label
630
- // clean, at the price of exposing the launcher directory on PATH — and only
631
- // while the host can actually resolve that name.
632
- const bare = shellCandidate(platform, launcher.path)
633
- const needsPath = bare !== launcher.path
634
- const env = spec.env || process.env
635
- const fs = spec.fs || { existsSync }
636
-
637
- let installed = false
638
- const publish = () => {
639
- // The PATH entry lives inside the effect, not outside it: if the effect ever
640
- // re-runs, the new run must put the entry back that the previous disposal
641
- // took away. `appendPathEntry` ref-counts, so interleaved install/dispose
642
- // pairs cannot strand a live registration without PATH.
643
- let restorePath
644
- let candidate = launcher.path
645
- // The default-shell claim uses the ABSOLUTE launcher path, never the bare
646
- // menu name: it must keep resolving even while the PATH entry is gone.
647
- const releaseDefault = spec.claimDefault === false
648
- ? undefined
649
- : claimDefaultShell(controller, launcher.path)
650
- if (needsPath) {
651
- try {
652
- restorePath = appendPathEntry(path.dirname(launcher.path), env)
653
- const found = resolveThroughPath(bare, {
654
- platform,
655
- pathEnv: envValue(env, 'PATH') || '',
656
- pathExt: envValue(env, 'PATHEXT'),
657
- fs,
658
- })
659
- if (found) candidate = bare
660
- else {
661
- // `PATHEXT` without `.CMD`, or a PATH that refuses the write. The
662
- // option still works when contributed by absolute path; only its
663
- // label carries the suffix.
664
- restorePath()
665
- restorePath = undefined
666
- warn('the host cannot resolve the launcher by name; the remote ssh option keeps its .cmd suffix')
667
- }
668
- } catch (err) {
669
- candidate = launcher.path
670
- restorePath = undefined
671
- warn(`the launcher directory cannot be added to PATH (${reason(err)}); the remote ssh option keeps its .cmd suffix`)
672
- }
673
- }
674
- try {
675
- const undo = addShellCandidate(controller, candidate)
676
- installed = true
677
- return () => {
678
- if (undo) undo()
679
- if (restorePath) restorePath()
680
- if (releaseDefault) releaseDefault()
681
- }
682
- } catch (err) {
683
- // The host advertises a shell list but will not take a write.
684
- if (restorePath) restorePath()
685
- if (releaseDefault) releaseDefault()
686
- warn(`the terminal shell list rejected the remote shell (${reason(err)}); the remote ssh option is unavailable`)
687
- return undefined
688
- }
689
- }
690
-
691
- if (ctx && typeof ctx.effect === 'function') {
692
- ctx.effect(publish, 'dsh-remote.terminal-shell')
693
- } else {
694
- publish()
695
- }
696
- return installed
697
- }
1
+ /**
2
+ * Remote terminal as a shell choice — the host terminal's own option list.
3
+ *
4
+ * The built-in terminal is a *local* pty whose program comes from
5
+ * `dsh-api-terminal-controller`'s verified shell list (`shellCandidates`). A
6
+ * plugin cannot hand that pty a command line, but it CAN contribute one entry
7
+ * to that list: an absolute path to a launcher we generate. The pty then runs
8
+ * our launcher as a local process, and the launcher execs `ssh` with inherited
9
+ * stdio — which is exactly how the terminal should behave. Resizing, key
10
+ * binding, scrollback and color all stay the host's job; nothing is re-implemented
11
+ * here.
12
+ *
13
+ * The launcher itself is dumb (find node, run the child script). The child
14
+ * (`remote-shell-child.cjs`) resolves the remote target from the checkout it is
15
+ * started in and replaces itself with `ssh`.
16
+ *
17
+ * @module dsh-remote/remote-shell
18
+ */
19
+
20
+ import { chmodSync, existsSync, mkdirSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'
21
+ import path from 'node:path'
22
+
23
+ /** Label shown in the terminal's shell menu.
24
+ *
25
+ * Windows needs a real `.cmd` on disk (ConPTY cannot start an extensionless
26
+ * file), but the label does not have to advertise it: the menu shows the
27
+ * candidate's basename, and `shellCandidate` contributes the bare name so the
28
+ * host resolves it through `PATH` + `PATHEXT`. The suffix is therefore an
29
+ * implementation detail of the file on disk, not of the menu entry. */
30
+ export const SHELL_OPTION_NAME = 'remote ssh'
31
+
32
+ /** Absolute path of the generated launcher for this platform. */
33
+ export function shellLauncherPath(dir, platform = process.platform) {
34
+ return path.join(dir, platform === 'win32' ? SHELL_OPTION_NAME + '.cmd' : SHELL_OPTION_NAME)
35
+ }
36
+
37
+ /** Default `PATHEXT`, used when the environment does not carry one. */
38
+ const DEFAULT_PATH_EXT = '.COM;.EXE;.BAT;.CMD'
39
+
40
+ /**
41
+ * The value to contribute to `shellCandidates`.
42
+ *
43
+ * The menu label is `executableName(candidate)` — the candidate's basename, with
44
+ * no extension stripped — while the path that actually runs is whatever the host
45
+ * resolves. Those are two different things, and the gap is the only way to get a
46
+ * clean label on Windows.
47
+ *
48
+ * A file path would be shown as `remote ssh.cmd`, because the terminal has to
49
+ * start a real `.cmd` and ConPTY refuses anything else (a file with no extension
50
+ * dies with 193, `ERROR_BAD_EXE_FORMAT`). So on Windows the *bare* name is
51
+ * contributed instead: the host resolves it through `PATH` + `PATHEXT`, lands on
52
+ * `remote ssh.cmd`, and the label stays `remote ssh`. That is exactly the rule
53
+ * `resolveExecutable` documents — an absolute path is checked as-is with no
54
+ * extension guessing, a bare name is looked up per `PATHEXT`.
55
+ *
56
+ * Two consequences, both handled by the caller: the launcher's directory has to
57
+ * be on `PATH` (see `appendPathEntry`), and the name must contain no dot, since
58
+ * a bare name is only extended when `extname()` is empty.
59
+ *
60
+ * POSIX has no such rule — the file is directly executable — so the absolute
61
+ * path is contributed as-is.
62
+ *
63
+ * @param {string} platform
64
+ * @param {string} launcherPath
65
+ * @returns {string} candidate value for the shell list
66
+ */
67
+ export function shellCandidate(platform, launcherPath) {
68
+ if (platform !== 'win32') return launcherPath
69
+ return path.basename(launcherPath).replace(/\.cmd$/i, '')
70
+ }
71
+
72
+ /**
73
+ * Resolve a bare command name the way the host does, without spawning anything.
74
+ *
75
+ * A mirror of `subprocess-local`'s `executableCandidates` + `resolveExecutable`:
76
+ * directory-major order over `PATH`, extension-minor over `PATHEXT`, and
77
+ * extensions only when the name has none of its own. Used to decide whether the
78
+ * bare-name contribution will actually resolve; if it will not, the caller falls
79
+ * back to the absolute path and accepts the `.cmd` in the label.
80
+ *
81
+ * @param {string} name
82
+ * @param {{ platform?: string, pathEnv?: string, pathExt?: string, cwd?: string,
83
+ * fs?: { existsSync: (p: string) => boolean } }} [deps]
84
+ * @returns {string} resolved path, or '' when nothing matches
85
+ */
86
+ export function resolveThroughPath(name, deps = {}) {
87
+ const platform = deps.platform || process.platform
88
+ const fs = deps.fs || { existsSync }
89
+ const pathEnv = deps.pathEnv === undefined ? (process.env.PATH || '') : deps.pathEnv
90
+ const pathExt = deps.pathExt === undefined
91
+ ? (process.env.PATHEXT || DEFAULT_PATH_EXT)
92
+ : deps.pathExt
93
+ const cwd = deps.cwd || process.cwd()
94
+ // The platform being MODELED owns the path semantics, not the platform this
95
+ // process runs on: a win32 lookup splits PATH on ';' and understands drive
96
+ // letters, which the runtime `path` only does when the host is Windows. On a
97
+ // real host the two coincide, so this changes nothing outside tests.
98
+ const pathApi = platform === 'win32' ? path.win32 : path.posix
99
+ const extensions = platform === 'win32' && pathApi.extname(name) === ''
100
+ ? pathExt.split(';').filter(Boolean)
101
+ : ['']
102
+ const delimiter = platform === 'win32' ? ';' : ':'
103
+ for (const directory of pathEnv.split(delimiter)) {
104
+ if (!directory) continue
105
+ for (const extension of extensions) {
106
+ const candidate = pathApi.resolve(cwd, directory, name + extension)
107
+ try {
108
+ if (fs.existsSync(candidate)) return candidate
109
+ } catch { /* an unreadable directory is simply skipped */ }
110
+ }
111
+ }
112
+ return ''
113
+ }
114
+
115
+ /** Per-environment ownership of the entries this module added. */
116
+ const pathEntries = new WeakMap()
117
+
118
+ /**
119
+ * Append a directory to the process `PATH`, idempotently and ref-counted.
120
+ *
121
+ * Appended, never prepended: a plugin has no business shadowing a program the
122
+ * user already has, and the launcher's name cannot collide by accident.
123
+ *
124
+ * The entry is ref-counted per environment object because the contribution can
125
+ * be installed more than once in a process lifetime — a reload disposes the old
126
+ * effect and installs a new one, and the two callbacks may interleave. A plain
127
+ * "set/clear" pair would let the first disposal strip the entry out from under
128
+ * the still-live registration, which only shows up much later as the menu entry
129
+ * silently vanishing (the host cannot resolve a bare name that is no longer on
130
+ * PATH).
131
+ *
132
+ * A directory that was already on `PATH` before we touched it is marked as
133
+ * externally owned and is never removed by us.
134
+ *
135
+ * @param {string} dir - absolute directory to expose
136
+ * @param {object} [env] - environment object; defaults to `process.env`
137
+ * @returns {() => void} undo, safe to call more than once
138
+ * @throws {Error} when the variable cannot be written
139
+ */
140
+ export function appendPathEntry(dir, env = process.env) {
141
+ const absolute = path.resolve(dir)
142
+ const key = Object.keys(env).find((name) => name.toUpperCase() === 'PATH') || 'PATH'
143
+ let owned = pathEntries.get(env)
144
+ if (!owned) {
145
+ owned = new Map()
146
+ pathEntries.set(env, owned)
147
+ }
148
+ const count = owned.get(absolute)
149
+ if (count === undefined) {
150
+ const current = env[key] || ''
151
+ const parts = current.split(path.delimiter).filter(Boolean)
152
+ if (parts.some((entry) => path.resolve(entry) === absolute)) {
153
+ owned.set(absolute, 0) // pre-existing: ours to use, not ours to remove
154
+ } else {
155
+ env[key] = current === '' ? dir : current + path.delimiter + dir
156
+ owned.set(absolute, 1)
157
+ }
158
+ } else if (count > 0) {
159
+ owned.set(absolute, count + 1)
160
+ }
161
+ return () => {
162
+ const live = owned.get(absolute)
163
+ if (live === undefined || live <= 0) return
164
+ if (live > 1) {
165
+ owned.set(absolute, live - 1)
166
+ return
167
+ }
168
+ owned.delete(absolute)
169
+ const kept = (env[key] || '')
170
+ .split(path.delimiter)
171
+ .filter((entry) => entry !== '' && path.resolve(entry) !== absolute)
172
+ env[key] = kept.join(path.delimiter)
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Node interpreters worth baking into the launcher, most specific first.
178
+ *
179
+ * The desktop host does not put its bundled node on a child's PATH (by design),
180
+ * so an absolute path is the only reliable option; `where node` is a last
181
+ * resort. When no node is found the launcher falls back to re-entering the
182
+ * Electron binary with `ELECTRON_RUN_AS_NODE`, which needs no second runtime.
183
+ *
184
+ * Electron puts its resources beside the executable on Windows and Linux, but
185
+ * under `Contents/Resources` on macOS, so the path derived from `execPath` has
186
+ * to follow the platform; the `resourcesPath` candidate already does.
187
+ *
188
+ * The runtime directory itself moved once already: DSH NEXT 2.x nests it under
189
+ * an architecture segment (`resources/runtime/x64/primary-runtime/…`) where
190
+ * older builds kept it directly under `resources/runtime` (issue #91). The
191
+ * exact arch is tried first, the pre-2.x layout second, and any other
192
+ * single-level directory under `runtime/` last, so a renamed arch segment
193
+ * still resolves instead of falling through to the Electron masquerade.
194
+ *
195
+ * @param {{ execPath?: string, resourcesPath?: string, platform?: string, arch?: string,
196
+ * env?: object, electron?: boolean }} deps
197
+ * @returns {string[]} existing interpreter candidates, in preference order
198
+ */
199
+ export function runtimeNodeCandidates(deps = {}) {
200
+ const platform = deps.platform || process.platform
201
+ const env = deps.env || process.env
202
+ const arch = deps.arch || process.arch
203
+ // `undefined` means "ask the process", `''` means "this host has no such
204
+ // executable" — callers that model another platform rely on the difference.
205
+ const execPath = deps.execPath === undefined ? (process.execPath || '') : deps.execPath
206
+ const exe = platform === 'win32' ? 'node.exe' : 'node'
207
+ const suffix = ['primary-runtime', 'dependencies', 'node', 'bin', exe]
208
+ const out = []
209
+ const push = (value) => { if (value && !out.includes(value)) out.push(value) }
210
+ const pushFrom = (resourcesDir) => {
211
+ if (!resourcesDir) return
212
+ push(path.join(resourcesDir, 'runtime', arch, ...suffix))
213
+ push(path.join(resourcesDir, 'runtime', ...suffix))
214
+ let entries = []
215
+ try { entries = readdirSync(path.join(resourcesDir, 'runtime')) } catch { /* no runtime dir */ }
216
+ for (const entry of entries) {
217
+ if (entry !== arch) push(path.join(resourcesDir, 'runtime', entry, ...suffix))
218
+ }
219
+ }
220
+ push(env.DSH_REMOTE_TERMINAL_NODE)
221
+ pushFrom(deps.resourcesPath)
222
+ if (execPath) {
223
+ const here = path.dirname(execPath)
224
+ pushFrom(platform === 'darwin' ? path.join(here, '..', 'Resources') : path.join(here, 'resources'))
225
+ // A plain node install: execPath IS the interpreter.
226
+ if (!deps.electron && path.basename(execPath).toLowerCase() === exe) push(execPath)
227
+ }
228
+ return out.filter((candidate) => {
229
+ try { return existsSync(candidate) } catch { return false }
230
+ })
231
+ }
232
+
233
+ /**
234
+ * Body of the generated launcher. Pure so it can be asserted without touching
235
+ * the filesystem.
236
+ *
237
+ * @param {{ platform?: string, nodePath?: string, electronPath?: string, childPath: string, machinesFile: string }} spec
238
+ * @returns {string} launcher source, runnable as-is
239
+ */
240
+ export function launcherSource(spec) {
241
+ const platform = spec.platform || process.platform
242
+ const child = spec.childPath
243
+ const machines = spec.machinesFile
244
+ if (platform === 'win32') {
245
+ const node = spec.nodePath || ''
246
+ const electron = spec.electronPath || ''
247
+ const lines = [
248
+ '@echo off',
249
+ 'rem Generated by dsh-remote - do not edit; rewritten on every load.',
250
+ 'setlocal',
251
+ `set "DSH_CHILD=${child}"`,
252
+ `set "DSH_MACHINES=${machines}"`,
253
+ // Where the askpass helper + credential-bridge payload live (this .cmd's
254
+ // own directory); the child reads it to decide whether password auth can
255
+ // be bridged (see remote-shell-child.cjs askpassEnv).
256
+ 'set "DSH_TERM_DIR=%~dp0"',
257
+ `set "DSH_NODE=${node}"`,
258
+ 'if defined DSH_NODE if exist "%DSH_NODE%" goto :run',
259
+ 'set "DSH_NODE="',
260
+ 'for /f "delims=" %%N in (\'where node 2^>nul\') do if not defined DSH_NODE set "DSH_NODE=%%N"',
261
+ 'if defined DSH_NODE goto :run',
262
+ ]
263
+ // Re-entering the Electron binary as node only makes sense when this host
264
+ // IS an Electron app; a plain node install has nothing to re-enter.
265
+ if (electron) {
266
+ lines.push(
267
+ // The hint must run BEFORE the fallback: anything after `exit /b` is
268
+ // dead code, which is exactly how the deaf-terminal hint used to be
269
+ // unreachable precisely in the configuration that needed it (issue #91).
270
+ 'echo [dsh-remote] no standalone node found; falling back to the bundled runtime. 1>&2',
271
+ 'echo [dsh-remote] if this terminal shows output but ignores input, set DSH_REMOTE_TERMINAL_NODE to an absolute node.exe path. 1>&2',
272
+ 'set "ELECTRON_RUN_AS_NODE=1"',
273
+ `"${electron}" "%DSH_CHILD%" --machines "%DSH_MACHINES%"`,
274
+ 'exit /b %ERRORLEVEL%',
275
+ )
276
+ }
277
+ lines.push(
278
+ 'echo [dsh-remote] no node interpreter found for the remote terminal. 1>&2',
279
+ 'echo [dsh-remote] set DSH_REMOTE_TERMINAL_NODE to an absolute node.exe path, or reinstall dsh-remote. 1>&2',
280
+ 'exit /b 127',
281
+ ':run',
282
+ '"%DSH_NODE%" "%DSH_CHILD%" --machines "%DSH_MACHINES%"',
283
+ 'exit /b %ERRORLEVEL%',
284
+ '',
285
+ )
286
+ return lines.join('\r\n')
287
+ }
288
+ const node = spec.nodePath || ''
289
+ return [
290
+ '#!/bin/sh',
291
+ '# Generated by dsh-remote - do not edit; rewritten on every load.',
292
+ `DSH_CHILD=${shqPosix(child)}`,
293
+ `DSH_MACHINES=${shqPosix(machines)}`,
294
+ // Physical directory of this script: the askpass helper + payload live here.
295
+ 'DSH_TERM_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
296
+ node ? `DSH_NODE=${shqPosix(node)}` : 'DSH_NODE=',
297
+ 'if [ -n "$DSH_NODE" ] && [ -x "$DSH_NODE" ]; then exec "$DSH_NODE" "$DSH_CHILD" --machines "$DSH_MACHINES"; fi',
298
+ 'if command -v node >/dev/null 2>&1; then exec node "$DSH_CHILD" --machines "$DSH_MACHINES"; fi',
299
+ 'echo "[dsh-remote] no node interpreter found for the remote terminal." >&2',
300
+ 'exit 127',
301
+ '',
302
+ ].join('\n')
303
+ }
304
+
305
+ /** POSIX single-quote, for paths baked into a shell script. */
306
+ export function shqPosix(value) {
307
+ return "'" + String(value).replace(/'/g, "'\\''") + "'"
308
+ }
309
+
310
+ // ── the credential bridge helper (saved-password terminal auth) ─────────────
311
+ //
312
+ // The `remote ssh` terminal spawns the OS ssh, which knows keys and agents but
313
+ // has no way to receive the password the plugin saved (plaintext registry or OS
314
+ // keychain). The bridge: ssh (with SSH_ASKPASS_REQUIRE=force) calls this
315
+ // helper, the helper POSTs the machine identity to the RUNNING plugin's
316
+ // loopback route `/dsh-remote/term-secret` with a per-boot bearer token, and
317
+ // the host answers through the same credential chain a real connect uses.
318
+ // The token + URL live in `term-secret.json` next to the launcher (0600); the
319
+ // helper itself carries no secret.
320
+
321
+ /** Absolute path of the askpass wrapper for the platform. */
322
+ export function askpassWrapperPath(dir, platform = process.platform) {
323
+ return path.join(dir, platform === 'win32' ? 'term-askpass.cmd' : 'term-askpass')
324
+ }
325
+
326
+ /** Body of term-askpass.cjs — plain CJS, no dependencies, no secrets. */
327
+ export function askpassHelperSource() {
328
+ return [
329
+ '#!/usr/bin/env node',
330
+ '// Generated by dsh-remote - do not edit; rewritten on every load.',
331
+ '// ssh askpass helper: fetch the saved password for DSH_TS_* (host/port/',
332
+ '// username) from the running dsh-remote host, print it on stdout.',
333
+ '// Exit nonzero without output when the bridge cannot answer - ssh then',
334
+ '// fails authentication (SSH_ASKPASS_REQUIRE=force trades the tty prompt',
335
+ '// for the bridge; the child only enables it when a credential exists).',
336
+ "'use strict'",
337
+ 'const { readFileSync } = require("node:fs")',
338
+ 'const { join } = require("node:path")',
339
+ 'const http = require("node:http")',
340
+ 'function main() {',
341
+ ' let cfg',
342
+ ' try { cfg = JSON.parse(readFileSync(join(__dirname, "term-secret.json"), "utf8")) } catch { process.exit(2) }',
343
+ ' const body = JSON.stringify({',
344
+ ' host: process.env.DSH_TS_HOST || "",',
345
+ ' port: Number(process.env.DSH_TS_PORT) || 22,',
346
+ ' username: process.env.DSH_TS_USERNAME || "",',
347
+ ' alias: process.env.DSH_TS_ALIAS || "",',
348
+ ' })',
349
+ ' const base = String(cfg.url || "").replace(/\\/+$/, "")',
350
+ ' if (!cfg.token || !base) process.exit(2)',
351
+ ' const url = new URL(base + "/dsh-remote/term-secret")',
352
+ ' const req = http.request({',
353
+ ' method: "POST", host: url.hostname, port: url.port, path: url.pathname,',
354
+ ' headers: {',
355
+ ' "content-type": "application/json",',
356
+ ' authorization: "Bearer " + cfg.token,',
357
+ ' "content-length": Buffer.byteLength(body),',
358
+ ' },',
359
+ ' timeout: 5000,',
360
+ ' }, (res) => {',
361
+ ' let buf = ""',
362
+ ' res.on("data", (chunk) => { buf += chunk })',
363
+ ' res.on("end", () => {',
364
+ ' try {',
365
+ ' const parsed = JSON.parse(buf)',
366
+ ' if (res.statusCode === 200 && parsed && parsed.ok && typeof parsed.password === "string" && parsed.password.length > 0) {',
367
+ ' process.stdout.write(parsed.password + "\\n")',
368
+ ' return',
369
+ ' }',
370
+ ' } catch { /* malformed answer */ }',
371
+ ' process.exit(3)',
372
+ ' })',
373
+ ' })',
374
+ ' req.on("timeout", () => { req.destroy(); process.exit(4) })',
375
+ ' req.on("error", () => process.exit(5))',
376
+ ' req.end(body)',
377
+ '}',
378
+ 'main()',
379
+ '',
380
+ ].join('\n')
381
+ }
382
+
383
+ /**
384
+ * Write the askpass helper + its platform wrapper next to the launcher.
385
+ * Called from writeLauncher so an upgrade rewrites both in one place.
386
+ * Carries NO secret: URL + per-boot token land in term-secret.json, written by
387
+ * the host half once the webserver origin is known (and deleted on boot when
388
+ * the composition has no webserver, so a stale bridge can never hijack the
389
+ * prompt on Desktop).
390
+ *
391
+ * @param {{ dir: string, platform?: string, nodePath?: string, fs?: object }} spec
392
+ */
393
+ export function writeTermSecretHelpers(spec) {
394
+ const platform = spec.platform || process.platform
395
+ const fs = spec.fs || { writeFileSync, chmodSync }
396
+ const node = spec.nodePath || 'node'
397
+ fs.writeFileSync(path.join(spec.dir, 'term-askpass.cjs'), askpassHelperSource(), 'utf8')
398
+ const wrapper = askpassWrapperPath(spec.dir, platform)
399
+ if (platform === 'win32') {
400
+ fs.writeFileSync(wrapper, [
401
+ '@echo off',
402
+ 'rem Generated by dsh-remote - do not edit; rewritten on every load.',
403
+ `"${node}" "%~dp0term-askpass.cjs" %*`,
404
+ '',
405
+ ].join('\r\n'), 'utf8')
406
+ } else {
407
+ fs.writeFileSync(wrapper, [
408
+ '#!/bin/sh',
409
+ '# Generated by dsh-remote - do not edit; rewritten on every load.',
410
+ `exec ${shqPosix(node)} "$(dirname -- "$0")/term-askpass.cjs" "$@"`,
411
+ '',
412
+ ].join('\n'), 'utf8')
413
+ try { fs.chmodSync(wrapper, 0o755) } catch { /* mode-less fs */ }
414
+ }
415
+ return { wrapper, helper: path.join(spec.dir, 'term-askpass.cjs') }
416
+ }
417
+
418
+ /**
419
+ * Remove a launcher left on disk under another spelling of the same name.
420
+ *
421
+ * The menu label IS the file name, so renaming the option renames the file. On
422
+ * a case-insensitive volume (NTFS, and APFS by default) writing the new spelling
423
+ * lands in the OLD directory entry and the menu keeps showing the previous
424
+ * name; on a case-sensitive one the old file would simply linger and, having
425
+ * been registered before, could still appear. Deleting the stale entry first
426
+ * makes a rename take effect on both.
427
+ *
428
+ * Best effort throughout: a launcher that cannot be cleaned up must not stop
429
+ * the new one from being written.
430
+ *
431
+ * @param {string} dir
432
+ * @param {string} keepName - basename that must survive
433
+ * @param {object} fs
434
+ */
435
+ function removeStaleLauncher(dir, keepName, fs) {
436
+ if (typeof fs.readdirSync !== 'function' || typeof fs.unlinkSync !== 'function') return
437
+ let entries
438
+ try {
439
+ entries = fs.readdirSync(dir)
440
+ } catch {
441
+ return // first run: the directory does not exist yet
442
+ }
443
+ for (const entry of entries) {
444
+ if (entry === keepName || entry.toLowerCase() !== keepName.toLowerCase()) continue
445
+ try { fs.unlinkSync(path.join(dir, entry)) } catch { /* keep going */ }
446
+ }
447
+ }
448
+
449
+ /**
450
+ * Write (or refresh) the launcher. Idempotent and cheap: the content is a pure
451
+ * function of this install's paths, so a plugin upgrade that moves the package
452
+ * rewrites the same file with the new child path.
453
+ *
454
+ * @param {{ dir: string, platform?: string, childPath: string, machinesFile: string, nodePath?: string, electronPath?: string, fs?: object }} spec
455
+ * @returns {{ path: string, source: string }}
456
+ */
457
+ export function writeLauncher(spec) {
458
+ const platform = spec.platform || process.platform
459
+ const fs = spec.fs || { mkdirSync, writeFileSync, chmodSync, readdirSync, unlinkSync }
460
+ fs.mkdirSync(spec.dir, { recursive: true })
461
+ const file = shellLauncherPath(spec.dir, platform)
462
+ // Before writing: on a case-insensitive filesystem the new name would
463
+ // otherwise be absorbed into the old entry.
464
+ removeStaleLauncher(spec.dir, path.basename(file), fs)
465
+ const source = launcherSource({ ...spec, platform })
466
+ fs.writeFileSync(file, source, 'utf8')
467
+ if (platform !== 'win32') {
468
+ try { fs.chmodSync(file, 0o755) } catch { /* a no-op on filesystems without modes */ }
469
+ }
470
+ // The credential-bridge helper travels with the launcher (same rewrite
471
+ // cadence, same directory the launcher exports as DSH_TERM_DIR).
472
+ const helpers = writeTermSecretHelpers({ dir: spec.dir, platform, nodePath: spec.nodePath || '', fs })
473
+ return { path: file, source, askpass: helpers.wrapper }
474
+ }
475
+
476
+ /**
477
+ * Add one entry to the host terminal's shell list.
478
+ *
479
+ * `shellCandidates` is the exact array `discoverShells` reads on every `shells()`
480
+ * call, so appending to it is live: the next time the user opens the shell menu
481
+ * the entry is there, and `spawn()` accepts the matching `shellPath` because it
482
+ * looks the path up in that same list. Removing it on dispose keeps the menu
483
+ * truthful when the plugin is unloaded.
484
+ *
485
+ * A host without the field (older line, or a controller rebuilt to hide the
486
+ * array) is not an error: the plugin simply contributes no shell. A host that
487
+ * HAS the field but refuses the write is a different story — that throws, so the
488
+ * caller can say why the option never appeared instead of leaving the user to
489
+ * guess.
490
+ *
491
+ * @param {object} controller - the `terminalController` service
492
+ * @param {string} candidate - absolute launcher path
493
+ * @returns {(() => void) | null} undo, or null when there is nothing to undo
494
+ * @throws {TypeError} when the host exposes a shell list that cannot be written
495
+ */
496
+ export function addShellCandidate(controller, candidate) {
497
+ const config = controller && controller.config
498
+ const list = config && config.shellCandidates
499
+ if (!Array.isArray(list)) return null
500
+ if (list.includes(candidate)) return null
501
+ list.push(candidate)
502
+ return () => {
503
+ const at = list.indexOf(candidate)
504
+ if (at >= 0) list.splice(at, 1)
505
+ }
506
+ }
507
+
508
+ /** Human-readable reason from anything thrown. */
509
+ function reason(err) {
510
+ return String((err && err.message) || err)
511
+ }
512
+
513
+ /** Read an environment variable case-insensitively, as Windows does. */
514
+ function envValue(env, name) {
515
+ if (!env) return undefined
516
+ if (env[name] !== undefined) return env[name]
517
+ const match = Object.keys(env).find((key) => key.toUpperCase() === name.toUpperCase())
518
+ return match === undefined ? undefined : env[match]
519
+ }
520
+
521
+ /**
522
+ * Claim the terminal's default shell slot when nobody else holds it.
523
+ *
524
+ * `config.shell` is what `discoverShells` puts FIRST and what a terminal spawn
525
+ * without an explicit shellPath resolves to — i.e. where a bare "open
526
+ * terminal" click lands. Pointing it at our launcher makes the default
527
+ * terminal SMART: the child script ssh'es into the remote workspace when the
528
+ * session cwd is a mirror and falls back to a local shell when it is not.
529
+ * A user-configured shell (config.shell already set) is never touched, and an
530
+ * explicit pick from the shell menu still wins (the client's remembered
531
+ * preference beats the first list entry).
532
+ *
533
+ * @param {object} controller - the terminalController service
534
+ * @param {string} launcherPath - absolute launcher path
535
+ * @returns {(() => void) | undefined} undo that only fires while the claim is still ours
536
+ */
537
+ function claimDefaultShell(controller, launcherPath) {
538
+ const config = controller && controller.config
539
+ if (!config || typeof config !== 'object') return undefined
540
+ if (config.shell !== undefined) return undefined
541
+ const ours = { path: launcherPath, name: SHELL_OPTION_NAME, args: [] }
542
+ config.shell = ours
543
+ return () => {
544
+ // Someone else (host settings, another plugin) took the slot since:
545
+ // restoring `undefined` would clobber THEIR choice.
546
+ if (config.shell === ours) config.shell = undefined
547
+ }
548
+ }
549
+
550
+ /**
551
+ * Write the launcher and put it in the terminal's shell menu.
552
+ *
553
+ * Kept out of the plugin entry so the whole contribution — write, publish,
554
+ * withdraw — can be exercised without booting the host. Every way this can
555
+ * fail to produce a visible menu entry is reported through `logger.warn`,
556
+ * because the failure mode that matters is silent: a launcher on disk plus no
557
+ * option in the menu is indistinguishable from "the feature was never built".
558
+ *
559
+ * @param {object} ctx - plugin context; only `effect`, `get('logger')` are used
560
+ * @param {object} controller - the resolved `terminalController` *service*
561
+ * @param {{ dir: string, childPath: string, machinesFile: string, platform?: string,
562
+ * nodePath?: string, electronPath?: string, electron?: boolean, logger?: object,
563
+ * env?: object, fs?: { existsSync: (p: string) => boolean },
564
+ * claimDefault?: boolean }} spec - `claimDefault: false` keeps the
565
+ * launcher menu-only (never touches `config.shell`)
566
+ * @returns {boolean} whether the option is (or already was) in the menu
567
+ */
568
+ export function installTerminalShell(ctx, controller, spec = {}) {
569
+ const logger = spec.logger !== undefined
570
+ ? spec.logger
571
+ : (ctx && typeof ctx.get === 'function' ? ctx.get('logger') : undefined)
572
+ const warn = (message) => {
573
+ try {
574
+ if (logger && typeof logger.warn === 'function') logger.warn(`dsh-remote: ${message}`)
575
+ } catch { /* a logger failure must not change the outcome */ }
576
+ }
577
+
578
+ const platform = spec.platform || process.platform
579
+ const electron = spec.electron === undefined
580
+ ? Boolean(process.versions && process.versions.electron)
581
+ : spec.electron
582
+ const nodePath = spec.nodePath === undefined
583
+ ? (runtimeNodeCandidates({
584
+ platform,
585
+ resourcesPath: process.resourcesPath,
586
+ execPath: process.execPath,
587
+ env: process.env,
588
+ electron,
589
+ })[0] || '')
590
+ : spec.nodePath
591
+ const electronPath = spec.electronPath === undefined
592
+ ? (electron ? process.execPath : '')
593
+ : spec.electronPath
594
+
595
+ let launcher
596
+ try {
597
+ launcher = writeLauncher({
598
+ dir: spec.dir,
599
+ platform,
600
+ childPath: spec.childPath,
601
+ machinesFile: spec.machinesFile,
602
+ nodePath,
603
+ electronPath,
604
+ })
605
+ } catch (err) {
606
+ // A read-only DSH_HOME must not take the plugin down: the terminal just
607
+ // keeps offering the shells it already had.
608
+ warn(`cannot write the remote terminal launcher: ${reason(err)}`)
609
+ return false
610
+ }
611
+
612
+ if (controller === undefined || controller === null) {
613
+ warn('the terminal controller is unavailable; the remote ssh option is unavailable')
614
+ return false
615
+ }
616
+ const list = controller.config && controller.config.shellCandidates
617
+ if (!Array.isArray(list)) {
618
+ // Either an older host, or the wrong object was passed in — the service is
619
+ // reached with `ctx.get('terminalController')`, not with the inject callback
620
+ // argument itself. Say which one it looks like.
621
+ const looksLikeContext = typeof controller.get === 'function' || typeof controller.inject === 'function'
622
+ warn(looksLikeContext
623
+ ? 'the terminal controller was not resolved (a plugin context was passed instead); the remote ssh option is unavailable'
624
+ : 'the terminal controller exposes no shellCandidates list; the remote ssh option is unavailable')
625
+ return false
626
+ }
627
+
628
+ // On Windows the label is the candidate's basename, so contributing a file
629
+ // path would show `remote ssh.cmd`. Contributing the bare name keeps the label
630
+ // clean, at the price of exposing the launcher directory on PATH — and only
631
+ // while the host can actually resolve that name.
632
+ const bare = shellCandidate(platform, launcher.path)
633
+ const needsPath = bare !== launcher.path
634
+ const env = spec.env || process.env
635
+ const fs = spec.fs || { existsSync }
636
+
637
+ let installed = false
638
+ const publish = () => {
639
+ // The PATH entry lives inside the effect, not outside it: if the effect ever
640
+ // re-runs, the new run must put the entry back that the previous disposal
641
+ // took away. `appendPathEntry` ref-counts, so interleaved install/dispose
642
+ // pairs cannot strand a live registration without PATH.
643
+ let restorePath
644
+ let candidate = launcher.path
645
+ // The default-shell claim uses the ABSOLUTE launcher path, never the bare
646
+ // menu name: it must keep resolving even while the PATH entry is gone.
647
+ const releaseDefault = spec.claimDefault === false
648
+ ? undefined
649
+ : claimDefaultShell(controller, launcher.path)
650
+ if (needsPath) {
651
+ try {
652
+ restorePath = appendPathEntry(path.dirname(launcher.path), env)
653
+ const found = resolveThroughPath(bare, {
654
+ platform,
655
+ pathEnv: envValue(env, 'PATH') || '',
656
+ pathExt: envValue(env, 'PATHEXT'),
657
+ fs,
658
+ })
659
+ if (found) candidate = bare
660
+ else {
661
+ // `PATHEXT` without `.CMD`, or a PATH that refuses the write. The
662
+ // option still works when contributed by absolute path; only its
663
+ // label carries the suffix.
664
+ restorePath()
665
+ restorePath = undefined
666
+ warn('the host cannot resolve the launcher by name; the remote ssh option keeps its .cmd suffix')
667
+ }
668
+ } catch (err) {
669
+ candidate = launcher.path
670
+ restorePath = undefined
671
+ warn(`the launcher directory cannot be added to PATH (${reason(err)}); the remote ssh option keeps its .cmd suffix`)
672
+ }
673
+ }
674
+ try {
675
+ const undo = addShellCandidate(controller, candidate)
676
+ installed = true
677
+ return () => {
678
+ if (undo) undo()
679
+ if (restorePath) restorePath()
680
+ if (releaseDefault) releaseDefault()
681
+ }
682
+ } catch (err) {
683
+ // The host advertises a shell list but will not take a write.
684
+ if (restorePath) restorePath()
685
+ if (releaseDefault) releaseDefault()
686
+ warn(`the terminal shell list rejected the remote shell (${reason(err)}); the remote ssh option is unavailable`)
687
+ return undefined
688
+ }
689
+ }
690
+
691
+ if (ctx && typeof ctx.effect === 'function') {
692
+ ctx.effect(publish, 'dsh-remote.terminal-shell')
693
+ } else {
694
+ publish()
695
+ }
696
+ return installed
697
+ }