dsh-remote-go 0.1.0 → 0.3.0

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 (133) hide show
  1. package/README.md +64 -95
  2. package/{client.js → dist/client.js} +7805 -5486
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +46 -0
  5. package/dist/src/api.js +442 -0
  6. package/dist/src/atomic-json.js +235 -0
  7. package/dist/src/bootstrap.js +106 -0
  8. package/dist/src/connect/attach.js +43 -0
  9. package/dist/src/connect/bootstrap.js +14 -0
  10. package/dist/src/connect/failures.js +44 -0
  11. package/dist/src/connect/guards.js +31 -0
  12. package/dist/src/connect/launch.js +80 -0
  13. package/dist/src/connect/links.js +70 -0
  14. package/dist/src/connect/ownership.js +220 -0
  15. package/dist/src/connect/pipeline.js +473 -0
  16. package/dist/src/connect/reattach.js +215 -0
  17. package/dist/src/connect/registry.js +11 -0
  18. package/dist/src/connect/repair.js +126 -0
  19. package/dist/src/connect/restart.js +316 -0
  20. package/dist/src/connect/stop.js +198 -0
  21. package/dist/src/connect/transport.js +109 -0
  22. package/dist/src/connect/verify.js +39 -0
  23. package/dist/src/connect/watchdog.js +76 -0
  24. package/dist/src/connect-log.js +162 -0
  25. package/dist/src/connect-progress.js +142 -0
  26. package/dist/src/constants.js +67 -0
  27. package/dist/src/context.js +117 -0
  28. package/dist/src/diagnostics.js +102 -0
  29. package/dist/src/download-jobs.js +230 -0
  30. package/dist/src/errors.js +243 -0
  31. package/dist/src/events.js +390 -0
  32. package/dist/src/host-lifecycle.js +504 -0
  33. package/dist/src/host-registry.js +232 -0
  34. package/dist/src/host-runtime.js +86 -0
  35. package/dist/src/host-view.js +75 -0
  36. package/dist/src/index.js +216 -0
  37. package/dist/src/kernel-adapter.js +434 -0
  38. package/dist/src/key-files.js +52 -0
  39. package/dist/src/known-hosts.js +125 -0
  40. package/dist/src/layout.js +43 -0
  41. package/dist/src/local-download.js +380 -0
  42. package/dist/src/local-ssh.js +30 -0
  43. package/dist/src/local-version.js +101 -0
  44. package/dist/src/node/download.js +160 -0
  45. package/dist/src/node-runtime.js +346 -0
  46. package/dist/src/probe.js +96 -0
  47. package/dist/src/prompts.js +270 -0
  48. package/dist/src/proxy/cookies.js +136 -0
  49. package/dist/src/proxy/headers.js +262 -0
  50. package/dist/src/proxy/http.js +142 -0
  51. package/dist/src/proxy/index.js +135 -0
  52. package/dist/src/proxy/limits.js +8 -0
  53. package/dist/src/proxy/routes.js +39 -0
  54. package/dist/src/proxy/upgrade.js +175 -0
  55. package/dist/src/redact.js +104 -0
  56. package/dist/src/remote-files.js +72 -0
  57. package/dist/src/remote-path.js +123 -0
  58. package/dist/src/remote-proc.js +339 -0
  59. package/dist/src/remote-web/registry.js +147 -0
  60. package/dist/src/remote-web/resolve.js +310 -0
  61. package/dist/src/remote-web/start.js +227 -0
  62. package/dist/src/remote-web/stop.js +93 -0
  63. package/dist/src/request-trust.js +87 -0
  64. package/dist/src/runtime/dispatch.js +310 -0
  65. package/dist/src/runtime/effects.js +91 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +120 -0
  68. package/dist/src/runtime/rules.js +565 -0
  69. package/dist/src/secrets.js +142 -0
  70. package/dist/src/service.js +406 -0
  71. package/dist/src/settings.js +144 -0
  72. package/dist/src/ssh-config.js +276 -0
  73. package/dist/src/ssh-failures.js +122 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +297 -0
  76. package/dist/src/ssh.js +477 -0
  77. package/dist/src/store.js +191 -0
  78. package/dist/src/tool-shared.js +181 -0
  79. package/dist/src/tools-exec-policy.js +167 -0
  80. package/dist/src/tools-exec.js +371 -0
  81. package/dist/src/tools-report.js +424 -0
  82. package/dist/src/tools.js +411 -0
  83. package/dist/src/tunnel.js +129 -0
  84. package/dist/src/util.js +149 -0
  85. package/dist/src/version.js +114 -0
  86. package/dist/src/watchdog-bus.js +29 -0
  87. package/dist/src/watchdog.js +156 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +2 -2
  90. package/locale/zh.json +2 -2
  91. package/package.json +40 -21
  92. package/vendor/THIRD_PARTY_NOTICES.md +27 -1
  93. package/src/api.js +0 -340
  94. package/src/atomic-json.js +0 -208
  95. package/src/bootstrap.js +0 -100
  96. package/src/connect-log.js +0 -39
  97. package/src/connect-pipeline.js +0 -463
  98. package/src/connect-progress.js +0 -135
  99. package/src/constants.js +0 -31
  100. package/src/diagnostics.js +0 -157
  101. package/src/download-jobs.js +0 -217
  102. package/src/errors.js +0 -316
  103. package/src/host-lifecycle.js +0 -187
  104. package/src/host-registry.js +0 -145
  105. package/src/host-runtime.js +0 -53
  106. package/src/host-view.js +0 -51
  107. package/src/index.js +0 -162
  108. package/src/key-files.js +0 -49
  109. package/src/known-hosts.js +0 -94
  110. package/src/layout.js +0 -35
  111. package/src/local-download.js +0 -162
  112. package/src/local-ssh.js +0 -27
  113. package/src/local-version.js +0 -88
  114. package/src/node-runtime.js +0 -521
  115. package/src/probe.js +0 -89
  116. package/src/prompts.js +0 -132
  117. package/src/redact.js +0 -54
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -73
  120. package/src/remote-proc.js +0 -208
  121. package/src/remote-web.js +0 -300
  122. package/src/secrets.js +0 -79
  123. package/src/service.js +0 -250
  124. package/src/settings.js +0 -135
  125. package/src/ssh-config.js +0 -271
  126. package/src/ssh.js +0 -652
  127. package/src/store.js +0 -143
  128. package/src/tunnel.js +0 -73
  129. package/src/util.js +0 -153
  130. package/src/version.js +0 -103
  131. package/src/webapp.js +0 -28
  132. package/vendor/ssh2-entry.mjs +0 -12
  133. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
package/src/remote-web.js DELETED
@@ -1,300 +0,0 @@
1
- /**
2
- * Remote DSH web lifecycle — start (detached, logged), parse the `dsh web:` URL, stop, adopt; the launch token stays in memory.
3
- */
4
- import { DEFAULT_REMOTE_PROFILE, REMOTE_START_TIMEOUT_MS } from './constants.js'
5
- import { errors } from './errors.js'
6
- import { remoteLayout } from './layout.js'
7
- import { headTail, isLoopbackHost, isPid, messageOf, shellQuote } from './util.js'
8
- import { normalizeVersion } from './version.js'
9
- import { isUiUp, remoteHttpStatus } from './remote-proc.js'
10
-
11
- const WEB_LINE_RE = /dsh web:\s*(https?:\/\/[^\s]+)/
12
-
13
- /**
14
- * Version tag written into the run registry. Bumping it invalidates adoption of
15
- * instances started by an older launch path (they may lack the browser-carrier
16
- * overlay, which would leave the in-window page stuck at "failed to load plugins").
17
- */
18
- export const LAUNCH_MARKER = 'browser-carrier-v1'
19
-
20
- /** Overlay file the launch passes with `--patch` when the profile disables the carrier. */
21
- export const BROWSER_CARRIER_PATCH_FILE = 'browser-carrier.patch.yml'
22
-
23
- /**
24
- * The window shows the remote DSH *web* UI, so the `api-remotes` Remote-Event
25
- * carrier must stay mounted. A profile bundle aimed at a native companion can
26
- * disable that row (e.g. goldenpigeon's patch does), which leaves the browser
27
- * client with `typert gateway: $events: forwarded Remote event source is
28
- * unavailable` and a blank "failed to load plugins" page. Re-enable the row with
29
- * a launch-only overlay instead of editing the user's profile.
30
- */
31
- const BROWSER_CARRIER_PATCH = `# Written by dsh-remote-go. The remote window is a browser client, so the
32
- # Remote-Event carrier (api-remotes) must stay enabled even when a profile
33
- # bundle disables it for a native-UI companion.
34
- - id: api-remotes
35
- disabled: false`
36
-
37
- export function parseWebLine(text) {
38
- const match = WEB_LINE_RE.exec(String(text ?? ''))
39
- if (!match) return null
40
- const rawUrl = match[1]
41
- let url
42
- try {
43
- url = new URL(rawUrl)
44
- } catch {
45
- return null
46
- }
47
- const host = url.hostname.replace(/^\[|\]$/g, '')
48
- const port = url.port ? Number(url.port) : url.protocol === 'https:' ? 443 : 80
49
- const token = url.searchParams.get('token') ?? ''
50
- if (!isPid(port)) return null
51
- return { url: rawUrl, host, port, token, rawLine: match[0] }
52
- }
53
-
54
- export function buildStartCommand(plan, layout, options = {}) {
55
- const profile = options.profile ?? plan.profile ?? DEFAULT_REMOTE_PROFILE
56
- const patch = options.patchPath ? `--patch ${shellQuote(options.patchPath)} ` : ''
57
- const args = `${patch}--profile ${shellQuote(profile)} --no-open --port 0`
58
- const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : ''
59
- return `env DSH_HOME=${shellQuote(layout.dshHome)} ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} ${args}`
60
- }
61
-
62
- export function buildBrowserCarrierProbe(plan, layout, profile) {
63
- const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : ''
64
- const dumpFile = shellQuote(`${layout.root}/profile-dump.yml`)
65
- const patchFile = shellQuote(`${layout.root}/${BROWSER_CARRIER_PATCH_FILE}`)
66
- return `set -u
67
- mkdir -p ${shellQuote(layout.root)}
68
- DUMP=${dumpFile}
69
- if ! env DSH_HOME=${shellQuote(layout.dshHome)} ${pathPrefix}${shellQuote(plan.start.npxPath ?? 'npx')} -y @deepseek-ai/dsh@${normalizeVersion(plan.start.targetVersion)} --profile ${shellQuote(profile)} --dump-config > "$DUMP" 2>/dev/null; then
70
- echo "DUMP-FAILED"
71
- exit 0
72
- fi
73
- if grep -A6 'id: api-remotes' "$DUMP" | grep -q 'disabled: true'; then
74
- cat > ${patchFile} <<'DSH_REMOTE_GO_PATCH'
75
- ${BROWSER_CARRIER_PATCH}
76
- DSH_REMOTE_GO_PATCH
77
- echo "PATCH"
78
- else
79
- echo "CLEAR"
80
- fi`
81
- }
82
-
83
- export async function ensureBrowserCarrier(ssh, options) {
84
- try {
85
- const result = await ssh.exec(buildBrowserCarrierProbe(options.plan, options.layout, options.profile), {
86
- timeoutMs: 60_000,
87
- maxBytes: 64_000,
88
- })
89
- if (result.code === 0 && result.stdout.includes('PATCH')) {
90
- options.onLine?.('browser carrier: the profile disables api-remotes; re-enabling it for this launch')
91
- return {
92
- status: 'patched',
93
- patchPath: `${options.layout.root}/${BROWSER_CARRIER_PATCH_FILE}`,
94
- }
95
- }
96
- if (result.code === 0 && result.stdout.includes('CLEAR')) {
97
- options.onLine?.('browser carrier: api-remotes is enabled by the profile')
98
- return { status: 'clear', patchPath: null }
99
- }
100
- options.onLine?.(`browser carrier: profile probe failed (${headTail(result.stdout + result.stderr, 300)})`)
101
- return { status: 'unknown', patchPath: null }
102
- } catch (error) {
103
- // swallow-ok: probe failure — launching without the overlay keeps the start
104
- // error (missing profile, npx failure) as the actionable one.
105
- options.onLine?.(`browser carrier: probe failed (${messageOf(error)})`)
106
- return { status: 'unknown', patchPath: null }
107
- }
108
- }
109
-
110
- export function buildStartScript(startCommand, layout, options = {}) {
111
- const waitSeconds = options.waitSeconds ?? Math.ceil(REMOTE_START_TIMEOUT_MS / 1000)
112
- const version = normalizeVersion(options.version ?? '')
113
- const profile = options.profile ?? DEFAULT_REMOTE_PROFILE
114
- const logFile = shellQuote(layout.logFile)
115
- const runFile = shellQuote(layout.runFile)
116
- const startedAtPlaceholder = '$(date -u +%Y-%m-%dT%H:%M:%SZ)'
117
- return `set -eu
118
- mkdir -p ${shellQuote(layout.logsDir)} ${shellQuote(layout.runDir)} ${shellQuote(layout.stateHome)}
119
- LOG=${logFile}
120
- : > "$LOG"
121
- cd "$HOME"
122
- setsid nohup bash -lc ${shellQuote(startCommand)} >> "$LOG" 2>&1 < /dev/null &
123
- PID=$!
124
- echo "PID:$PID"
125
- i=0
126
- while [ "$i" -lt ${waitSeconds} ]; do
127
- if grep -q 'dsh web:' "$LOG" 2>/dev/null; then break; fi
128
- if ! kill -0 "$PID" 2>/dev/null; then
129
- echo "EXITED:$PID"
130
- echo "---LOG---"
131
- tail -n 60 "$LOG" 2>/dev/null || true
132
- exit 3
133
- fi
134
- i=$((i+1))
135
- sleep 1
136
- done
137
- LINE=$(grep -m1 'dsh web:' "$LOG" 2>/dev/null || true)
138
- if [ -z "$LINE" ]; then
139
- echo "TIMEOUT"
140
- echo "---LOG---"
141
- tail -n 60 "$LOG" 2>/dev/null || true
142
- exit 4
143
- fi
144
- echo "LINE:$LINE"
145
- PORT=$(printf '%s' "$LINE" | sed -n 's#.*127\\.0\\.0\\.1:\\([0-9][0-9]*\\)/.*#\\1#p')
146
- if [ -z "$PORT" ]; then PORT=$(printf '%s' "$LINE" | sed -n 's#.*:\\([0-9][0-9]*\\)/.*#\\1#p'); fi
147
- printf '{"pid":%s,"port":%s,"startedAt":"%s","profile":%s,"version":%s,"dshHome":%s,"launch":"${LAUNCH_MARKER}"}\\n' "$PID" "\${PORT:-0}" "${startedAtPlaceholder}" ${shellQuote(JSON.stringify(profile))} ${shellQuote(JSON.stringify(version))} ${shellQuote(JSON.stringify(layout.dshHome))} > ${runFile}
148
- echo "DONE:$PID:$PORT"
149
- `
150
- }
151
-
152
- export async function startRemoteWeb(ssh, options) {
153
- const layout = options.layout ?? remoteLayout(options.home ?? null)
154
- const profile = options.profile ?? options.plan.profile ?? DEFAULT_REMOTE_PROFILE
155
- const carrier = await ensureBrowserCarrier(ssh, { plan: options.plan, layout, profile, onLine: options.onLine })
156
- const startCommand = buildStartCommand(options.plan, layout, { profile, patchPath: carrier.patchPath })
157
- const script = buildStartScript(startCommand, layout, {
158
- waitSeconds: Math.ceil((options.timeoutMs ?? REMOTE_START_TIMEOUT_MS) / 1000),
159
- version: options.plan.start.targetVersion,
160
- profile,
161
- })
162
- const lines = []
163
- const result = await ssh.exec(script, {
164
- timeoutMs: (options.timeoutMs ?? REMOTE_START_TIMEOUT_MS) + 30_000,
165
- maxBytes: 200_000,
166
- onStdout: (chunk) => {
167
- for (const line of chunk.split(/\r?\n/)) {
168
- if (line !== '') {
169
- lines.push(line)
170
- options.onLine?.(line)
171
- }
172
- }
173
- },
174
- })
175
- const combined = `${result.stdout}\n${result.stderr}`
176
- if (result.code !== 0) {
177
- throw errors.remoteDshStartFailed(headTail(combined, 1500))
178
- }
179
- const parsed = parseWebLine(combined)
180
- if (!parsed) throw errors.remoteDshStartFailed(headTail(combined, 1500))
181
- if (!isLoopbackHost(parsed.host)) {
182
- throw errors.remoteUiUnreachable({
183
- zh: `远端 DSH 宣布的地址不是回环地址(${parsed.host}),无法安全地经 SSH 隧道访问。`,
184
- en: `The remote DSH advertised a non-loopback host (${parsed.host}); it cannot be reached safely through the SSH tunnel.`,
185
- })
186
- }
187
- const pidMatch = /DONE:(\d+):(\d+)/.exec(combined)
188
- const pid = pidMatch ? Number(pidMatch[1]) : 0
189
- const startedAt = new Date().toISOString()
190
- return {
191
- pid,
192
- port: parsed.port,
193
- token: parsed.token,
194
- url: parsed.url,
195
- logPath: layout.logFile,
196
- startedAt,
197
- rawLine: parsed.rawLine,
198
- profile,
199
- dshHome: layout.dshHome,
200
- browserCarrier: carrier.status,
201
- }
202
- }
203
-
204
- export async function stopRemoteWeb(ssh, layout, options = {}) {
205
- const pid = Number(options.pid ?? 0)
206
- const script = `set -u
207
- PID=${isPid(pid) ? pid : 0}
208
- if [ "$PID" -eq 0 ] && [ -f ${shellQuote(layout.runFile)} ]; then
209
- PID=$(sed -n 's/.*"pid":\\([0-9][0-9]*\\).*/\\1/p' ${shellQuote(layout.runFile)} | head -n 1)
210
- fi
211
- if [ -n "\${PID:-}" ] && [ "$PID" -ne 0 ]; then
212
- kill -TERM "-$PID" 2>/dev/null || kill -TERM "$PID" 2>/dev/null || true
213
- n=0
214
- while [ "$n" -lt 20 ]; do
215
- kill -0 "$PID" 2>/dev/null || break
216
- n=$((n+1))
217
- sleep 0.5
218
- done
219
- kill -KILL "-$PID" 2>/dev/null || kill -KILL "$PID" 2>/dev/null || true
220
- fi
221
- rm -f ${shellQuote(layout.runFile)}
222
- echo "STOPPED"
223
- `
224
- try {
225
- const result = await ssh.exec(script, { timeoutMs: 30_000 })
226
- return { ok: result.code === 0, output: result.stdout.trim() }
227
- } catch (error) {
228
- return { ok: false, output: messageOf(error) }
229
- }
230
- }
231
-
232
- export async function readRunRegistry(ssh, layout) {
233
- try {
234
- const result = await ssh.exec(`cat ${shellQuote(layout.runFile)} 2>/dev/null || true`, { timeoutMs: 10_000 })
235
- if (result.code !== 0 || result.stdout.trim() === '') return null
236
- const parsed = JSON.parse(result.stdout.trim())
237
- return parsed && typeof parsed === 'object' ? parsed : null
238
- } catch {
239
- return null
240
- }
241
- }
242
-
243
- export async function readWebLineFromLog(ssh, layout) {
244
- try {
245
- const result = await ssh.exec(`grep 'dsh web:' ${shellQuote(layout.logFile)} 2>/dev/null | tail -n 1 || true`, {
246
- timeoutMs: 15_000,
247
- })
248
- if (result.code !== 0 || !result.stdout.trim()) return null
249
- return parseWebLine(result.stdout)
250
- } catch {
251
- return null
252
- }
253
- }
254
-
255
- export async function remotePidAlive(ssh, pid) {
256
- if (!isPid(pid)) return false
257
- try {
258
- const result = await ssh.exec(`kill -0 ${pid} 2>/dev/null && echo alive || true`, { timeoutMs: 10_000 })
259
- return result.stdout.includes('alive')
260
- } catch {
261
- return false
262
- }
263
- }
264
-
265
- /**
266
- * Try to adopt a still-running remote web instance from a previous local
267
- * process: registry pid alive + last log line parseable + loopback HTTP alive.
268
- *
269
- * The registry must name the same DSH home and profile this connection is about
270
- * to use; a process left over from another home or profile would show a
271
- * different DSH state than the user asked for.
272
- */
273
- export async function adoptRemoteWeb(ssh, layout, options = {}) {
274
- const profile = options.profile ?? DEFAULT_REMOTE_PROFILE
275
- const registry = await readRunRegistry(ssh, layout)
276
- // Instances from a launch path that did not apply the browser-carrier overlay
277
- // cannot be adopted: the page they serve may be stuck at "failed to load
278
- // plugins", and nothing on the server side reveals that.
279
- if (registry?.launch !== LAUNCH_MARKER) return null
280
- if (registry?.dshHome !== layout.dshHome) return null
281
- if (registry?.profile !== profile) return null
282
- const pid = Number(registry?.pid ?? 0)
283
- if (!(await remotePidAlive(ssh, pid))) return null
284
- const line = await readWebLineFromLog(ssh, layout)
285
- if (!line) return null
286
- const status = await remoteHttpStatus(ssh, line.port)
287
- if (!isUiUp(status)) return null
288
- const version =
289
- typeof registry?.version === 'string' && registry.version !== '' ? normalizeVersion(registry.version) : null
290
- return {
291
- pid,
292
- port: line.port,
293
- token: line.token,
294
- url: line.url,
295
- version,
296
- profile,
297
- dshHome: layout.dshHome,
298
- adopted: true,
299
- }
300
- }
package/src/secrets.js DELETED
@@ -1,79 +0,0 @@
1
- /**
2
- * Per-host SSH password storage in DSH's own credential store (`ctx.credentials`), never in `hosts.json`; with no credential service nothing is persisted.
3
- */
4
-
5
- const RECORD_PREFIX = 'dsh-remote-go:ssh-password:'
6
- const PAYLOAD_VERSION = 1
7
-
8
- export function createSecretStore(options = {}) {
9
- const logger = options.logger ?? console
10
-
11
- function credentials() {
12
- try {
13
- const ctx = options.ctx
14
- if (!ctx || typeof ctx.get !== 'function') return null
15
- const service = ctx.get('credentials')
16
- if (!service || typeof service.modifyRecord !== 'function' || typeof service.readRecord !== 'function') {
17
- return null
18
- }
19
- return service
20
- } catch (error) {
21
- logger.warn?.('[dsh-remote-go] credential service lookup failed:', error)
22
- return null
23
- }
24
- }
25
-
26
- function keyFor(hostId) {
27
- return RECORD_PREFIX + String(hostId)
28
- }
29
-
30
- return {
31
- available() {
32
- return credentials() !== null
33
- },
34
-
35
- async get(hostId) {
36
- const service = credentials()
37
- if (!service || !hostId) return null
38
- try {
39
- const record = await service.readRecord(keyFor(hostId))
40
- const payload = record && record.kind === 'grant' ? record.payload : null
41
- if (!payload || typeof payload !== 'object') return null
42
- if (payload.version !== PAYLOAD_VERSION || typeof payload.password !== 'string') return null
43
- return payload.password === '' ? null : payload.password
44
- } catch (error) {
45
- logger.warn?.('[dsh-remote-go] could not read the saved password:', error)
46
- return null
47
- }
48
- },
49
-
50
- async has(hostId) {
51
- return (await this.get(hostId)) !== null
52
- },
53
-
54
- async set(hostId, password) {
55
- const service = credentials()
56
- if (!service || !hostId || typeof password !== 'string' || password === '') return false
57
- try {
58
- await service.modifyRecord(keyFor(hostId), async () => ({
59
- kind: 'grant',
60
- payload: { version: PAYLOAD_VERSION, password },
61
- }))
62
- return true
63
- } catch (error) {
64
- logger.warn?.('[dsh-remote-go] could not save the password:', error)
65
- return false
66
- }
67
- },
68
-
69
- async remove(hostId) {
70
- const service = credentials()
71
- if (!service || typeof service.deleteRecord !== 'function' || !hostId) return
72
- try {
73
- await service.deleteRecord(keyFor(hostId))
74
- } catch (error) {
75
- logger.warn?.('[dsh-remote-go] could not delete the saved password:', error)
76
- }
77
- },
78
- }
79
- }
package/src/service.js DELETED
@@ -1,250 +0,0 @@
1
- /**
2
- * Orchestration service — the facade over host-registry, connect-pipeline, host-lifecycle, prompts and connect-progress; every external step is injected.
3
- */
4
- import { EventEmitter } from 'node:events'
5
- import { planNpx, verifyNpxVersion } from './bootstrap.js'
6
- import { REMOTE_CONFLICT_TIMEOUT_MS } from './constants.js'
7
- import { createConnectProgress, describePreflightEvent } from './connect-progress.js'
8
- import { createDownloadJobs } from './download-jobs.js'
9
- import { reconnectHost, startConnect } from './connect-pipeline.js'
10
- import { diagnoseHost } from './diagnostics.js'
11
- import { errors } from './errors.js'
12
- import {
13
- discoverSshAliases,
14
- initRegistry,
15
- listKeyFiles,
16
- removeHost,
17
- runtimeOf,
18
- saveHost,
19
- saveSettings,
20
- setActiveHost,
21
- snapshot,
22
- } from './host-registry.js'
23
- import { disconnectHost, shutdownAll } from './host-lifecycle.js'
24
- import { loadLocalSshMaterial } from './local-ssh.js'
25
- import { ensureRemoteNode } from './node-runtime.js'
26
- import { confirmConflict, confirmHostKey } from './prompts.js'
27
- import { probeRemote } from './probe.js'
28
- import { SshConnection } from './ssh.js'
29
- import { createTunnel } from './tunnel.js'
30
- import { normalizeVersion } from './version.js'
31
- import {
32
- adoptRemoteWeb,
33
- exchangeTokenOverTunnel,
34
- findForeignDshProcesses,
35
- readRunRegistry,
36
- startRemoteWeb,
37
- stopForeignDshProcesses,
38
- stopRemoteWeb,
39
- waitForRemoteUi,
40
- } from './webapp.js'
41
-
42
- export { describePreflightEvent }
43
-
44
- /** Milliseconds a paused host-key handshake waits for the user. */
45
- const HOST_KEY_CONFIRM_TIMEOUT_MS = 120_000
46
-
47
- export class RemoteGoService extends EventEmitter {
48
- constructor(options) {
49
- super()
50
- this.store = options.store
51
- this.home = options.home
52
- this.logger = options.logger ?? console
53
- this.localVersion = options.localVersion ?? null
54
- // `engines.node` of the local DSH package; the managed Node version is its
55
- // lower bound (see `managedNodeVersionFromEngine`). Null until detected.
56
- this.engineNodeRange = options.engineNodeRange ?? null
57
- this.secrets = options.secrets ?? null
58
- this.hostKeyConfirmTimeoutMs = options.hostKeyConfirmTimeoutMs ?? HOST_KEY_CONFIRM_TIMEOUT_MS
59
- this.conflictConfirmTimeoutMs = options.conflictConfirmTimeoutMs ?? REMOTE_CONFLICT_TIMEOUT_MS
60
- this.logLevel = typeof options.logLevel === 'string' ? options.logLevel : null
61
-
62
- const deps = {
63
- sshFactory: options.sshFactory ?? ((sshOptions) => new SshConnection(sshOptions)),
64
- tunnelFactory: options.tunnelFactory ?? createTunnel,
65
- probe: options.probe ?? probeRemote,
66
- plan: options.plan ?? planNpx,
67
- ensureNode: options.ensureNode ?? ensureRemoteNode,
68
- preflight: options.preflight ?? verifyNpxVersion,
69
- startWeb: options.startWeb ?? startRemoteWeb,
70
- stopWeb: options.stopWeb ?? stopRemoteWeb,
71
- waitUi: options.waitUi ?? waitForRemoteUi,
72
- exchange: options.exchange ?? exchangeTokenOverTunnel,
73
- adopt: options.adopt ?? adoptRemoteWeb,
74
- findForeign: options.findForeign ?? findForeignDshProcesses,
75
- stopForeign: options.stopForeign ?? stopForeignDshProcesses,
76
- readRegistry: options.readRegistry ?? readRunRegistry,
77
- loadSshMaterial: options.loadSshMaterial ?? loadLocalSshMaterial,
78
- }
79
- this.ctx = {
80
- deps,
81
- store: this.store,
82
- home: this.home,
83
- logger: this.logger,
84
- secrets: this.secrets,
85
- state: { runtimes: new Map(), activeHostId: null, initialized: false, disposed: false },
86
- timers: {
87
- hostKeyConfirmMs: this.hostKeyConfirmTimeoutMs,
88
- conflictConfirmMs: this.conflictConfirmTimeoutMs,
89
- },
90
- // Live readers, never cached: a setting or a detected version can change
91
- // while a connect is already in flight.
92
- settings: () => this.store.getSettings(),
93
- localVersion: () => this.localVersion,
94
- engineNodeRange: () => this.engineNodeRange,
95
- userHome: () => process.env.USERPROFILE || process.env.HOME || this.home,
96
- emitState: () => this.emitState(),
97
- init: () => this.init(),
98
- }
99
- this.ctx.progress = createConnectProgress({
100
- logger: this.logger,
101
- logLevel: this.logLevel,
102
- getSettings: () => this.store.getSettings(),
103
- emitState: () => this.emitState(),
104
- })
105
- this.downloads = createDownloadJobs({
106
- logger: this.logger,
107
- emit: (job) => this.emit('download', job),
108
- })
109
- }
110
-
111
- get runtimes() {
112
- return this.ctx.state.runtimes
113
- }
114
-
115
- get activeHostId() {
116
- return this.ctx.state.activeHostId
117
- }
118
-
119
- async init() {
120
- await initRegistry(this.ctx)
121
- return this
122
- }
123
-
124
- emitState() {
125
- try {
126
- this.emit('state', this.snapshot())
127
- } catch (error) {
128
- this.logger.warn?.('[dsh-remote-go] state listener failed:', error)
129
- }
130
- }
131
-
132
- setLocalVersion(version) {
133
- const normalized = version ? normalizeVersion(version) : null
134
- if (normalized) {
135
- this.localVersion = normalized
136
- this.emitState()
137
- }
138
- }
139
-
140
- setLocalEnginesNode(range) {
141
- const text = typeof range === 'string' ? range.trim() : ''
142
- this.engineNodeRange = text === '' ? null : text
143
- }
144
-
145
- /** Build the client-facing state snapshot (contract: docs/api.md). */
146
- snapshot() {
147
- return snapshot(this.ctx)
148
- }
149
-
150
- userHome() {
151
- return this.ctx.userHome()
152
- }
153
-
154
- async saveHost(rawHost) {
155
- return saveHost(this.ctx, rawHost)
156
- }
157
-
158
- async removeHost(id) {
159
- return removeHost(this.ctx, id)
160
- }
161
-
162
- setActiveHost(id) {
163
- return setActiveHost(this.ctx, id)
164
- }
165
-
166
- async saveSettings(patch) {
167
- return saveSettings(this.ctx, patch)
168
- }
169
-
170
- async listKeyFiles(dir) {
171
- return listKeyFiles(this.ctx, dir)
172
- }
173
-
174
- async discoverSshAliases() {
175
- return discoverSshAliases(this.ctx)
176
- }
177
-
178
- async connect(id, options = {}) {
179
- return startConnect(this.ctx, id, options)
180
- }
181
-
182
- async disconnect(id, options = {}) {
183
- await this.init()
184
- return disconnectHost(this.ctx, runtimeOf(this.ctx, id), options)
185
- }
186
-
187
- async reconnect(id) {
188
- await this.init()
189
- return reconnectHost(this.ctx, runtimeOf(this.ctx, id))
190
- }
191
-
192
- async confirmFingerprint(id, decision) {
193
- return confirmHostKey(this.ctx, runtimeOf(this.ctx, id), decision)
194
- }
195
-
196
- async confirmConflict(id, decision) {
197
- return confirmConflict(runtimeOf(this.ctx, id), decision)
198
- }
199
-
200
- openInfo(id) {
201
- const runtime = runtimeOf(this.ctx, id)
202
- if (runtime.status !== 'connected' || !runtime.tunnel || !runtime.token) {
203
- throw errors.remoteUiUnreachable({
204
- zh: '主机尚未连接,无法打开远端界面。',
205
- en: 'The host is not connected yet, so the remote UI cannot be opened.',
206
- })
207
- }
208
- return {
209
- url: `http://127.0.0.1:${runtime.tunnel.localPort}/?token=${encodeURIComponent(runtime.token)}`,
210
- localPort: runtime.tunnel.localPort,
211
- address: `127.0.0.1:${runtime.tunnel.localPort}`,
212
- }
213
- }
214
-
215
- async diagnose(id) {
216
- await this.init()
217
- return diagnoseHost(runtimeOf(this.ctx, id), { targetVersion: this.localVersion })
218
- }
219
-
220
- /**
221
- * Start preparing one remote file or folder for the client's download.
222
- * @param {string} id - host id.
223
- * @param {unknown} path - absolute remote path.
224
- * @param {{ destination?: string }} [options] - local destination directory.
225
- * @returns {object} the initial download job view.
226
- */
227
- async startRemoteDownload(id, path, options = {}) {
228
- await this.init()
229
- return this.downloads.start(runtimeOf(this.ctx, id), path, options)
230
- }
231
-
232
- /** Current view of one download job. */
233
- async remoteDownloadStatus(jobId) {
234
- await this.init()
235
- return this.downloads.status(jobId)
236
- }
237
-
238
- /** Cancel one download job. */
239
- async cancelRemoteDownload(jobId) {
240
- await this.init()
241
- return this.downloads.cancel(jobId)
242
- }
243
-
244
- async shutdown() {
245
- this.ctx.state.disposed = true
246
- this.ctx.progress.dispose()
247
- this.downloads.dispose()
248
- await shutdownAll(this.ctx)
249
- }
250
- }