dsh-remote 0.8.94 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +128 -370
  3. package/README.md +129 -355
  4. package/cordis.patch.yml +9 -9
  5. package/lib/audit.js +45 -45
  6. package/lib/auto-update.js +70 -0
  7. package/lib/binding.js +174 -172
  8. package/lib/boot.js +42 -42
  9. package/lib/client.js +6381 -4662
  10. package/lib/credential.js +277 -270
  11. package/lib/errors.js +141 -141
  12. package/lib/exec-job.js +245 -242
  13. package/lib/file-changes.js +57 -0
  14. package/lib/file-reference.js +457 -457
  15. package/lib/forwards.js +258 -258
  16. package/lib/host-api.js +822 -822
  17. package/lib/hostkey.js +108 -108
  18. package/lib/http-transport.js +201 -201
  19. package/lib/ignore.js +202 -202
  20. package/lib/index.js +4555 -4488
  21. package/lib/instructions-dynamic.js +415 -415
  22. package/lib/instructions.js +288 -288
  23. package/lib/open-folder.js +56 -56
  24. package/lib/openssh.js +950 -940
  25. package/lib/paths.js +292 -292
  26. package/lib/pool.js +1029 -1029
  27. package/lib/posix-shell.cjs +34 -34
  28. package/lib/registry.js +296 -296
  29. package/lib/remote-fs.js +179 -173
  30. package/lib/remote-git.js +127 -0
  31. package/lib/remote-sandbox.js +183 -183
  32. package/lib/remote-shell-child.cjs +460 -397
  33. package/lib/remote-shell.js +697 -697
  34. package/lib/remote-skills.js +312 -312
  35. package/lib/remote-write.js +51 -0
  36. package/lib/routes-audit.js +58 -58
  37. package/lib/routes-forwards.js +72 -72
  38. package/lib/routes-fs.js +299 -251
  39. package/lib/routes-machines.js +217 -186
  40. package/lib/routes-misc.js +187 -187
  41. package/lib/routes-term.js +169 -169
  42. package/lib/routes-update.js +147 -143
  43. package/lib/routes-web-attach.js +121 -112
  44. package/lib/routes-workspace.js +325 -312
  45. package/lib/search.js +235 -235
  46. package/lib/self-heal.js +130 -130
  47. package/lib/sftp-surface.js +119 -119
  48. package/lib/sshconfig.js +779 -779
  49. package/lib/sync-status.js +31 -0
  50. package/lib/sync.js +350 -350
  51. package/lib/tasks.js +95 -95
  52. package/lib/telemetry.js +247 -247
  53. package/lib/terminal.js +205 -205
  54. package/lib/tui/flow.js +130 -130
  55. package/lib/tui/format.js +380 -380
  56. package/lib/tui/i18n.js +350 -350
  57. package/lib/tui/index.js +531 -531
  58. package/lib/tui/provider.js +344 -344
  59. package/lib/tui/scene.js +986 -986
  60. package/lib/update.js +497 -490
  61. package/lib/vendor/jsdiff/LICENSE +29 -0
  62. package/lib/vendor/jsdiff/SOURCE.md +4 -0
  63. package/lib/vendor/jsdiff/diff/base.js +254 -0
  64. package/lib/vendor/jsdiff/diff/line.js +66 -0
  65. package/lib/vendor/jsdiff/patch/create.js +229 -0
  66. package/lib/vendor/jsdiff/util/params.js +15 -0
  67. package/lib/web-attach.js +1081 -860
  68. package/lib/workspace-cleanup.js +337 -337
  69. package/lib/workspace-search.js +219 -0
  70. package/node_modules/buildcheck/.eslintrc.js +5 -0
  71. package/node_modules/buildcheck/.github/workflows/ci.yml +88 -0
  72. package/node_modules/buildcheck/.github/workflows/lint.yml +27 -0
  73. package/node_modules/buildcheck/.npmignore +3 -0
  74. package/node_modules/buildcheck/LICENSE +19 -0
  75. package/node_modules/buildcheck/README.md +106 -0
  76. package/node_modules/buildcheck/deps/Find-VisualStudio.cs +250 -0
  77. package/node_modules/buildcheck/lib/findvs.js +361 -0
  78. package/node_modules/buildcheck/lib/index.js +738 -0
  79. package/node_modules/buildcheck/package.json +36 -0
  80. package/node_modules/buildcheck/test/test.js +8 -0
  81. package/node_modules/cpu-features/.eslintrc.js +5 -0
  82. package/node_modules/cpu-features/.github/workflows/ci.yml +74 -0
  83. package/node_modules/cpu-features/.github/workflows/lint.yml +27 -0
  84. package/node_modules/cpu-features/LICENSE +19 -0
  85. package/node_modules/cpu-features/README.md +59 -0
  86. package/node_modules/cpu-features/binding.gyp +16 -0
  87. package/node_modules/cpu-features/buildcheck.js +32 -0
  88. package/node_modules/cpu-features/deps/cpu_features/.clang-format +4 -0
  89. package/node_modules/cpu-features/deps/cpu_features/.dockerignore +31 -0
  90. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/Dockerfile +5 -0
  91. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/aarch64_linux_cmake.yml +30 -0
  92. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_freebsd_cmake.yml +22 -0
  93. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_bazel.yml +26 -0
  94. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_linux_cmake.yml +31 -0
  95. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_macos_cmake.yml +43 -0
  96. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/amd64_windows_cmake.yml +25 -0
  97. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/arm_linux_cmake.yml +31 -0
  98. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/clang_format.yml +24 -0
  99. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/mips_linux_cmake.yml +30 -0
  100. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/power_linux_cmake.yml +29 -0
  101. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/riscv_linux_cmake.yml +28 -0
  102. package/node_modules/cpu-features/deps/cpu_features/.github/workflows/s390x_linux_cmake.yml +27 -0
  103. package/node_modules/cpu-features/deps/cpu_features/.grenrc.yml +21 -0
  104. package/node_modules/cpu-features/deps/cpu_features/BUILD.bazel +329 -0
  105. package/node_modules/cpu-features/deps/cpu_features/CMakeLists.txt +261 -0
  106. package/node_modules/cpu-features/deps/cpu_features/CONTRIBUTING.md +23 -0
  107. package/node_modules/cpu-features/deps/cpu_features/LICENSE +230 -0
  108. package/node_modules/cpu-features/deps/cpu_features/README.md +272 -0
  109. package/node_modules/cpu-features/deps/cpu_features/WORKSPACE +19 -0
  110. package/node_modules/cpu-features/deps/cpu_features/bazel/ci/README.md +5 -0
  111. package/node_modules/cpu-features/deps/cpu_features/bazel/platforms.bzl +11 -0
  112. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesConfig.cmake.in +3 -0
  113. package/node_modules/cpu-features/deps/cpu_features/cmake/CpuFeaturesNdkCompatConfig.cmake.in +3 -0
  114. package/node_modules/cpu-features/deps/cpu_features/cmake/README.md +30 -0
  115. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/Makefile +252 -0
  116. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/README.md +40 -0
  117. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.dot +64 -0
  118. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/docker.svg +312 -0
  119. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/doc/generate_image.sh +7 -0
  120. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/amd64/Dockerfile +48 -0
  121. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/docker/toolchain/Dockerfile +34 -0
  122. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/CMakeLists.txt +22 -0
  123. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/sample/main.cpp +11 -0
  124. package/node_modules/cpu-features/deps/cpu_features/cmake/ci/vagrant/freebsd/Vagrantfile +107 -0
  125. package/node_modules/cpu-features/deps/cpu_features/cmake/googletest.CMakeLists.txt.in +15 -0
  126. package/node_modules/cpu-features/deps/cpu_features/cpu_features.gyp +105 -0
  127. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_cache_info.h +54 -0
  128. package/node_modules/cpu-features/deps/cpu_features/include/cpu_features_macros.h +384 -0
  129. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_aarch64.h +259 -0
  130. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_arm.h +121 -0
  131. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_mips.h +74 -0
  132. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_ppc.h +149 -0
  133. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_riscv.h +72 -0
  134. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_s390x.h +108 -0
  135. package/node_modules/cpu-features/deps/cpu_features/include/cpuinfo_x86.h +288 -0
  136. package/node_modules/cpu-features/deps/cpu_features/include/internal/bit_utils.h +40 -0
  137. package/node_modules/cpu-features/deps/cpu_features/include/internal/cpuid_x86.h +37 -0
  138. package/node_modules/cpu-features/deps/cpu_features/include/internal/filesystem.h +39 -0
  139. package/node_modules/cpu-features/deps/cpu_features/include/internal/hwcaps.h +240 -0
  140. package/node_modules/cpu-features/deps/cpu_features/include/internal/stack_line_reader.h +49 -0
  141. package/node_modules/cpu-features/deps/cpu_features/include/internal/string_view.h +110 -0
  142. package/node_modules/cpu-features/deps/cpu_features/include/internal/windows_utils.h +70 -0
  143. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/CMakeLists.txt +60 -0
  144. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/README.md +4 -0
  145. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.c +205 -0
  146. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/cpu-features.h +320 -0
  147. package/node_modules/cpu-features/deps/cpu_features/ndk_compat/ndk-compat-test.c +12 -0
  148. package/node_modules/cpu-features/deps/cpu_features/patches/0001-Add-Apple-Silicon-Support.patch +456 -0
  149. package/node_modules/cpu-features/deps/cpu_features/scripts/generate_badges.d +165 -0
  150. package/node_modules/cpu-features/deps/cpu_features/scripts/make_release.sh +75 -0
  151. package/node_modules/cpu-features/deps/cpu_features/scripts/run_integration.sh +490 -0
  152. package/node_modules/cpu-features/deps/cpu_features/scripts/test_integration.sh +79 -0
  153. package/node_modules/cpu-features/deps/cpu_features/src/copy.inl +19 -0
  154. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection.inl +86 -0
  155. package/node_modules/cpu-features/deps/cpu_features/src/define_introspection_and_hwcaps.inl +26 -0
  156. package/node_modules/cpu-features/deps/cpu_features/src/equals.inl +22 -0
  157. package/node_modules/cpu-features/deps/cpu_features/src/filesystem.c +62 -0
  158. package/node_modules/cpu-features/deps/cpu_features/src/hwcaps.c +169 -0
  159. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64__base_implementation.inl +88 -0
  160. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_linux_or_android.c +79 -0
  161. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_macos_or_iphone.c +82 -0
  162. package/node_modules/cpu-features/deps/cpu_features/src/impl_aarch64_windows.c +138 -0
  163. package/node_modules/cpu-features/deps/cpu_features/src/impl_arm_linux_or_android.c +212 -0
  164. package/node_modules/cpu-features/deps/cpu_features/src/impl_mips_linux_or_android.c +93 -0
  165. package/node_modules/cpu-features/deps/cpu_features/src/impl_ppc_linux.c +163 -0
  166. package/node_modules/cpu-features/deps/cpu_features/src/impl_riscv_linux.c +111 -0
  167. package/node_modules/cpu-features/deps/cpu_features/src/impl_s390x_linux.c +120 -0
  168. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86__base_implementation.inl +2055 -0
  169. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_freebsd.c +68 -0
  170. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_linux_or_android.c +58 -0
  171. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_macos.c +57 -0
  172. package/node_modules/cpu-features/deps/cpu_features/src/impl_x86_windows.c +58 -0
  173. package/node_modules/cpu-features/deps/cpu_features/src/stack_line_reader.c +132 -0
  174. package/node_modules/cpu-features/deps/cpu_features/src/string_view.c +192 -0
  175. package/node_modules/cpu-features/deps/cpu_features/src/utils/list_cpu_features.c +461 -0
  176. package/node_modules/cpu-features/deps/cpu_features/test/CMakeLists.txt +114 -0
  177. package/node_modules/cpu-features/deps/cpu_features/test/bit_utils_test.cc +53 -0
  178. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_aarch64_test.cc +396 -0
  179. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_arm_test.cc +384 -0
  180. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_mips_test.cc +176 -0
  181. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_ppc_test.cc +131 -0
  182. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_riscv_test.cc +180 -0
  183. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_s390x_test.cc +82 -0
  184. package/node_modules/cpu-features/deps/cpu_features/test/cpuinfo_x86_test.cc +1729 -0
  185. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.cc +103 -0
  186. package/node_modules/cpu-features/deps/cpu_features/test/filesystem_for_testing.h +61 -0
  187. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.cc +52 -0
  188. package/node_modules/cpu-features/deps/cpu_features/test/hwcaps_for_testing.h +31 -0
  189. package/node_modules/cpu-features/deps/cpu_features/test/stack_line_reader_test.cc +132 -0
  190. package/node_modules/cpu-features/deps/cpu_features/test/string_view_test.cc +202 -0
  191. package/node_modules/cpu-features/lib/index.js +5 -0
  192. package/node_modules/cpu-features/package.json +40 -0
  193. package/node_modules/cpu-features/src/binding.cc +151 -0
  194. package/node_modules/cpu-features/test/test.js +12 -0
  195. package/node_modules/nan/tools/1to2.js +0 -0
  196. package/package.json +107 -103
@@ -1,397 +1,460 @@
1
- #!/usr/bin/env node
2
- /**
3
- * The program the host terminal runs when the user picks the "Remote SSH" shell.
4
- *
5
- * It is started by a generated launcher (see `remote-shell.js`) inside the
6
- * session's working directory, resolves which remote checkout that directory
7
- * belongs to, and then replaces itself with `ssh`. Inheriting stdio is the whole
8
- * point: the local pty stays in charge of the screen, so resize and key handling
9
- * keep working without this script knowing anything about terminals.
10
- *
11
- * Plain CommonJS on purpose: it is spawned as a standalone script, and it must
12
- * not depend on how the plugin package itself is loaded.
13
- */
14
-
15
- 'use strict'
16
-
17
- const { spawn } = require('node:child_process')
18
- const { existsSync, fstatSync, readFileSync } = require('node:fs')
19
- const path = require('node:path')
20
- const { posixViaSh, quotePosix } = require('./posix-shell.cjs')
21
-
22
- /** Name of the marker the host half writes into every local mirror root. */
23
- const META_FILE = '.dsh-remote-meta.json'
24
- /** How far up from the working directory a marker may be found. */
25
- const MAX_WALK_UP = 12
26
-
27
- /**
28
- * Read and parse a JSON file, returning undefined for anything unusable.
29
- * @param {string} file
30
- * @returns {any}
31
- */
32
- function readJson(file) {
33
- try {
34
- return JSON.parse(readFileSync(file, 'utf8'))
35
- } catch {
36
- return undefined
37
- }
38
- }
39
-
40
- /**
41
- * Find the mirror root that contains `cwd` by walking upwards for the marker.
42
- * @param {string} cwd - session working directory
43
- * @param {{ exists?: (p: string) => boolean, readJsonFile?: (p: string) => any, maxUp?: number }} deps
44
- * @returns {{ dir: string, meta: object } | null}
45
- */
46
- function findMirror(cwd, deps = {}) {
47
- const exists = deps.exists || ((p) => existsSync(p))
48
- const read = deps.readJsonFile || readJson
49
- const maxUp = deps.maxUp || MAX_WALK_UP
50
- let dir = path.resolve(cwd || '.')
51
- for (let depth = 0; depth <= maxUp; depth += 1) {
52
- const marker = path.join(dir, META_FILE)
53
- if (exists(marker)) {
54
- const meta = read(marker)
55
- if (meta && typeof meta === 'object' && meta.host) return { dir, meta }
56
- }
57
- const parent = path.dirname(dir)
58
- if (parent === dir) break
59
- dir = parent
60
- }
61
- return null
62
- }
63
-
64
- /**
65
- * Pick the saved connection that owns a mirror.
66
- *
67
- * The marker records the SSH alias when the machine was saved from
68
- * `~/.ssh/config` (issue #38), so the alias is the most precise key; otherwise
69
- * host + user + port identify it. A missing entry is not fatal — the marker
70
- * alone is enough to connect, and ssh will use its own defaults for the key.
71
- *
72
- * @param {object} meta - mirror marker
73
- * @param {{ list?: object[] }} registry - parsed `machines.json`
74
- * @returns {object | undefined}
75
- */
76
- function matchMachine(meta, registry) {
77
- const list = registry && Array.isArray(registry.list) ? registry.list : []
78
- const port = Number(meta.port || 22)
79
- if (meta.alias) {
80
- const byAlias = list.find((m) => m && m.host === meta.alias)
81
- if (byAlias) return byAlias
82
- }
83
- return list.find((m) => m && m.host === meta.host
84
- && String(m.username || '') === String(meta.username || '')
85
- && Number(m.port || 22) === port)
86
- }
87
-
88
- // Paths and the outer sh -c boundary share the same POSIX quoting rules.
89
- // WebAttach uses this same helper so both generated command paths quote identically.
90
- /**
91
- * Build the `cd` half of the remote command, keeping `~` for the *remote* shell
92
- * to expand: the local home is not the remote home, so expanding it here would
93
- * silently land in the wrong directory.
94
- * @param {string} remotePath
95
- * @returns {string}
96
- */
97
- function remoteCd(remotePath) {
98
- const raw = String(remotePath || '').trim()
99
- if (raw === '' || raw === '~') return 'cd "$HOME"'
100
- if (raw === '~/') return 'cd "$HOME"'
101
- if (raw.startsWith('~/')) return 'cd "$HOME"/' + quotePosix(raw.slice(2))
102
- return 'cd ' + quotePosix(raw)
103
- }
104
-
105
- /**
106
- * The remote command: land in the workspace, then hand over to a login shell.
107
- *
108
- * `exec` keeps the pty attached to a single interactive shell, so the exit code
109
- * the terminal sees is the shell's own, and a deleted workspace falls back to
110
- * `$HOME` instead of leaving a broken terminal. The POSIX script goes through
111
- * `sh -c` because sshd otherwise hands it to a possibly non-POSIX login shell
112
- * (fish/csh); the final interactive shell is still the user's own `$SHELL`.
113
- *
114
- * @param {string} remotePath
115
- * @returns {string}
116
- */
117
- function remoteCommand(remotePath) {
118
- const script = `${remoteCd(remotePath)} 2>/dev/null || cd "$HOME"; exec "\${SHELL:-/bin/bash}" -l`
119
- return posixViaSh(script)
120
- }
121
-
122
- /** Absolute Windows path: `D:\x`, `D:/x`, or a `\\server\share` UNC path.
123
- * These cannot be the operand of a POSIX `cd`. */
124
- const WINDOWS_REMOTE_PATH = /^(?:[a-zA-Z]:[\\/]|\\\\)/
125
-
126
- /**
127
- * Whether a remote workspace path is a Windows one.
128
- *
129
- * A Windows remote speaks cmd or PowerShell in its default shell, so the POSIX
130
- * `cd … || …; exec "$SHELL"` line would fail outright there — `2>/dev/null`,
131
- * `||` and `exec` are not cmd syntax at all. The marker records no remote
132
- * platform, but the path form is unambiguous: `/srv/x` and `~/x` are POSIX,
133
- * while `D:\x` and `\\server\share` are not valid POSIX paths.
134
- *
135
- * @param {string} p - `remotePath` from the mirror marker
136
- * @returns {boolean}
137
- */
138
- function isWindowsRemotePath(p) {
139
- return WINDOWS_REMOTE_PATH.test(String(p || '').trim())
140
- }
141
-
142
- /**
143
- * Argument list (without the ssh binary) for one connection.
144
- *
145
- * `-tt` is mandatory: the terminal needs a tty even though a command is given,
146
- * otherwise the shell comes up non-interactive and every key press is ignored.
147
- * Options are pushed in order and never spliced between an `-o` and its value —
148
- * an inserted `-J` there once reached ssh as the value of `-o`, which aborted
149
- * every connection that used a jump host (issue #21).
150
- *
151
- * @param {object} target - `{ host, port, username, alias, remotePath }`
152
- * @param {object} [machine] - saved connection, for the key and transport hints
153
- * @returns {string[]}
154
- */
155
- function buildSshArgs(target, machine) {
156
- const args = ['-tt']
157
- const alias = target.alias || (machine && machine.useSshConfig ? machine.host : '')
158
- if (alias) {
159
- args.push(String(alias))
160
- } else {
161
- const port = Number(target.port || (machine && machine.port) || 22)
162
- if (port !== 22) args.push('-p', String(port))
163
- const key = machine && machine.privateKeyPath
164
- if (key && !machine.useAgent) args.push('-i', String(key))
165
- const user = target.username || (machine && machine.username) || ''
166
- args.push(user ? `${user}@${target.host}` : String(target.host))
167
- }
168
- // A Windows workspace cannot be reached with the POSIX line: the remote's
169
- // default shell may be cmd or PowerShell, and picking one would be a guess.
170
- // Opening ssh with no command leaves the remote's own default shell in charge,
171
- // so the terminal still works; only the automatic `cd` is given up.
172
- if (!isWindowsRemotePath(target.remotePath)) args.push(remoteCommand(target.remotePath))
173
- return args
174
- }
175
-
176
- /**
177
- * Prefer the OS OpenSSH binary on Windows. A PATH lookup there can reach an
178
- * MSYS2/git-bash `ssh`, which resolves `~/.ssh` against a different home and
179
- * makes keys saved by the host half look missing.
180
- * @param {string} [platform]
181
- * @param {object} [env]
182
- * @param {(p: string) => boolean} [exists]
183
- * @returns {string}
184
- */
185
- function sshBinary(platform = process.platform, env = process.env, exists = existsSync) {
186
- if (platform === 'win32') {
187
- const system = env.SystemRoot || env.windir || 'C:\\Windows'
188
- const native = path.join(system, 'System32', 'OpenSSH', 'ssh.exe')
189
- if (exists(native)) return native
190
- }
191
- return 'ssh'
192
- }
193
-
194
- /**
195
- * The shell to fall back to when this directory is not a remote checkout.
196
- * @param {string} [platform]
197
- * @param {object} [env]
198
- * @returns {string}
199
- */
200
- function localShell(platform = process.platform, env = process.env) {
201
- if (platform === 'win32') return env.ComSpec || 'cmd.exe'
202
- return env.SHELL || '/bin/sh'
203
- }
204
-
205
- /**
206
- * Parse the arguments the launcher passes.
207
- * @param {string[]} argv
208
- * @returns {{ machines?: string }}
209
- */
210
- function parseArgs(argv) {
211
- const out = {}
212
- for (let i = 0; i < argv.length; i += 1) {
213
- if (argv[i] === '--machines' && argv[i + 1]) {
214
- out.machines = argv[i + 1]
215
- i += 1
216
- }
217
- }
218
- return out
219
- }
220
-
221
- /**
222
- * Resolve everything needed to connect from a working directory.
223
- * @param {{ cwd?: string, machines?: string, exists?: Function, readJsonFile?: Function }} input
224
- * @returns {{ target?: object, machine?: object, found: boolean }}
225
- */
226
- function resolveTarget(input = {}) {
227
- const cwd = input.cwd || process.cwd()
228
- const mirror = findMirror(cwd, input)
229
- if (!mirror) return { found: false }
230
- const registry = input.machines ? (input.readJsonFile || readJson)(input.machines) : undefined
231
- const machine = matchMachine(mirror.meta, registry)
232
- const target = {
233
- host: mirror.meta.host,
234
- port: mirror.meta.port || (machine && machine.port) || 22,
235
- username: mirror.meta.username || (machine && machine.username) || '',
236
- alias: mirror.meta.alias || '',
237
- remotePath: mirror.meta.remotePath || (machine && machine.workspace) || '',
238
- }
239
- return { found: true, target, machine, dir: mirror.dir }
240
- }
241
-
242
- /**
243
- * Whether stdin is a console this process can actually receive keys from.
244
- *
245
- * A terminal that inherits stdio from `ELECTRON_RUN_AS_NODE` gets pipes, not
246
- * the ConPTY console: output flows while every keystroke is dropped, leaving a
247
- * tab that looks alive and accepts nothing (issue #91). Detecting that here
248
- * turns a silent dead end into an explicit, actionable refusal. `isTTY` is the
249
- * cheap check; `fstat(0)` catches runtimes that never set the flag.
250
- *
251
- * @param {{ stdin?: object, fstat?: (fd: number) => any }} [deps]
252
- * @returns {boolean}
253
- */
254
- function stdinIsInteractive(deps = {}) {
255
- const stdin = deps.stdin === undefined ? process.stdin : deps.stdin
256
- const fstat = deps.fstat || fstatSync
257
- if (stdin && stdin.isTTY === true) return true
258
- try {
259
- const stat = fstat(0)
260
- return Boolean(stat && typeof stat.isCharacterDevice === 'function' && stat.isCharacterDevice())
261
- } catch {
262
- return false
263
- }
264
- }
265
-
266
- /**
267
- * Whether the machine's password auth needs (and can use) the credential
268
- * bridge. Keys, agents and ssh-config aliases authenticate without us;
269
- * keyboard-interactive (OTP) prompts are per-login and must stay on the tty;
270
- * everything else with a stored credential (plaintext registry or OS keychain)
271
- * goes through the bridge.
272
- *
273
- * @param {object|undefined} machine - the matched registry record.
274
- * @returns {boolean}
275
- */
276
- function needsAskpass(machine) {
277
- if (!machine) return false
278
- if (machine.useAgent || machine.useSshConfig || machine.keyboardInteractive) return false
279
- if (String(machine.privateKeyPath || '')) return false
280
- if (String(machine.password || '')) return true
281
- return Boolean(machine.credentialBackend && machine.credentialBackend !== 'plain')
282
- }
283
-
284
- /**
285
- * Environment additions that route ssh's password prompt to the bridge helper.
286
- * Only applied when needsAskpass() held AND the payload file exists.
287
- *
288
- * `SSH_ASKPASS_REQUIRE=force` (OpenSSH ≥ 8.4) is what makes askpass run at all
289
- * on a tty; DISPLAY feeds prehistoric ssh builds. DSH_TS_* carries the machine
290
- * identity to the helper through the process environment.
291
- *
292
- * @param {object} machine
293
- * @param {string} termDir - the launcher's directory (DSH_TERM_DIR).
294
- * @param {string} [platform]
295
- * @returns {object} env entries to merge over process.env
296
- */
297
- function askpassEnv(machine, termDir, platform = process.platform) {
298
- const wrapper = path.join(termDir, platform === 'win32' ? 'term-askpass.cmd' : 'term-askpass')
299
- return {
300
- SSH_ASKPASS: wrapper,
301
- SSH_ASKPASS_REQUIRE: 'force',
302
- DISPLAY: process.env.DISPLAY || 'dsh-remote:0',
303
- DSH_TS_HOST: String(machine.host || ''),
304
- DSH_TS_PORT: String(Number(machine.port) || 22),
305
- DSH_TS_USERNAME: String(machine.username || ''),
306
- DSH_TS_ALIAS: String(machine.alias || ''),
307
- }
308
- }
309
-
310
- /**
311
- * Hand the current process over to `file args…`, propagating the exit code.
312
- * @param {string} file
313
- * @param {string[]} args
314
- * @param {object} [extraEnv] - env entries merged over process.env (askpass).
315
- * @returns {import('node:child_process').ChildProcess}
316
- */
317
- function handover(file, args, extraEnv) {
318
- const child = spawn(file, args, { stdio: 'inherit', env: extraEnv ? { ...process.env, ...extraEnv } : process.env })
319
- child.on('error', (error) => {
320
- process.stderr.write(`[dsh-remote] cannot run ${file}: ${error && error.message}\n`)
321
- process.exit(127)
322
- })
323
- child.on('exit', (code, signal) => {
324
- if (signal) process.kill(process.pid, signal)
325
- else process.exit(code == null ? 0 : code)
326
- })
327
- return child
328
- }
329
-
330
- /**
331
- * Entry point: connect, or explain why a local shell was used instead.
332
- * @param {string[]} [argv]
333
- * @param {{ cwd?: string, platform?: string, env?: object,
334
- * stdin?: object, fstat?: (fd: number) => any,
335
- * write?: (line: string) => void, exit?: (code: number) => any }} [deps]
336
- */
337
- function main(argv = process.argv.slice(2), deps = {}) {
338
- const platform = deps.platform || process.platform
339
- const env = deps.env || process.env
340
- const write = deps.write || ((line) => process.stderr.write(line))
341
- const exit = deps.exit || ((code) => process.exit(code))
342
- if (!stdinIsInteractive(deps)) {
343
- // Anything we could hand over to — ssh, cmd, sh — reads stdin the same
344
- // way, so there is no useful fallback here: the tab would render the
345
- // remote prompt and ignore every key. Refuse loudly instead (issue #91).
346
- write('[dsh-remote] this terminal cannot receive input: stdin is not a real console.\n')
347
- write('[dsh-remote] point DSH_REMOTE_TERMINAL_NODE at an absolute node.exe path and restart, so the launcher does not have to reuse the app runtime.\n')
348
- write('[dsh-remote] 终端无法接收输入(stdin 不是真实控制台)。请把 DSH_REMOTE_TERMINAL_NODE 指向 node.exe 的绝对路径后重启。\n')
349
- exit(126)
350
- return undefined
351
- }
352
- const options = parseArgs(argv)
353
- const resolved = resolveTarget({ cwd: deps.cwd || process.cwd(), machines: options.machines })
354
- if (!resolved.found) {
355
- process.stderr.write('[dsh-remote] this directory is not a remote workspace; opening a local shell.\n')
356
- process.stderr.write('[dsh-remote] 当前目录不是远程工作区,已打开本地终端。\n')
357
- return handover(localShell(platform, env), platform === 'win32' ? [] : ['-l'])
358
- }
359
- const ssh = sshBinary(platform, env)
360
- const args = buildSshArgs(resolved.target, resolved.machine)
361
- const user = resolved.target.username || (resolved.machine && resolved.machine.username) || ''
362
- process.stderr.write(`[dsh-remote] connecting to ${user ? user + '@' : ''}${resolved.target.host}…\n`)
363
- if (isWindowsRemotePath(resolved.target.remotePath)) {
364
- process.stderr.write('[dsh-remote] the remote workspace is a Windows path; opening the remote default shell without changing directory.\n')
365
- process.stderr.write('[dsh-remote] 远端工作区是 Windows 路径,已打开默认 shell(未自动切换目录)。\n')
366
- }
367
- // Saved-password bridge: when the machine needs password auth and the host
368
- // wrote the bridge payload (Web composition only), answer ssh's password
369
- // prompt through the plugin's credential chain instead of the tty.
370
- const termDir = env.DSH_TERM_DIR || ''
371
- if (termDir && needsAskpass(resolved.machine) && existsSync(path.join(termDir, 'term-secret.json'))) {
372
- process.stderr.write('[dsh-remote] using the saved password via the local credential bridge.\n')
373
- process.stderr.write('[dsh-remote] 已保存的密码将通过本机凭据桥自动应答。\n')
374
- return handover(ssh, args, askpassEnv(resolved.machine, termDir, platform))
375
- }
376
- return handover(ssh, args)
377
- }
378
-
379
- module.exports = {
380
- META_FILE,
381
- askpassEnv,
382
- buildSshArgs,
383
- findMirror,
384
- needsAskpass,
385
- isWindowsRemotePath,
386
- localShell,
387
- main,
388
- matchMachine,
389
- parseArgs,
390
- remoteCd,
391
- remoteCommand,
392
- resolveTarget,
393
- sshBinary,
394
- stdinIsInteractive,
395
- }
396
-
397
- if (require.main === module) main()
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The program the host terminal runs when the user picks the "Remote SSH" shell.
4
+ *
5
+ * It is started by a generated launcher (see `remote-shell.js`) inside the
6
+ * session's working directory, resolves which remote checkout that directory
7
+ * belongs to, and then replaces itself with `ssh`. Inheriting stdio is the whole
8
+ * point: the local pty stays in charge of the screen, so resize and key handling
9
+ * keep working without this script knowing anything about terminals.
10
+ *
11
+ * Plain CommonJS on purpose: it is spawned as a standalone script, and it must
12
+ * not depend on how the plugin package itself is loaded.
13
+ */
14
+
15
+ 'use strict'
16
+
17
+ const { spawn } = require('node:child_process')
18
+ const { existsSync, fstatSync, readFileSync } = require('node:fs')
19
+ const path = require('node:path')
20
+ const { posixViaSh, quotePosix } = require('./posix-shell.cjs')
21
+
22
+ /** Name of the marker the host half writes into every local mirror root. */
23
+ const META_FILE = '.dsh-remote-meta.json'
24
+ /** How far up from the working directory a marker may be found. */
25
+ const MAX_WALK_UP = 12
26
+
27
+ /**
28
+ * Read and parse a JSON file, returning undefined for anything unusable.
29
+ * @param {string} file
30
+ * @returns {any}
31
+ */
32
+ function readJson(file) {
33
+ try {
34
+ return JSON.parse(readFileSync(file, 'utf8'))
35
+ } catch {
36
+ return undefined
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Find the mirror root that contains `cwd` by walking upwards for the marker.
42
+ * @param {string} cwd - session working directory
43
+ * @param {{ exists?: (p: string) => boolean, readJsonFile?: (p: string) => any, maxUp?: number }} deps
44
+ * @returns {{ dir: string, meta: object } | null}
45
+ */
46
+ function findMirror(cwd, deps = {}) {
47
+ const exists = deps.exists || ((p) => existsSync(p))
48
+ const read = deps.readJsonFile || readJson
49
+ const maxUp = deps.maxUp || MAX_WALK_UP
50
+ let dir = path.resolve(cwd || '.')
51
+ for (let depth = 0; depth <= maxUp; depth += 1) {
52
+ const marker = path.join(dir, META_FILE)
53
+ if (exists(marker)) {
54
+ const meta = read(marker)
55
+ if (meta && typeof meta === 'object' && meta.host) return { dir, meta }
56
+ }
57
+ const parent = path.dirname(dir)
58
+ if (parent === dir) break
59
+ dir = parent
60
+ }
61
+ return null
62
+ }
63
+
64
+ /**
65
+ * Pick the saved connection that owns a mirror.
66
+ *
67
+ * The marker records the SSH alias when the machine was saved from
68
+ * `~/.ssh/config` (issue #38), so the alias is the most precise key; otherwise
69
+ * host + user + port identify it. A missing entry is not fatal — the marker
70
+ * alone is enough to connect, and ssh will use its own defaults for the key.
71
+ *
72
+ * @param {object} meta - mirror marker
73
+ * @param {{ list?: object[] }} registry - parsed `machines.json`
74
+ * @returns {object | undefined}
75
+ */
76
+ function matchMachine(meta, registry) {
77
+ const list = registry && Array.isArray(registry.list) ? registry.list : []
78
+ const port = Number(meta.port || 22)
79
+ if (meta.alias) {
80
+ const byAlias = list.find((m) => m && m.host === meta.alias)
81
+ if (byAlias) return byAlias
82
+ }
83
+ return list.find((m) => m && m.host === meta.host
84
+ && String(m.username || '') === String(meta.username || '')
85
+ && Number(m.port || 22) === port)
86
+ }
87
+
88
+ // Paths and the outer sh -c boundary share the same POSIX quoting rules.
89
+ // WebAttach uses this same helper so both generated command paths quote identically.
90
+ /**
91
+ * Build the `cd` half of the remote command, keeping `~` for the *remote* shell
92
+ * to expand: the local home is not the remote home, so expanding it here would
93
+ * silently land in the wrong directory.
94
+ * @param {string} remotePath
95
+ * @returns {string}
96
+ */
97
+ function remoteCd(remotePath) {
98
+ const raw = String(remotePath || '').trim()
99
+ if (raw === '' || raw === '~') return 'cd "$HOME"'
100
+ if (raw === '~/') return 'cd "$HOME"'
101
+ if (raw.startsWith('~/')) return 'cd "$HOME"/' + quotePosix(raw.slice(2))
102
+ return 'cd ' + quotePosix(raw)
103
+ }
104
+
105
+ /**
106
+ * The remote command: land in the workspace, then hand over to a login shell.
107
+ *
108
+ * `exec` keeps the pty attached to a single interactive shell, so the exit code
109
+ * the terminal sees is the shell's own, and a deleted workspace falls back to
110
+ * `$HOME` instead of leaving a broken terminal. The POSIX script goes through
111
+ * `sh -c` because sshd otherwise hands it to a possibly non-POSIX login shell
112
+ * (fish/csh); the final interactive shell is still the user's own `$SHELL`.
113
+ *
114
+ * @param {string} remotePath
115
+ * @returns {string}
116
+ */
117
+ function remoteCommand(remotePath) {
118
+ const script = `${remoteCd(remotePath)} 2>/dev/null || cd "$HOME"; exec "\${SHELL:-/bin/bash}" -l`
119
+ return posixViaSh(script)
120
+ }
121
+
122
+ /** Absolute Windows path: `D:\x`, `D:/x`, or a `\\server\share` UNC path.
123
+ * These cannot be the operand of a POSIX `cd`. */
124
+ const WINDOWS_REMOTE_PATH = /^(?:[a-zA-Z]:[\\/]|\\\\)/
125
+
126
+ /**
127
+ * Whether a remote workspace path is a Windows one.
128
+ *
129
+ * A Windows remote speaks cmd or PowerShell in its default shell, so the POSIX
130
+ * `cd … || …; exec "$SHELL"` line would fail outright there — `2>/dev/null`,
131
+ * `||` and `exec` are not cmd syntax at all. The marker records no remote
132
+ * platform, but the path form is unambiguous: `/srv/x` and `~/x` are POSIX,
133
+ * while `D:\x` and `\\server\share` are not valid POSIX paths.
134
+ *
135
+ * @param {string} p - `remotePath` from the mirror marker
136
+ * @returns {boolean}
137
+ */
138
+ function isWindowsRemotePath(p) {
139
+ return WINDOWS_REMOTE_PATH.test(String(p || '').trim())
140
+ }
141
+
142
+ /**
143
+ * Argument list (without the ssh binary) for one connection.
144
+ *
145
+ * `-tt` is mandatory: the terminal needs a tty even though a command is given,
146
+ * otherwise the shell comes up non-interactive and every key press is ignored.
147
+ * Options are pushed in order and never spliced between an `-o` and its value —
148
+ * an inserted `-J` there once reached ssh as the value of `-o`, which aborted
149
+ * every connection that used a jump host (issue #21).
150
+ *
151
+ * @param {object} target - `{ host, port, username, alias, remotePath }`
152
+ * @param {object} [machine] - saved connection, for the key and transport hints
153
+ * @returns {string[]}
154
+ */
155
+ function buildSshArgs(target, machine) {
156
+ const args = ['-tt']
157
+ const alias = target.alias || (machine && machine.useSshConfig ? machine.host : '')
158
+ if (alias) {
159
+ args.push(String(alias))
160
+ } else {
161
+ const port = Number(target.port || (machine && machine.port) || 22)
162
+ if (port !== 22) args.push('-p', String(port))
163
+ const key = machine && machine.privateKeyPath
164
+ if (key && !machine.useAgent) args.push('-i', String(key))
165
+ const user = target.username || (machine && machine.username) || ''
166
+ args.push(user ? `${user}@${target.host}` : String(target.host))
167
+ }
168
+ // A Windows workspace cannot be reached with the POSIX line: the remote's
169
+ // default shell may be cmd or PowerShell, and picking one would be a guess.
170
+ // Opening ssh with no command leaves the remote's own default shell in charge,
171
+ // so the terminal still works; only the automatic `cd` is given up.
172
+ if (!isWindowsRemotePath(target.remotePath)) args.push(remoteCommand(target.remotePath))
173
+ return args
174
+ }
175
+
176
+ /**
177
+ * Prefer the OS OpenSSH binary on Windows. A PATH lookup there can reach an
178
+ * MSYS2/git-bash `ssh`, which resolves `~/.ssh` against a different home and
179
+ * makes keys saved by the host half look missing.
180
+ * @param {string} [platform]
181
+ * @param {object} [env]
182
+ * @param {(p: string) => boolean} [exists]
183
+ * @returns {string}
184
+ */
185
+ function sshBinary(platform = process.platform, env = process.env, exists = existsSync) {
186
+ if (platform === 'win32') {
187
+ const system = env.SystemRoot || env.windir || 'C:\\Windows'
188
+ const native = path.join(system, 'System32', 'OpenSSH', 'ssh.exe')
189
+ if (exists(native)) return native
190
+ }
191
+ return 'ssh'
192
+ }
193
+
194
+ /**
195
+ * The shell to fall back to when this directory is not a remote checkout.
196
+ * @param {string} [platform]
197
+ * @param {object} [env]
198
+ * @returns {string}
199
+ */
200
+ function localShell(platform = process.platform, env = process.env) {
201
+ if (platform === 'win32') return env.ComSpec || 'cmd.exe'
202
+ return env.SHELL || '/bin/sh'
203
+ }
204
+
205
+ /**
206
+ * Parse the arguments the launcher passes.
207
+ * @param {string[]} argv
208
+ * @returns {{ machines?: string }}
209
+ */
210
+ function parseArgs(argv) {
211
+ const out = {}
212
+ for (let i = 0; i < argv.length; i += 1) {
213
+ if (argv[i] === '--machines' && argv[i + 1]) {
214
+ out.machines = argv[i + 1]
215
+ i += 1
216
+ }
217
+ }
218
+ return out
219
+ }
220
+
221
+ /**
222
+ * Resolve everything needed to connect from a working directory.
223
+ * @param {{ cwd?: string, machines?: string, exists?: Function, readJsonFile?: Function }} input
224
+ * @returns {{ target?: object, machine?: object, found: boolean }}
225
+ */
226
+ function resolveTarget(input = {}) {
227
+ const cwd = input.cwd || process.cwd()
228
+ const mirror = findMirror(cwd, input)
229
+ if (!mirror) return { found: false }
230
+ const registry = input.machines ? (input.readJsonFile || readJson)(input.machines) : undefined
231
+ const machine = matchMachine(mirror.meta, registry)
232
+ const target = {
233
+ host: mirror.meta.host,
234
+ port: mirror.meta.port || (machine && machine.port) || 22,
235
+ username: mirror.meta.username || (machine && machine.username) || '',
236
+ alias: mirror.meta.alias || '',
237
+ remotePath: mirror.meta.remotePath || (machine && machine.workspace) || '',
238
+ }
239
+ const relative = path.relative(mirror.dir, path.resolve(cwd))
240
+ if (relative && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative)) {
241
+ const sep = isWindowsRemotePath(target.remotePath) ? '\\' : '/'
242
+ target.remotePath = String(target.remotePath || '~').replace(/[\\/]+$/, '') + sep + relative.split(path.sep).join(sep)
243
+ }
244
+ return { found: true, target, machine, dir: mirror.dir }
245
+ }
246
+
247
+ /**
248
+ * Whether stdin is a console this process can actually receive keys from.
249
+ *
250
+ * A terminal that inherits stdio from `ELECTRON_RUN_AS_NODE` gets pipes, not
251
+ * the ConPTY console: output flows while every keystroke is dropped, leaving a
252
+ * tab that looks alive and accepts nothing (issue #91). Detecting that here
253
+ * turns a silent dead end into an explicit, actionable refusal. `isTTY` is the
254
+ * cheap check; `fstat(0)` catches runtimes that never set the flag.
255
+ *
256
+ * @param {{ stdin?: object, fstat?: (fd: number) => any }} [deps]
257
+ * @returns {boolean}
258
+ */
259
+ function stdinIsInteractive(deps = {}) {
260
+ const stdin = deps.stdin === undefined ? process.stdin : deps.stdin
261
+ const fstat = deps.fstat || fstatSync
262
+ if (stdin && stdin.isTTY === true) return true
263
+ try {
264
+ const stat = fstat(0)
265
+ return Boolean(stat && typeof stat.isCharacterDevice === 'function' && stat.isCharacterDevice())
266
+ } catch {
267
+ return false
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Whether the machine's password auth needs (and can use) the credential
273
+ * bridge. Keys, agents and ssh-config aliases authenticate without us;
274
+ * keyboard-interactive (OTP) prompts are per-login and must stay on the tty;
275
+ * everything else with a stored credential (plaintext registry or OS keychain)
276
+ * goes through the bridge.
277
+ *
278
+ * @param {object|undefined} machine - the matched registry record.
279
+ * @returns {boolean}
280
+ */
281
+ function needsAskpass(machine) {
282
+ if (!machine) return false
283
+ if (machine.useAgent || machine.useSshConfig || machine.keyboardInteractive) return false
284
+ if (String(machine.privateKeyPath || '')) return false
285
+ if (String(machine.password || '')) return true
286
+ return Boolean(machine.credentialBackend && machine.credentialBackend !== 'plain')
287
+ }
288
+
289
+ /**
290
+ * Environment additions that route ssh's password prompt to the bridge helper.
291
+ * Only applied when needsAskpass() held AND the payload file exists.
292
+ *
293
+ * `SSH_ASKPASS_REQUIRE=force` (OpenSSH ≥ 8.4) is what makes askpass run at all
294
+ * on a tty; DISPLAY feeds prehistoric ssh builds. DSH_TS_* carries the machine
295
+ * identity to the helper through the process environment.
296
+ *
297
+ * @param {object} machine
298
+ * @param {string} termDir - the launcher's directory (DSH_TERM_DIR).
299
+ * @param {string} [platform]
300
+ * @returns {object} env entries to merge over process.env
301
+ */
302
+ function askpassEnv(machine, termDir, platform = process.platform) {
303
+ const wrapper = path.join(termDir, platform === 'win32' ? 'term-askpass.cmd' : 'term-askpass')
304
+ return {
305
+ SSH_ASKPASS: wrapper,
306
+ SSH_ASKPASS_REQUIRE: 'force',
307
+ DISPLAY: process.env.DISPLAY || 'dsh-remote:0',
308
+ DSH_TS_HOST: String(machine.host || ''),
309
+ DSH_TS_PORT: String(Number(machine.port) || 22),
310
+ DSH_TS_USERNAME: String(machine.username || ''),
311
+ DSH_TS_ALIAS: String(machine.alias || ''),
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Hand the current process over to `file args…`, propagating the exit code.
317
+ * @param {string} file
318
+ * @param {string[]} args
319
+ * @param {object} [extraEnv] - env entries merged over process.env (askpass).
320
+ * @returns {import('node:child_process').ChildProcess}
321
+ */
322
+ function handover(file, args, extraEnv) {
323
+ const child = spawn(file, args, { stdio: 'inherit', env: extraEnv ? { ...process.env, ...extraEnv } : process.env })
324
+ child.on('error', (error) => {
325
+ process.stderr.write(`[dsh-remote] cannot run ${file}: ${error && error.message}\n`)
326
+ process.exit(127)
327
+ })
328
+ child.on('exit', (code, signal) => {
329
+ if (signal) process.kill(process.pid, signal)
330
+ else process.exit(code == null ? 0 : code)
331
+ })
332
+ return child
333
+ }
334
+
335
+ // A small whale-shaped pixel mark, following the DSH mascot silhouette. Two
336
+ // pixel rows share one terminal row so it stays compact beside a normal prompt.
337
+ // This is terminal text (SGR + block characters), not an image protocol or DOM
338
+ // overlay; it works in the native terminal and never echoes connection secrets.
339
+ const TERMINAL_FISH = [
340
+ ' bbbb b',
341
+ ' bbbbbbbbbb bb',
342
+ ' bbbbbbbbbbbbbb bbb',
343
+ ' bbbbbbbbbbbbbbbbbbbbb',
344
+ 'bbbbbbbbbbbbbbbbbbbb',
345
+ 'bbbbbbebbbbbbbbbbbb',
346
+ 'bbbbbbbbbllllbbbbbb',
347
+ ' bbbbbbblllllbbbbb',
348
+ ' bbbbbbbbbbbbbb',
349
+ ' bbbbbbbb',
350
+ ]
351
+
352
+ /** Render a static welcome mark; a restart prints once, never on a poll/resize.
353
+ * `_target` is deliberately ignored: shell prompts and the workbench already
354
+ * identify the remote, so the decoration must not duplicate host/path metadata.
355
+ */
356
+ function connectionBanner(_target, env = process.env, terminalColumns) {
357
+ const columns = Number(terminalColumns || env.COLUMNS)
358
+ const width = Number.isFinite(columns) && columns > 0 ? Math.floor(columns) : 80
359
+ if (width < 12) return ''
360
+ const color = env.NO_COLOR === undefined && !!env.TERM && env.TERM !== 'dumb'
361
+ const reset = color ? '\x1b[0m' : ''
362
+ // Avoid wrapping the fish in a narrow split terminal. ASCII is the most
363
+ // portable fallback, including terminals without block-character support.
364
+ if (width < 30 || env.TERM === 'dumb') return '\r\n' + (color ? '\x1b[36m' : '') + '><(((o> dsh' + reset + '\r\n\r\n'
365
+ const pixelWidth = 23
366
+ const ink = { b: '36', l: '96', e: '30' }
367
+ const lines = []
368
+ for (let y = 0; y < TERMINAL_FISH.length; y += 2) {
369
+ const upper = TERMINAL_FISH[y].padEnd(pixelWidth)
370
+ const lower = TERMINAL_FISH[y + 1].padEnd(pixelWidth)
371
+ let line = ' ', lastStyle = ''
372
+ for (let x = 0; x < pixelWidth; x++) {
373
+ // In monochrome the eye stays a hole rather than a filled body pixel.
374
+ const top = color ? ink[upper[x]] : upper[x] !== ' ' && upper[x] !== 'e'
375
+ const bottom = color ? ink[lower[x]] : lower[x] !== ' ' && lower[x] !== 'e'
376
+ let glyph = ' ', style = ''
377
+ if (top && bottom) {
378
+ glyph = top === bottom ? '█' : '▀'
379
+ if (color) style = '\x1b[' + top + ';' + (top === bottom ? '49' : String(Number(bottom) + 10)) + 'm'
380
+ } else if (top || bottom) {
381
+ glyph = top ? '▀' : '▄'
382
+ if (color) style = '\x1b[' + (top || bottom) + ';49m'
383
+ } else if (color) style = '\x1b[0m'
384
+ if (style !== lastStyle) { line += style; lastStyle = style }
385
+ line += glyph
386
+ }
387
+ line += reset
388
+ if (y === 4) line += ' dsh'
389
+ lines.push(line.trimEnd())
390
+ }
391
+ return '\r\n' + lines.join('\r\n') + '\r\n\r\n'
392
+ }
393
+
394
+ /**
395
+ * Entry point: connect, or explain why a local shell was used instead.
396
+ * @param {string[]} [argv]
397
+ * @param {{ cwd?: string, platform?: string, env?: object,
398
+ * stdin?: object, columns?: number, fstat?: (fd: number) => any,
399
+ * write?: (line: string) => void, exit?: (code: number) => any }} [deps]
400
+ */
401
+ function main(argv = process.argv.slice(2), deps = {}) {
402
+ const platform = deps.platform || process.platform
403
+ const env = deps.env || process.env
404
+ const write = deps.write || ((line) => process.stderr.write(line))
405
+ const exit = deps.exit || ((code) => process.exit(code))
406
+ if (!stdinIsInteractive(deps)) {
407
+ // Anything we could hand over to — ssh, cmd, sh — reads stdin the same
408
+ // way, so there is no useful fallback here: the tab would render the
409
+ // remote prompt and ignore every key. Refuse loudly instead (issue #91).
410
+ write('[dsh-remote] this terminal cannot receive input: stdin is not a real console.\n')
411
+ write('[dsh-remote] point DSH_REMOTE_TERMINAL_NODE at an absolute node.exe path and restart, so the launcher does not have to reuse the app runtime.\n')
412
+ write('[dsh-remote] 终端无法接收输入(stdin 不是真实控制台)。请把 DSH_REMOTE_TERMINAL_NODE 指向 node.exe 的绝对路径后重启。\n')
413
+ exit(126)
414
+ return undefined
415
+ }
416
+ const options = parseArgs(argv)
417
+ const resolved = resolveTarget({ cwd: deps.cwd || process.cwd(), machines: options.machines })
418
+ if (!resolved.found) {
419
+ process.stderr.write('[dsh-remote] this directory is not a remote workspace; opening a local shell.\n')
420
+ process.stderr.write('[dsh-remote] 当前目录不是远程工作区,已打开本地终端。\n')
421
+ return handover(localShell(platform, env), platform === 'win32' ? [] : ['-l'])
422
+ }
423
+ const ssh = sshBinary(platform, env)
424
+ const args = buildSshArgs(resolved.target, resolved.machine)
425
+ write(connectionBanner(resolved.target, env, deps.columns || process.stderr.columns || process.stdout.columns))
426
+ if (isWindowsRemotePath(resolved.target.remotePath)) {
427
+ process.stderr.write('[dsh-remote] the remote workspace is a Windows path; opening the remote default shell without changing directory.\n')
428
+ process.stderr.write('[dsh-remote] 远端工作区是 Windows 路径,已打开默认 shell(未自动切换目录)。\n')
429
+ }
430
+ // Saved-password bridge: when the machine needs password auth and the host
431
+ // wrote the bridge payload (Web composition only), answer ssh's password
432
+ // prompt through the plugin's credential chain instead of the tty.
433
+ const termDir = env.DSH_TERM_DIR || ''
434
+ if (termDir && needsAskpass(resolved.machine) && existsSync(path.join(termDir, 'term-secret.json'))) {
435
+ if (env.DSH_REMOTE_TERMINAL_DEBUG === '1') write('[dsh-remote] using saved credentials.\n')
436
+ return handover(ssh, args, askpassEnv(resolved.machine, termDir, platform))
437
+ }
438
+ return handover(ssh, args)
439
+ }
440
+
441
+ module.exports = {
442
+ META_FILE,
443
+ connectionBanner,
444
+ askpassEnv,
445
+ buildSshArgs,
446
+ findMirror,
447
+ needsAskpass,
448
+ isWindowsRemotePath,
449
+ localShell,
450
+ main,
451
+ matchMachine,
452
+ parseArgs,
453
+ remoteCd,
454
+ remoteCommand,
455
+ resolveTarget,
456
+ sshBinary,
457
+ stdinIsInteractive,
458
+ }
459
+
460
+ if (require.main === module) main()