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
@@ -1,187 +0,0 @@
1
- /**
2
- * Per-host lifecycle: the reconnect backoff, the idle-stop timer and the single teardown path; the reconnect timer gets a callback, so this never imports the pipeline.
3
- */
4
- import { DEFAULT_IDLE_MINUTES } from './constants.js'
5
- import { errors, toErrorView } from './errors.js'
6
- import { emptyRemote } from './host-runtime.js'
7
- import { remoteLayout } from './layout.js'
8
- import { cancelConflict } from './prompts.js'
9
- import { messageOf, randomDelay } from './util.js'
10
-
11
- export function cancelReconnect(runtime) {
12
- if (runtime.reconnectTimer) {
13
- clearTimeout(runtime.reconnectTimer)
14
- runtime.reconnectTimer = null
15
- }
16
- }
17
-
18
- export function cancelIdleStop(runtime) {
19
- if (runtime.idleTimer) {
20
- clearTimeout(runtime.idleTimer)
21
- runtime.idleTimer = null
22
- }
23
- }
24
-
25
- /**
26
- * Arm the next reconnect attempt, or give up once the configured budget is spent.
27
- */
28
- export function scheduleReconnect(ctx, runtime, onDue) {
29
- cancelReconnect(runtime)
30
- const settings = ctx.settings()
31
- if (!runtime.entry.autoReconnect || !settings.autoReconnect.enabled) {
32
- ctx.progress.set(runtime, { status: 'disconnected' })
33
- return
34
- }
35
- const maxAttempts = settings.autoReconnect.maxAttempts
36
- if (runtime.reconnectAttempts >= maxAttempts) {
37
- runtime.status = 'error'
38
- runtime.error = toErrorView(
39
- errors.network({
40
- zh: `连接已断开,自动重连 ${maxAttempts} 次均失败。远端任务可能仍在运行。`,
41
- en: `The connection dropped and ${maxAttempts} automatic retries failed. Remote tasks may still be running.`,
42
- }),
43
- )
44
- runtime.progress = null
45
- ctx.emitState()
46
- return
47
- }
48
- runtime.reconnectAttempts += 1
49
- const delay = randomDelay(
50
- settings.autoReconnect.baseDelayMs,
51
- settings.autoReconnect.baseDelayMs * 2 ** Math.min(runtime.reconnectAttempts, 4),
52
- )
53
- runtime.progress = { code: 'reconnecting', params: { attempt: runtime.reconnectAttempts, max: maxAttempts } }
54
- ctx.progress.log(
55
- runtime,
56
- 'warn',
57
- `link lost; retrying in ${Math.round(delay / 100) / 10}s (attempt ${runtime.reconnectAttempts}/${maxAttempts})`,
58
- )
59
- ctx.emitState()
60
- runtime.reconnectTimer = setTimeout(() => {
61
- runtime.reconnectTimer = null
62
- onDue()
63
- }, delay)
64
- }
65
-
66
- function scheduleIdleStop(ctx, runtime) {
67
- cancelIdleStop(runtime)
68
- const minutes = Math.max(1, runtime.entry.idleMinutes ?? DEFAULT_IDLE_MINUTES)
69
- runtime.idleTimer = setTimeout(() => {
70
- runtime.idleTimer = null
71
- void stopRemoteQuietly(ctx, runtime)
72
- }, minutes * 60_000)
73
- }
74
-
75
- /** Best-effort stop of the remote web for the idle policy, then drop the transport. */
76
- async function stopRemoteQuietly(ctx, runtime) {
77
- try {
78
- if (runtime.ssh?.connected) {
79
- await ctx.deps.stopWeb(runtime.ssh, remoteLayout(runtime.facts?.home ?? null), {
80
- pid: runtime.remote.pid ?? undefined,
81
- })
82
- }
83
- } catch (error) {
84
- ctx.progress.log(runtime, 'warn', 'idle stop failed:', messageOf(error))
85
- } finally {
86
- await disposeSsh(runtime)
87
- }
88
- }
89
-
90
- export async function closeTunnel(runtime) {
91
- const tunnel = runtime.tunnel
92
- runtime.tunnel = null
93
- if (tunnel) {
94
- try {
95
- await tunnel.close()
96
- } catch {}
97
- }
98
- }
99
-
100
- export async function disposeSsh(runtime) {
101
- const ssh = runtime.ssh
102
- runtime.ssh = null
103
- const jump = runtime.jumpSsh
104
- runtime.jumpSsh = null
105
- if (ssh) {
106
- try {
107
- await ssh.dispose()
108
- } catch {}
109
- }
110
- if (jump) {
111
- try {
112
- await jump.dispose()
113
- } catch {}
114
- }
115
- }
116
-
117
- /**
118
- * The single teardown path. `stopRemote` also stops the remote web (keep-alive
119
- * `stop`), `keepSshForIdle` leaves the transport up for a fast resume, and
120
- * `keepRemote` preserves the remote facts so the card still describes what is
121
- * running on the other side.
122
- */
123
- export async function teardownRuntime(ctx, runtime, options = {}) {
124
- cancelConflict(runtime)
125
- runtime.closing = true
126
- cancelIdleStop(runtime)
127
- if (options.stopRemote && runtime.ssh?.connected) {
128
- try {
129
- await ctx.deps.stopWeb(runtime.ssh, remoteLayout(runtime.facts?.home ?? null), {
130
- pid: runtime.remote.pid ?? undefined,
131
- })
132
- } catch (error) {
133
- ctx.progress.log(runtime, 'warn', 'stop remote failed:', messageOf(error))
134
- }
135
- }
136
- await closeTunnel(runtime)
137
- if (!options.keepSshForIdle) await disposeSsh(runtime)
138
- if (!options.keepRemote) {
139
- runtime.remote = { ...emptyRemote(), version: runtime.remote.version }
140
- runtime.token = null
141
- runtime.facts = null
142
- runtime.exchange = null
143
- }
144
- }
145
-
146
- /**
147
- * Tear one host down and leave it idle: the keep-alive policy decides whether the
148
- * remote web is stopped and whether the transport survives for a fast resume.
149
- */
150
- export async function disconnectHost(ctx, runtime, options = {}) {
151
- ctx.progress.log(runtime, 'info', `disconnect requested (keepAlive=${runtime.entry.keepAlive})`)
152
- runtime.desired = 'idle'
153
- cancelReconnect(runtime)
154
- const policy = runtime.entry.keepAlive
155
- const stopRemote = options.stopRemote === true || policy === 'stop'
156
- await teardownRuntime(ctx, runtime, { stopRemote, keepSshForIdle: policy === 'idle' && !stopRemote })
157
- runtime.status = 'disconnected'
158
- runtime.phase = null
159
- runtime.progress = null
160
- runtime.remote.uiReady = false
161
- runtime.remote.localPort = null
162
- runtime.token = null
163
- ctx.progress.set(runtime, {})
164
- if (policy === 'idle' && !stopRemote) scheduleIdleStop(ctx, runtime)
165
- return { ok: true }
166
- }
167
-
168
- /**
169
- * Stop every host's timers and release its transport. The `stop` keep-alive
170
- * policy also stops the remote web so nothing is left running unowned.
171
- */
172
- export async function shutdownAll(ctx) {
173
- for (const runtime of ctx.state.runtimes.values()) {
174
- cancelReconnect(runtime)
175
- cancelIdleStop(runtime)
176
- try {
177
- if (runtime.entry.keepAlive === 'stop') {
178
- await stopRemoteQuietly(ctx, runtime)
179
- } else {
180
- await closeTunnel(runtime)
181
- await disposeSsh(runtime)
182
- }
183
- } catch {
184
- /* best effort on shutdown */
185
- }
186
- }
187
- }
@@ -1,145 +0,0 @@
1
- /**
2
- * The host registry: the configured hosts, their runtime objects and the client-facing snapshot; reads are pure, writes re-emit the snapshot after `store`.
3
- */
4
- import { homedir } from 'node:os'
5
- import path from 'node:path'
6
- import { errors } from './errors.js'
7
- import { createHostRuntime } from './host-runtime.js'
8
- import { hostView } from './host-view.js'
9
- import { listKeyFiles as listKeyFilesInHome } from './key-files.js'
10
- import { parseKnownHosts, summarizeKnownHosts } from './known-hosts.js'
11
- import { cancelIdleStop, cancelReconnect, teardownRuntime } from './host-lifecycle.js'
12
- import { discoverSshAliases as discoverAliasesFromConfig, parseSshConfig } from './ssh-config.js'
13
-
14
- function ensureRuntime(ctx, host) {
15
- const existing = ctx.state.runtimes.get(host.id)
16
- if (existing) {
17
- existing.entry = host
18
- return existing
19
- }
20
- const runtime = createHostRuntime(host)
21
- ctx.state.runtimes.set(host.id, runtime)
22
- return runtime
23
- }
24
-
25
- export function runtimeOf(ctx, id) {
26
- const runtime = ctx.state.runtimes.get(id)
27
- if (!runtime) throw errors.invalidInput('id', { zh: `未知主机 ${id}`, en: `Unknown host ${id}` })
28
- return runtime
29
- }
30
-
31
- export async function initRegistry(ctx) {
32
- if (ctx.state.initialized) return
33
- await ctx.store.load()
34
- for (const host of ctx.store.listHosts()) ensureRuntime(ctx, host)
35
- ctx.state.initialized = true
36
- }
37
-
38
- function hostViewFor(ctx, runtime) {
39
- return hostView(runtime, {
40
- targetVersion: ctx.localVersion(),
41
- passwordStorageAvailable: ctx.secrets ? ctx.secrets.available() === true : false,
42
- })
43
- }
44
-
45
- /** Build the client-facing state snapshot (contract: docs/api.md). */
46
- export function snapshot(ctx) {
47
- const localVersion = ctx.localVersion()
48
- const hosts = [...ctx.state.runtimes.values()].map((runtime) => hostViewFor(ctx, runtime))
49
- return {
50
- hostVersion: localVersion,
51
- targetVersion: localVersion,
52
- hosts,
53
- settings: ctx.store.getSettings(),
54
- activeHostId: ctx.state.activeHostId,
55
- firstRun: hosts.length === 0,
56
- }
57
- }
58
-
59
- export async function saveHost(ctx, rawHost) {
60
- await ctx.init()
61
- let entry
62
- try {
63
- entry = await ctx.store.upsertHost(rawHost, { settings: ctx.store.getSettings() })
64
- } catch (error) {
65
- // The store's validators throw bare messages; map them to the client's field
66
- // errors here so the contract stays typed.
67
- const message = error instanceof Error ? error.message : String(error)
68
- if (message === 'address is required') {
69
- throw errors.invalidInput('address', {
70
- zh: '请填写服务器地址或 ~/.ssh/config 别名。',
71
- en: 'Enter a server address or an ~/.ssh/config alias.',
72
- })
73
- }
74
- if (message === 'address is invalid') {
75
- throw errors.invalidInput('address', { zh: '服务器地址格式不正确。', en: 'The server address is not valid.' })
76
- }
77
- throw errors.invalidInput('host', {
78
- zh: `主机配置不合法:${message}`,
79
- en: `Invalid host entry: ${message}`,
80
- })
81
- }
82
- ensureRuntime(ctx, entry)
83
- ctx.emitState()
84
- return hostViewFor(ctx, runtimeOf(ctx, entry.id))
85
- }
86
-
87
- export async function removeHost(ctx, id) {
88
- await ctx.init()
89
- const runtime = ctx.state.runtimes.get(id)
90
- if (runtime) {
91
- // A deleted host must not be resurrected by a timer scheduled before deletion.
92
- cancelReconnect(runtime)
93
- cancelIdleStop(runtime)
94
- await teardownRuntime(ctx, runtime, { stopRemote: runtime.entry.keepAlive === 'stop' })
95
- }
96
- ctx.state.runtimes.delete(id)
97
- await ctx.store.removeHost(id)
98
- if (ctx.state.activeHostId === id) ctx.state.activeHostId = null
99
- ctx.emitState()
100
- return { ok: true }
101
- }
102
-
103
- export function setActiveHost(ctx, id) {
104
- if (id !== null && !ctx.state.runtimes.has(id)) throw errors.invalidInput('id')
105
- ctx.state.activeHostId = id
106
- ctx.emitState()
107
- }
108
-
109
- export async function saveSettings(ctx, patch) {
110
- await ctx.init()
111
- const settings = await ctx.store.saveSettings(patch)
112
- ctx.emitState()
113
- return settings
114
- }
115
-
116
- /**
117
- * Browse directories inside the user's home so the client can pick a private-key
118
- * file instead of typing an absolute path. Read-only and home-confined.
119
- */
120
- export async function listKeyFiles(ctx, dir) {
121
- // The picker is rooted at the OS user home, not DSH_HOME: private keys live in
122
- // `~/.ssh` of the account, while the service's `home` is the DSH state root.
123
- const userHome = homedir()
124
- const listing = await listKeyFilesInHome({ home: userHome, dir: typeof dir === 'string' ? dir : '' })
125
- const settings = ctx.store.getSettings()
126
- return { ...listing, defaultKeyPath: settings.defaultKeyPath, defaultDir: path.join(userHome, '.ssh') }
127
- }
128
-
129
- /** Read-only SSH discovery for the wizard (design §15.1). */
130
- export async function discoverSshAliases(ctx) {
131
- const material = await ctx.deps.loadSshMaterial({ home: ctx.userHome() })
132
- const parsed = parseSshConfig(material.configText)
133
- const aliases = discoverAliasesFromConfig(parsed, { home: ctx.userHome() })
134
- const knownHosts = parseKnownHosts(material.knownHostsText)
135
- return {
136
- aliases: aliases.map((alias) => ({
137
- alias: alias.alias,
138
- host: alias.host,
139
- user: alias.user,
140
- port: alias.port,
141
- source: 'config',
142
- })),
143
- knownHosts: summarizeKnownHosts(knownHosts),
144
- }
145
- }
@@ -1,53 +0,0 @@
1
- /**
2
- * The per-host runtime object shared by the service and every helper.
3
- */
4
-
5
- export function emptyRemote() {
6
- return {
7
- version: null,
8
- uiReady: false,
9
- localPort: null,
10
- port: null,
11
- pid: null,
12
- dshHome: null,
13
- profile: null,
14
- bootstrapLevel: null,
15
- nodeVersion: null,
16
- nodeSource: null,
17
- startedAt: null,
18
- }
19
- }
20
-
21
- export function createHostRuntime(host) {
22
- return {
23
- id: host.id,
24
- entry: host,
25
- status: 'unconfigured',
26
- phase: null,
27
- progress: null,
28
- error: null,
29
- warning: null,
30
- fingerprint: host.pinnedFingerprint
31
- ? { sha256: host.pinnedFingerprint, keyType: 'pinned', status: 'pinned', pinned: host.pinnedFingerprint }
32
- : null,
33
- remote: emptyRemote(),
34
- ssh: null,
35
- jumpSsh: null,
36
- tunnel: null,
37
- token: null,
38
- password: null,
39
- facts: null,
40
- exchange: null,
41
- pendingHostKey: null,
42
- pendingConflict: null,
43
- conflict: null,
44
- desired: 'idle',
45
- reconnectAttempts: 0,
46
- reconnectTimer: null,
47
- idleTimer: null,
48
- connectPromise: null,
49
- closing: false,
50
- logs: [],
51
- logSeq: 0,
52
- }
53
- }
package/src/host-view.js DELETED
@@ -1,51 +0,0 @@
1
- /**
2
- * The client-facing view of one host (docs/api.md HostView).
3
- */
4
- import { versionParity } from './version.js'
5
- import { connectLogTail, connectLogVisible } from './connect-log.js'
6
-
7
- export function hostView(runtime, ctx) {
8
- const entry = runtime.entry
9
- return {
10
- id: runtime.id,
11
- name: entry.name,
12
- address: entry.address,
13
- addressMasked: maskAddress(entry),
14
- /** Never the secret itself; lets the Client ask for a one-time password. */
15
- authType: entry.auth?.type ?? 'key',
16
- /** The configured key file path (not a secret); lets the edit form prefill it. */
17
- authKeyPath: entry.auth?.type === 'key' && typeof entry.auth.keyPath === 'string' ? entry.auth.keyPath : null,
18
- /** Whether a remembered password exists in the credential store (never the value). */
19
- passwordSaved: entry.auth?.type === 'password' ? runtime.passwordSaved === true || runtime.password != null : false,
20
- passwordStorageAvailable: ctx.passwordStorageAvailable,
21
- jumpHost: entry.jumpHost ?? null,
22
- status: runtime.status,
23
- phase: runtime.phase,
24
- progress: runtime.progress,
25
- error: runtime.error,
26
- warning: runtime.warning,
27
- conflict: runtime.conflict,
28
- fingerprint: runtime.fingerprint,
29
- logs: connectLogVisible(runtime.status) ? connectLogTail(runtime) : [],
30
- remote: {
31
- ...runtime.remote,
32
- version: runtime.remote.version ?? null,
33
- },
34
- keepAlive: entry.keepAlive,
35
- idleMinutes: entry.idleMinutes,
36
- autoReconnect: entry.autoReconnect,
37
- hostKeyPolicy: entry.hostKeyPolicy,
38
- lastOpenedAt: entry.lastOpenedAt,
39
- createdAt: entry.createdAt,
40
- updatedAt: entry.updatedAt,
41
- targetVersion: ctx.targetVersion,
42
- versionParity: versionParity(ctx.targetVersion, runtime.remote.version ?? null),
43
- }
44
- }
45
-
46
- function maskAddress(entry) {
47
- const port = entry.port && entry.port !== 22 ? `:${entry.port}` : ''
48
- const user = entry.username ? `${entry.username}@` : ''
49
- const host = entry.address || '?'
50
- return `${user}${host}${port}`
51
- }
package/src/index.js DELETED
@@ -1,162 +0,0 @@
1
- /**
2
- * dsh-remote-go — Host half: registers the local HTTP API the browser panel uses and owns the SSH / bootstrap / tunnel lifecycle; it never proxies UI bytes.
3
- */
4
- import { API_PREFIX, PLUGIN_ID } from './constants.js'
5
- import { statSync } from 'node:fs'
6
- import path from 'node:path'
7
- import { createApi } from './api.js'
8
- import { detectLocalEnginesNode, detectLocalVersion } from './local-version.js'
9
- import { RemoteGoService } from './service.js'
10
- import { createSecretStore } from './secrets.js'
11
- import { HostStore, resolveDshHome, resolveStateDir } from './store.js'
12
- import { messageOf } from './util.js'
13
-
14
- export const name = PLUGIN_ID
15
- export const inject = ['webServer']
16
-
17
- export const optional = ['connection', 'credentials']
18
-
19
- export function apply(ctx, config = {}) {
20
- const logger = createLogger()
21
- const home = config.home ? String(config.home) : resolveDshHome(process.env)
22
- const stateDir = resolveStateDir(home)
23
- const store = new HostStore({ dir: stateDir, logger })
24
- // Saved SSH passwords live in DSH's credential store, never in hosts.json.
25
- const secrets = createSecretStore({ ctx, logger })
26
- const service = new RemoteGoService({
27
- store,
28
- home,
29
- logger,
30
- secrets,
31
- localVersion: config.localVersion ? String(config.localVersion) : null,
32
- hostKeyConfirmTimeoutMs: config.hostKeyConfirmTimeoutMs,
33
- })
34
- const getOrigin = () => {
35
- try {
36
- return ctx.webServer?.getOrigin?.() ?? null
37
- } catch {
38
- return null
39
- }
40
- }
41
- const api = createApi({
42
- service,
43
- getOrigin,
44
- logger,
45
- diagnostics: () =>
46
- describeSelf(ctx, {
47
- home,
48
- stateDir,
49
- localVersion: service.localVersion,
50
- engineNodeRange: service.engineNodeRange,
51
- }),
52
- })
53
-
54
- ctx.effect(() => {
55
- const disposeRoute = ctx.webServer.register({
56
- kind: 'prefix',
57
- path: API_PREFIX,
58
- handler: (/** @type {any} */ req, /** @type {any} */ res) => {
59
- void api.handler(req, res)
60
- },
61
- })
62
- logger.info(`API mounted at ${API_PREFIX} (state dir ${stateDir})`)
63
-
64
- void (async () => {
65
- try {
66
- await service.init()
67
- const detected = await detectLocalVersion({ ctx })
68
- if (detected.version) service.setLocalVersion(detected.version, detected.source)
69
- // The managed Node version is the lower bound of DSH's own `engines.node`;
70
- // reading it here keeps the plugin in step with the running DSH build.
71
- const engine = await detectLocalEnginesNode({ ctx })
72
- if (engine.range) service.setLocalEnginesNode(engine.range, engine.source)
73
- if (!detected.version)
74
- logger.warn(
75
- 'could not detect the local DSH version; the remote npx runtime cannot be pinned to this machine, so connections will fail until the version is readable',
76
- )
77
- } catch (error) {
78
- logger.error('initialization failed:', error)
79
- }
80
- })()
81
-
82
- return () => {
83
- api.dispose()
84
- void service.shutdown()
85
- disposeRoute()
86
- logger.info('unloaded')
87
- }
88
- }, 'dsh-remote-go: http api + service')
89
-
90
- return service
91
- }
92
-
93
- function describeSelf(ctx, info) {
94
- const out = {
95
- home: info.home,
96
- stateDir: info.stateDir,
97
- hostVersion: info.localVersion,
98
- engineNodeRange: info.engineNodeRange ?? null,
99
- entry: null,
100
- client: null,
101
- }
102
- try {
103
- const entry = ctx?.fiber?.entry
104
- out.entry = {
105
- id: entry?.options?.id ?? null,
106
- name: entry?.options?.name ?? null,
107
- }
108
- } catch {
109
- /* fiber shape is loader-internal; diagnostics must never throw */
110
- }
111
- try {
112
- const clientModules = ctx?.get?.('clientModules') ?? ctx?.clientModules
113
- const graph = clientModules?.graph?.()
114
- const clientPath = clientModules?.clientPath?.(PLUGIN_ID) ?? null
115
- const row = Array.isArray(graph?.entries) ? (graph.entries.find((item) => item.id === PLUGIN_ID) ?? null) : null
116
- let bundle = null
117
- if (clientPath) {
118
- try {
119
- const stat = statSync(clientPath)
120
- bundle = { path: clientPath, size: stat.size, mtimeMs: stat.mtimeMs }
121
- } catch (error) {
122
- bundle = { path: clientPath, error: messageOf(error) }
123
- }
124
- }
125
- out.client = {
126
- graph: graph ? { rev: graph.rev ?? null, release: graph.release ?? null, entries: graph.entries.length } : null,
127
- row: row
128
- ? { id: row.id, rev: row.rev, url: row.url, inject: row.inject ?? [], immediately: row.immediately === true }
129
- : null,
130
- clientPath,
131
- bundle,
132
- }
133
- } catch (error) {
134
- out.client = { error: messageOf(error) }
135
- }
136
- return out
137
- }
138
-
139
- function createLogger() {
140
- const tag = '[dsh-remote-go]'
141
- const write = (/** @type {'info'|'warn'|'error'|'debug'} */ level, /** @type {any[]} */ args) => {
142
- const sink =
143
- level === 'debug'
144
- ? console.debug
145
- : level === 'error'
146
- ? console.error
147
- : level === 'warn'
148
- ? console.warn
149
- : console.info
150
- try {
151
- sink?.call(console, tag, ...args)
152
- } catch {
153
- /* logging must never throw */
154
- }
155
- }
156
- return {
157
- info: (...args) => write('info', args),
158
- warn: (...args) => write('warn', args),
159
- error: (...args) => write('error', args),
160
- debug: (...args) => write('debug', args),
161
- }
162
- }
package/src/key-files.js DELETED
@@ -1,49 +0,0 @@
1
- /**
2
- * Read-only directory browsing for the key-file picker; a path that resolves outside the user home directory (through `..` or a symlink) is refused.
3
- */
4
- import { promises as fs } from 'node:fs'
5
- import path from 'node:path'
6
- import { expandHome } from './util.js'
7
-
8
- const MAX_ENTRIES = 500
9
-
10
- export async function listKeyFiles(options) {
11
- const home = path.resolve(options.home)
12
- const impl = options.fsImpl ?? fs
13
- // Canonical base: the home directory spelled the way the filesystem reports it.
14
- // Every path below derives from this one spelling, so the returned `path` and
15
- // `parent` can never disagree — Windows hands out an 8.3 short path
16
- // (`C:\Users\RUNNER~1\…`) for a directory that realpath reports in long form.
17
- const realHome = await impl.realpath(home).catch(() => home)
18
- const requested = expandHome(options.dir, realHome)
19
- const target = path.resolve(requested || path.join(realHome, '.ssh'))
20
- // Resolve first, then judge: a symlinked directory may lead outside home. A path
21
- // that does not exist keeps its requested spelling, which the check still judges.
22
- const realTarget = await impl.realpath(target).catch(() => target)
23
- if (realTarget !== realHome && !realTarget.startsWith(realHome + path.sep)) {
24
- throw new Error('key-file path must stay inside the home directory')
25
- }
26
-
27
- const dirents = await impl.readdir(realTarget, { withFileTypes: true })
28
- const entries = []
29
- for (const dirent of dirents) {
30
- const full = path.join(realTarget, dirent.name)
31
- const isDirectory = dirent.isDirectory()
32
- // Only regular files and directories are selectable; a socket or device node
33
- // in a home directory is never a private key.
34
- if (!isDirectory && !dirent.isFile()) continue
35
- entries.push({ name: dirent.name, path: full, isDirectory })
36
- }
37
- entries.sort((left, right) => {
38
- if (left.isDirectory !== right.isDirectory) return left.isDirectory ? -1 : 1
39
- return left.name.localeCompare(right.name)
40
- })
41
- const shown = entries.slice(0, MAX_ENTRIES)
42
- const parent = realTarget === realHome ? null : path.dirname(realTarget)
43
- return {
44
- path: realTarget,
45
- parent: parent ?? realHome,
46
- entries: shown,
47
- truncated: entries.length > shown.length,
48
- }
49
- }