dsh-remote-go 0.2.0 → 0.3.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 (135) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7144 -8367
  3. package/dist/index.js +4 -0
  4. package/dist/src/admission.js +21 -0
  5. package/dist/src/api.js +380 -0
  6. package/dist/src/atomic-json.js +201 -0
  7. package/dist/src/bootstrap.js +96 -0
  8. package/dist/src/connect/attach.js +21 -0
  9. package/dist/src/connect/bootstrap.js +8 -0
  10. package/dist/src/connect/failures.js +29 -0
  11. package/dist/src/connect/guards.js +36 -0
  12. package/dist/src/connect/launch.js +70 -0
  13. package/dist/src/connect/links.js +54 -0
  14. package/dist/src/connect/ownership.js +139 -0
  15. package/dist/src/connect/pipeline.js +376 -0
  16. package/dist/src/connect/reattach.js +191 -0
  17. package/dist/src/connect/registry.js +10 -0
  18. package/dist/src/connect/repair.js +97 -0
  19. package/dist/src/connect/restart.js +255 -0
  20. package/dist/src/connect/stop.js +164 -0
  21. package/dist/src/connect/transport.js +101 -0
  22. package/dist/src/connect/verify.js +30 -0
  23. package/dist/src/connect/watchdog.js +44 -0
  24. package/dist/src/connect-log.js +137 -0
  25. package/dist/src/connect-progress.js +110 -0
  26. package/dist/src/constants.js +29 -0
  27. package/dist/src/context.js +96 -0
  28. package/dist/src/diagnostics.js +133 -0
  29. package/dist/src/download-jobs.js +221 -0
  30. package/dist/src/errors.js +228 -0
  31. package/dist/src/events.js +326 -0
  32. package/dist/src/host-lifecycle.js +368 -0
  33. package/dist/src/host-registry.js +181 -0
  34. package/dist/src/host-runtime.js +77 -0
  35. package/dist/src/host-view.js +52 -0
  36. package/dist/src/index.js +196 -0
  37. package/dist/src/kernel-adapter.js +388 -0
  38. package/dist/src/key-files.js +39 -0
  39. package/dist/src/known-hosts.js +104 -0
  40. package/dist/src/layout.js +26 -0
  41. package/dist/src/local-download.js +311 -0
  42. package/dist/src/local-ssh.js +23 -0
  43. package/dist/src/local-version.js +87 -0
  44. package/dist/src/node/download.js +157 -0
  45. package/dist/src/node-runtime.js +327 -0
  46. package/dist/src/probe.js +95 -0
  47. package/dist/src/prompts.js +198 -0
  48. package/dist/src/proxy/cookies.js +102 -0
  49. package/dist/src/proxy/headers.js +167 -0
  50. package/dist/src/proxy/http.js +134 -0
  51. package/dist/src/proxy/index.js +121 -0
  52. package/dist/src/proxy/limits.js +6 -0
  53. package/dist/src/proxy/routes.js +32 -0
  54. package/dist/src/proxy/upgrade.js +160 -0
  55. package/dist/src/redact.js +85 -0
  56. package/dist/src/remote-files.js +60 -0
  57. package/dist/src/remote-path.js +82 -0
  58. package/dist/src/remote-proc.js +271 -0
  59. package/dist/src/remote-web/registry.js +107 -0
  60. package/dist/src/remote-web/resolve.js +229 -0
  61. package/dist/src/remote-web/start.js +190 -0
  62. package/dist/src/remote-web/stop.js +74 -0
  63. package/dist/src/request-trust.js +70 -0
  64. package/dist/src/runtime/dispatch.js +200 -0
  65. package/dist/src/runtime/effects.js +81 -0
  66. package/dist/src/runtime/events.js +35 -0
  67. package/dist/src/runtime/fsm.js +70 -0
  68. package/dist/src/runtime/rules.js +480 -0
  69. package/dist/src/secrets.js +119 -0
  70. package/dist/src/service.js +300 -0
  71. package/dist/src/settings.js +143 -0
  72. package/dist/src/ssh-config.js +257 -0
  73. package/dist/src/ssh-failures.js +71 -0
  74. package/dist/src/ssh-port.js +4 -0
  75. package/dist/src/ssh-sftp.js +258 -0
  76. package/dist/src/ssh.js +395 -0
  77. package/dist/src/store.js +174 -0
  78. package/dist/src/tool-shared.js +146 -0
  79. package/dist/src/tools-exec-policy.js +121 -0
  80. package/dist/src/tools-exec.js +307 -0
  81. package/dist/src/tools-report.js +357 -0
  82. package/dist/src/tools.js +337 -0
  83. package/dist/src/tunnel.js +111 -0
  84. package/dist/src/util.js +112 -0
  85. package/dist/src/version.js +108 -0
  86. package/dist/src/watchdog-bus.js +21 -0
  87. package/dist/src/watchdog.js +116 -0
  88. package/index.js +5 -4
  89. package/locale/en.json +1 -1
  90. package/locale/zh.json +1 -1
  91. package/package.json +37 -19
  92. package/src/admission.js +0 -43
  93. package/src/api.js +0 -536
  94. package/src/atomic-json.js +0 -225
  95. package/src/bootstrap.js +0 -113
  96. package/src/connect-log.js +0 -176
  97. package/src/connect-pipeline.js +0 -1900
  98. package/src/connect-progress.js +0 -155
  99. package/src/constants.js +0 -93
  100. package/src/diagnostics.js +0 -160
  101. package/src/download-jobs.js +0 -234
  102. package/src/errors.js +0 -412
  103. package/src/host-lifecycle.js +0 -604
  104. package/src/host-registry.js +0 -217
  105. package/src/host-runtime.js +0 -127
  106. package/src/host-view.js +0 -75
  107. package/src/index.js +0 -206
  108. package/src/key-files.js +0 -54
  109. package/src/known-hosts.js +0 -133
  110. package/src/layout.js +0 -53
  111. package/src/local-download.js +0 -381
  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 -101
  116. package/src/prompts.js +0 -229
  117. package/src/redact.js +0 -68
  118. package/src/remote-files.js +0 -71
  119. package/src/remote-path.js +0 -137
  120. package/src/remote-proc.js +0 -343
  121. package/src/remote-proxy.js +0 -815
  122. package/src/remote-web.js +0 -751
  123. package/src/request-trust.js +0 -89
  124. package/src/secrets.js +0 -109
  125. package/src/service.js +0 -459
  126. package/src/settings.js +0 -163
  127. package/src/ssh-config.js +0 -271
  128. package/src/ssh.js +0 -731
  129. package/src/store.js +0 -193
  130. package/src/tools.js +0 -386
  131. package/src/tunnel.js +0 -132
  132. package/src/util.js +0 -153
  133. package/src/version.js +0 -103
  134. package/src/webapp.js +0 -43
  135. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
@@ -1,217 +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, OUTSIDE_HOME } from './key-files.js'
10
- import { parseKnownHosts, summarizeKnownHosts } from './known-hosts.js'
11
- import {
12
- cancelIdleStop,
13
- cancelReconnect,
14
- startRemoteHeartbeat,
15
- stopRemoteHeartbeat,
16
- teardownRuntime,
17
- } from './host-lifecycle.js'
18
- import { discoverSshAliases as discoverAliasesFromConfig, parseSshConfig } from './ssh-config.js'
19
-
20
- function ensureRuntime(ctx, host) {
21
- const existing = ctx.state.runtimes.get(host.id)
22
- if (existing) {
23
- existing.entry = host
24
- return existing
25
- }
26
- const runtime = createHostRuntime(host)
27
- ctx.state.runtimes.set(host.id, runtime)
28
- return runtime
29
- }
30
-
31
- export function runtimeOf(ctx, id) {
32
- const runtime = ctx.state.runtimes.get(id)
33
- if (!runtime) throw errors.invalidInput('id', { zh: `未知主机 ${id}`, en: `Unknown host ${id}` })
34
- return runtime
35
- }
36
-
37
- export async function initRegistry(ctx) {
38
- if (ctx.state.initialized) return
39
- await ctx.store.load()
40
- for (const host of ctx.store.listHosts()) ensureRuntime(ctx, host)
41
- // `passwordSaved` is a fact about the credential store, not about this process: without this
42
- // read the Client would ask again after every DSH restart even though the password is saved,
43
- // and the saved value would never be tried.
44
- await restoreSavedPasswords(ctx)
45
- ctx.state.initialized = true
46
- }
47
-
48
- /**
49
- * Re-read which password-auth hosts have a saved password. Only presence is loaded; the secret
50
- * itself stays in the credential store until a connection actually needs it.
51
- * @param {object} ctx - service context.
52
- */
53
- async function restoreSavedPasswords(ctx) {
54
- if (!ctx.secrets) return
55
- await Promise.all(
56
- [...ctx.state.runtimes.values()].map(async (runtime) => {
57
- if (runtime.entry.auth?.type !== 'password') {
58
- runtime.passwordSaved = false
59
- return
60
- }
61
- runtime.passwordSaved = await ctx.secrets.has(runtime.id)
62
- }),
63
- )
64
- }
65
-
66
- function hostViewFor(ctx, runtime) {
67
- return hostView(runtime, {
68
- targetVersion: ctx.localVersion(),
69
- passwordStorageAvailable: ctx.secrets ? ctx.secrets.available() === true : false,
70
- // A quarantined hosts.json means the list beside it is the empty recovery fallback.
71
- storeCorrupt: ctx.store?.hostsCorrupt === true,
72
- })
73
- }
74
-
75
- /** Build the client-facing state snapshot (contract: docs/api.md). */
76
- export function snapshot(ctx) {
77
- const localVersion = ctx.localVersion()
78
- const hosts = [...ctx.state.runtimes.values()].map((runtime) => hostViewFor(ctx, runtime))
79
- return {
80
- hostVersion: localVersion,
81
- targetVersion: localVersion,
82
- hosts,
83
- settings: ctx.store.getSettings(),
84
- activeHostId: ctx.state.activeHostId,
85
- firstRun: hosts.length === 0,
86
- /** Whether a password typed for any host can be persisted at all (the Client hides the choice). */
87
- passwordStorageAvailable: ctx.secrets ? ctx.secrets.available() === true : false,
88
- // Store-wide, and deliberately not per host: a quarantined hosts.json leaves this list
89
- // empty, which is exactly the case the user has to be told about.
90
- storeCorrupt: ctx.store?.hostsCorrupt === true,
91
- }
92
- }
93
-
94
- export async function saveHost(ctx, rawHost) {
95
- await ctx.init()
96
- // The auth mode as it is stored now: a switch away from password must not leave its secret
97
- // behind as an orphaned credential record.
98
- const previousAuth =
99
- rawHost && typeof rawHost === 'object' && typeof rawHost.id === 'string'
100
- ? (ctx.store.getHost(rawHost.id)?.auth?.type ?? null)
101
- : null
102
- let entry
103
- try {
104
- entry = await ctx.store.upsertHost(rawHost, { settings: ctx.store.getSettings() })
105
- } catch (error) {
106
- // The store's validators throw bare messages; map them to the client's field
107
- // errors here so the contract stays typed.
108
- const message = error instanceof Error ? error.message : String(error)
109
- if (message === 'address is required') {
110
- throw errors.invalidInput('address', {
111
- zh: '请填写服务器地址或 ~/.ssh/config 别名。',
112
- en: 'Enter a server address or an ~/.ssh/config alias.',
113
- })
114
- }
115
- if (message === 'address is invalid') {
116
- throw errors.invalidInput('address', { zh: '服务器地址格式不正确。', en: 'The server address is not valid.' })
117
- }
118
- throw errors.invalidInput('host', {
119
- zh: `主机配置不合法:${message}`,
120
- en: `Invalid host entry: ${message}`,
121
- })
122
- }
123
- const runtime = ensureRuntime(ctx, entry)
124
- if (previousAuth === 'password' && entry.auth?.type !== 'password') {
125
- await ctx.secrets?.remove(entry.id)
126
- runtime.passwordSaved = false
127
- runtime.password = null
128
- }
129
- ctx.emitState()
130
- return hostViewFor(ctx, runtime)
131
- }
132
-
133
- export async function removeHost(ctx, id) {
134
- await ctx.init()
135
- const runtime = ctx.state.runtimes.get(id)
136
- if (runtime) {
137
- // A deleted host must not be resurrected by a timer scheduled before deletion, and a
138
- // connect pipeline still in flight must see that the user no longer wants it: it may
139
- // never publish a connected state or a fresh `activeHostId` afterwards (H4).
140
- runtime.desired = 'idle'
141
- cancelReconnect(runtime)
142
- cancelIdleStop(runtime)
143
- if (ctx.state.activeHostId === id) ctx.state.activeHostId = null
144
- await teardownRuntime(ctx, runtime, { stopRemote: runtime.entry.keepAlive === 'stop' })
145
- }
146
- ctx.state.runtimes.delete(id)
147
- await ctx.store.removeHost(id)
148
- // The host is gone: its saved password must not outlive it in the credential store.
149
- await ctx.secrets?.remove(id)
150
- if (ctx.state.activeHostId === id) ctx.state.activeHostId = null
151
- ctx.emitState()
152
- return { ok: true }
153
- }
154
-
155
- export function setActiveHost(ctx, id) {
156
- if (id !== null && !ctx.state.runtimes.has(id)) throw errors.invalidInput('id')
157
- ctx.state.activeHostId = id
158
- ctx.emitState()
159
- }
160
-
161
- export async function saveSettings(ctx, patch) {
162
- await ctx.init()
163
- const settings = await ctx.store.saveSettings(patch)
164
- // The liveness switch applies to hosts that are already connected, not just the next one.
165
- for (const runtime of ctx.state.runtimes.values()) {
166
- if (runtime.status !== 'connected') continue
167
- if (settings.remoteHeartbeat.enabled) startRemoteHeartbeat(ctx, runtime)
168
- else stopRemoteHeartbeat(runtime)
169
- }
170
- ctx.emitState()
171
- return settings
172
- }
173
-
174
- /**
175
- * Browse directories inside the user's home so the client can pick a private-key
176
- * file instead of typing an absolute path. Read-only and home-confined.
177
- */
178
- export async function listKeyFiles(ctx, dir) {
179
- // The picker is rooted at the OS user home, not DSH_HOME: private keys live in
180
- // `~/.ssh` of the account, while the service's `home` is the DSH state root.
181
- const userHome = homedir()
182
- let listing
183
- try {
184
- listing = await listKeyFilesInHome({ home: userHome, dir: typeof dir === 'string' ? dir : '' })
185
- } catch (error) {
186
- // A path outside the home directory (`C:\Windows`, `..`, a symlink escape) or an
187
- // unreadable one is the caller's mistake: answer 400 instead of turning a bare `Error`
188
- // into a 500, and never echo the requested path back in `technical`.
189
- if (error?.code === OUTSIDE_HOME || ['ENOENT', 'EACCES', 'EPERM', 'ENOTDIR'].includes(error?.code)) {
190
- throw errors.invalidInput('path', {
191
- zh: '这个目录不在用户主目录内,或无法读取。',
192
- en: 'This folder is outside the home directory, or cannot be read.',
193
- })
194
- }
195
- throw error
196
- }
197
- const settings = ctx.store.getSettings()
198
- return { ...listing, defaultKeyPath: settings.defaultKeyPath, defaultDir: path.join(userHome, '.ssh') }
199
- }
200
-
201
- /** Read-only SSH discovery for the wizard (design §15.1). */
202
- export async function discoverSshAliases(ctx) {
203
- const material = await ctx.deps.loadSshMaterial({ home: ctx.userHome() })
204
- const parsed = parseSshConfig(material.configText)
205
- const aliases = discoverAliasesFromConfig(parsed, { home: ctx.userHome() })
206
- const knownHosts = parseKnownHosts(material.knownHostsText)
207
- return {
208
- aliases: aliases.map((alias) => ({
209
- alias: alias.alias,
210
- host: alias.host,
211
- user: alias.user,
212
- port: alias.port,
213
- source: 'config',
214
- })),
215
- knownHosts: summarizeKnownHosts(knownHosts),
216
- }
217
- }
@@ -1,127 +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
- * Bumped on every successful attach (connect, local restart, remote re-attach).
20
- * The Client uses it to know that its warm carrier holds a launch URL and a
21
- * session cookie from the previous tunnel, so it must navigate again.
22
- */
23
- viewRev: 0,
24
- }
25
- }
26
-
27
- export function createHostRuntime(host) {
28
- return {
29
- id: host.id,
30
- entry: host,
31
- status: 'unconfigured',
32
- phase: null,
33
- progress: null,
34
- error: null,
35
- warning: null,
36
- fingerprint: host.pinnedFingerprint
37
- ? { sha256: host.pinnedFingerprint, keyType: 'pinned', status: 'pinned', pinned: host.pinnedFingerprint }
38
- : null,
39
- /**
40
- * The jump host's own host key context: `{ sha256, keyType, status, pinned }`. Kept apart
41
- * from `fingerprint` (the target) so a jump-host confirmation can never pin the target
42
- * and a target pin can never be checked against the jump host (B1).
43
- */
44
- jumpFingerprint: null,
45
- remote: emptyRemote(),
46
- ssh: null,
47
- jumpSsh: null,
48
- tunnel: null,
49
- token: null,
50
- password: null,
51
- /**
52
- * What to do with `password` once SSH accepts it: write it to the credential store, or
53
- * remove the stored record (an explicit "this connection only"). Both reset per attempt.
54
- */
55
- savePassword: false,
56
- forgetPassword: false,
57
- /** Mirrors the credential store for `HostView.passwordSaved` (restored on load). */
58
- passwordSaved: false,
59
- facts: null,
60
- /**
61
- * The last known remote home, managed web pid and profile. `facts`/`remote` are cleared by
62
- * every teardown, but the idle policy still has to prove and stop the right process on the
63
- * right host path afterwards (H1).
64
- */
65
- remoteHome: null,
66
- remotePid: null,
67
- remoteProfile: null,
68
- exchange: null,
69
- pendingHostKey: null,
70
- pendingConflict: null,
71
- conflict: null,
72
- desired: 'idle',
73
- /**
74
- * The user answered a prompt with "no" (or let it time out): the connection attempt must
75
- * not be retried automatically, because a retry would ask the same question again (H2).
76
- */
77
- connectCancelled: false,
78
- /**
79
- * The transport this attempt was dialling closed under the pipeline (including while the
80
- * handshake was still waiting for a host-key answer). Such a failure is a dropped link,
81
- * not an auth/key decision (H3).
82
- */
83
- transportLost: false,
84
- reconnectAttempts: 0,
85
- reconnectTimer: null,
86
- idleTimer: null,
87
- connectPromise: null,
88
- /** One-shot link actions (local restart / remote re-attach / listener repair / stop) and their token. */
89
- linkBusy: null,
90
- linkToken: 0,
91
- restartPromise: null,
92
- reattachPromise: null,
93
- /**
94
- * Processes this connection actually launched (pid -> start time), plus pids adopted from a
95
- * registry record written by a launch. Only these may ever be stopped; a pid a re-attach
96
- * discovered gets display rights, never kill rights.
97
- */
98
- launched: new Map(),
99
- /**
100
- * The remote web this connection is bound to, with the `/proc` identity proved when it bound:
101
- * `{ pid, startTime, origin: 'launch' | 'reattach' }`. A re-attached pid lives here (never in
102
- * `launched`), so the explicit "Stop remote DSH" action can stop exactly that one process
103
- * without granting the kill right to a restart.
104
- */
105
- bound: null,
106
- /** Current tunnel repair (a broken local listener under a healthy remote). */
107
- tunnelRepair: null,
108
- tunnelRepairFailures: 0,
109
- nextTunnelRepairAt: 0,
110
- /** Liveness probes: a confirmed episode is two consecutive failed probes. */
111
- heartbeatTimer: null,
112
- remoteCheckTimer: null,
113
- remoteFailures: 0,
114
- remoteEpisode: false,
115
- episodeSource: null,
116
- episodeCooldownUntil: 0,
117
- /** Processes kept alongside this connection (chosen in the conflict prompt). */
118
- alongsidePids: [],
119
- /** Bounded, client-independent record of restarts / re-attaches for diagnostics. */
120
- restarts: [],
121
- closing: false,
122
- logs: [],
123
- logSeq: 0,
124
- // Which connection this runtime is on; the connect log starts at 1 and resets its ring.
125
- connectCount: 0,
126
- }
127
- }
package/src/host-view.js DELETED
@@ -1,75 +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
- /**
15
- * The plain connection fields. The masked address is presentation only: the editor must not
16
- * parse it back (a bare IPv6 like `fe80::1` used to yield port 1, and the default port was
17
- * silently replaced by 22). Never a secret.
18
- */
19
- username: entry.username ?? null,
20
- port: entry.port ?? 22,
21
- /** Never the secret itself; lets the Client ask for a one-time password. */
22
- authType: entry.auth?.type ?? 'key',
23
- /** The configured key file path (not a secret); lets the edit form prefill it. */
24
- authKeyPath: entry.auth?.type === 'key' && typeof entry.auth.keyPath === 'string' ? entry.auth.keyPath : null,
25
- /**
26
- * Whether a remembered password exists in the credential store (never the value). The
27
- * runtime mirror is restored from the store on load, so this stays true across a DSH
28
- * restart while a one-time password used for this connection alone stays false.
29
- */
30
- passwordSaved: entry.auth?.type === 'password' ? runtime.passwordSaved === true : false,
31
- passwordStorageAvailable: ctx.passwordStorageAvailable,
32
- jumpHost: entry.jumpHost ?? null,
33
- status: runtime.status,
34
- phase: runtime.phase,
35
- progress: runtime.progress,
36
- error: runtime.error,
37
- warning: runtime.warning,
38
- conflict: runtime.conflict,
39
- fingerprint: runtime.fingerprint,
40
- logs: connectLogVisible(runtime.status) ? connectLogTail(runtime) : [],
41
- remote: {
42
- ...runtime.remote,
43
- version: runtime.remote.version ?? null,
44
- },
45
- keepAlive: entry.keepAlive,
46
- idleMinutes: entry.idleMinutes,
47
- autoReconnect: entry.autoReconnect,
48
- hostKeyPolicy: entry.hostKeyPolicy,
49
- lastOpenedAt: entry.lastOpenedAt,
50
- createdAt: entry.createdAt,
51
- updatedAt: entry.updatedAt,
52
- targetVersion: ctx.targetVersion,
53
- versionParity: versionParity(ctx.targetVersion, runtime.remote.version ?? null),
54
- /**
55
- * True when `hosts.json` was unreadable on load: this list is the recovered fallback, and a
56
- * copy of the damaged file is kept next to it (`hosts.json.corrupt-<timestamp>`). Contract
57
- * field only — the Client renders it as a warning (docs/api.md HostView).
58
- */
59
- storeCorrupt: ctx.storeCorrupt === true,
60
- }
61
- }
62
-
63
- /**
64
- * The display form of the endpoint: `user@host`, `user@host:2222`, and bracketed IPv6
65
- * (`user@[fe80::1]`, `user@[fe80::1]:2222`). The port is omitted only for SSH's default 22, which
66
- * is why the Client reads `port`/`username` instead of parsing this string.
67
- */
68
- export function maskAddress(entry) {
69
- const port = entry.port && entry.port !== 22 ? `:${entry.port}` : ''
70
- const user = entry.username ? `${entry.username}@` : ''
71
- const raw = entry.address || '?'
72
- // An unbracketed address containing a colon is IPv6 in URL/SSH notation.
73
- const host = raw.includes(':') && !(raw.startsWith('[') && raw.endsWith(']')) ? `[${raw}]` : raw
74
- return `${user}${host}${port}`
75
- }
package/src/index.js DELETED
@@ -1,206 +0,0 @@
1
- /**
2
- * dsh-remote-go — Host half: registers the local HTTP API and the browser half's same-origin remote proxy,
3
- * and owns the SSH / bootstrap / tunnel lifecycle; it never copies remote data.
4
- */
5
- import { API_PREFIX, PLUGIN_ID, REMOTE_VIEW_PREFIX } from './constants.js'
6
- import { statSync } from 'node:fs'
7
- import { createAdmission } from './admission.js'
8
- import { createApi } from './api.js'
9
- import { detectLocalEnginesNode, detectLocalVersion } from './local-version.js'
10
- import { createRemoteProxy } from './remote-proxy.js'
11
- import { RemoteGoService } from './service.js'
12
- import { createSecretStore } from './secrets.js'
13
- import { HostStore, resolveDshHome, resolveStateDir } from './store.js'
14
- import { registerHostTools } from './tools.js'
15
- import { messageOf } from './util.js'
16
-
17
- export const name = PLUGIN_ID
18
- export const inject = ['webServer']
19
-
20
- export const optional = ['connection', 'credentials']
21
-
22
- export function apply(ctx, config = {}) {
23
- const logger = createLogger()
24
- const home = config.home ? String(config.home) : resolveDshHome(process.env)
25
- const stateDir = resolveStateDir(home)
26
- const store = new HostStore({ dir: stateDir, logger })
27
- // Saved SSH passwords live in DSH's credential store, never in hosts.json.
28
- const secrets = createSecretStore({ ctx, logger })
29
- const service = new RemoteGoService({
30
- store,
31
- home,
32
- logger,
33
- secrets,
34
- localVersion: config.localVersion ? String(config.localVersion) : null,
35
- hostKeyConfirmTimeoutMs: config.hostKeyConfirmTimeoutMs,
36
- })
37
- const getOrigin = () => {
38
- try {
39
- return ctx.webServer?.getOrigin?.() ?? null
40
- } catch {
41
- return null
42
- }
43
- }
44
- // DSH's own admission for every route this plugin serves: the kernel's Host/Origin fence plus
45
- // browser-session authentication. `connection` is optional, so the gate hands the request to the
46
- // plugin's own fence when the service is absent (see admission.js).
47
- const admit = createAdmission(ctx, logger)
48
- const api = createApi({
49
- service,
50
- getOrigin,
51
- admit,
52
- logger,
53
- diagnostics: () =>
54
- describeSelf(ctx, {
55
- home,
56
- stateDir,
57
- localVersion: service.localVersion,
58
- engineNodeRange: service.engineNodeRange,
59
- storeCorrupt: store.hostsCorrupt,
60
- }),
61
- })
62
- // The browser half's remote window lives on the local origin (the desktop half uses a guest
63
- // instead), so the same-origin proxy is the only thing that needs to know how to reach a tunnel.
64
- const proxy = createRemoteProxy({
65
- webServer: ctx.webServer,
66
- getOrigin,
67
- admit,
68
- resolveHost: (id) => service.webViewTarget(id),
69
- // A failed upstream is a suspicion, not a restart: the service confirms it with probes.
70
- onUpstreamError: (id) => service.noteUpstreamFailure(id),
71
- logger,
72
- })
73
-
74
- ctx.effect(() => {
75
- const disposeRoute = ctx.webServer.register({
76
- kind: 'prefix',
77
- path: API_PREFIX,
78
- handler: (/** @type {any} */ req, /** @type {any} */ res) => {
79
- void api.handler(req, res)
80
- },
81
- })
82
- const disposeView = ctx.webServer.register({
83
- kind: 'prefix',
84
- path: proxy.routePath,
85
- handler: (/** @type {any} */ req, /** @type {any} */ res) => proxy.handle(req, res),
86
- })
87
- // The model-facing host list lives on the Host half only: a local LLM session reads the same
88
- // snapshot the switcher renders, and the remote DSH never loads this package.
89
- const disposeTools = registerHostTools(ctx, { service, logger })
90
- const syncViewRoutes = () => proxy.sync(service.hostIds())
91
- service.on('state', syncViewRoutes)
92
- logger.info(`API mounted at ${API_PREFIX} (state dir ${stateDir})`)
93
- logger.info(`remote view mounted at ${REMOTE_VIEW_PREFIX}<host> (browser carrier)`)
94
-
95
- void (async () => {
96
- try {
97
- await service.init()
98
- syncViewRoutes()
99
- const detected = await detectLocalVersion({ ctx })
100
- if (detected.version) service.setLocalVersion(detected.version, detected.source)
101
- // The managed Node version is the lower bound of DSH's own `engines.node`;
102
- // reading it here keeps the plugin in step with the running DSH build.
103
- const engine = await detectLocalEnginesNode({ ctx })
104
- if (engine.range) service.setLocalEnginesNode(engine.range, engine.source)
105
- if (!detected.version)
106
- logger.warn(
107
- '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',
108
- )
109
- } catch (error) {
110
- logger.error('initialization failed:', error)
111
- }
112
- })()
113
-
114
- return () => {
115
- service.removeListener('state', syncViewRoutes)
116
- // A failing disposer must not skip the rest of the unload: the proxy, the API and the SSH
117
- // transports below still have to be released.
118
- try {
119
- disposeTools()
120
- } catch (error) {
121
- logger.error('unload: could not dispose the model tools:', error)
122
- }
123
- proxy.dispose()
124
- api.dispose()
125
- void service.shutdown()
126
- disposeRoute()
127
- disposeView()
128
- logger.info('unloaded')
129
- }
130
- }, 'dsh-remote-go: http api + service')
131
-
132
- return service
133
- }
134
-
135
- function describeSelf(ctx, info) {
136
- const out = {
137
- home: info.home,
138
- stateDir: info.stateDir,
139
- hostVersion: info.localVersion,
140
- engineNodeRange: info.engineNodeRange ?? null,
141
- // True when hosts.json was unreadable and the list beside it is the recovered fallback.
142
- storeCorrupt: info.storeCorrupt === true,
143
- entry: null,
144
- client: null,
145
- }
146
- try {
147
- const entry = ctx?.fiber?.entry
148
- out.entry = {
149
- id: entry?.options?.id ?? null,
150
- name: entry?.options?.name ?? null,
151
- }
152
- } catch {
153
- /* fiber shape is loader-internal; diagnostics must never throw */
154
- }
155
- try {
156
- const clientModules = ctx?.get?.('clientModules') ?? ctx?.clientModules
157
- const graph = clientModules?.graph?.()
158
- const clientPath = clientModules?.clientPath?.(PLUGIN_ID) ?? null
159
- const row = Array.isArray(graph?.entries) ? (graph.entries.find((item) => item.id === PLUGIN_ID) ?? null) : null
160
- let bundle = null
161
- if (clientPath) {
162
- try {
163
- const stat = statSync(clientPath)
164
- bundle = { path: clientPath, size: stat.size, mtimeMs: stat.mtimeMs }
165
- } catch (error) {
166
- bundle = { path: clientPath, error: messageOf(error) }
167
- }
168
- }
169
- out.client = {
170
- graph: graph ? { rev: graph.rev ?? null, release: graph.release ?? null, entries: graph.entries.length } : null,
171
- row: row
172
- ? { id: row.id, rev: row.rev, url: row.url, inject: row.inject ?? [], immediately: row.immediately === true }
173
- : null,
174
- clientPath,
175
- bundle,
176
- }
177
- } catch (error) {
178
- out.client = { error: messageOf(error) }
179
- }
180
- return out
181
- }
182
-
183
- function createLogger() {
184
- const tag = '[dsh-remote-go]'
185
- const write = (/** @type {'info'|'warn'|'error'|'debug'} */ level, /** @type {any[]} */ args) => {
186
- const sink =
187
- level === 'debug'
188
- ? console.debug
189
- : level === 'error'
190
- ? console.error
191
- : level === 'warn'
192
- ? console.warn
193
- : console.info
194
- try {
195
- sink?.call(console, tag, ...args)
196
- } catch {
197
- /* logging must never throw */
198
- }
199
- }
200
- return {
201
- info: (...args) => write('info', args),
202
- warn: (...args) => write('warn', args),
203
- error: (...args) => write('error', args),
204
- debug: (...args) => write('debug', args),
205
- }
206
- }
package/src/key-files.js DELETED
@@ -1,54 +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
- /** Code of the "not inside the home directory" refusal, so callers can map it to an HTTP 400. */
11
- export const OUTSIDE_HOME = 'EOUTSIDEHOME'
12
-
13
- export async function listKeyFiles(options) {
14
- const home = path.resolve(options.home)
15
- const impl = options.fsImpl ?? fs
16
- // Canonical base: the home directory spelled the way the filesystem reports it.
17
- // Every path below derives from this one spelling, so the returned `path` and
18
- // `parent` can never disagree — Windows hands out an 8.3 short path
19
- // (`C:\Users\RUNNER~1\…`) for a directory that realpath reports in long form.
20
- const realHome = await impl.realpath(home).catch(() => home)
21
- const requested = expandHome(options.dir, realHome)
22
- const target = path.resolve(requested || path.join(realHome, '.ssh'))
23
- // Resolve first, then judge: a symlinked directory may lead outside home. A path
24
- // that does not exist keeps its requested spelling, which the check still judges.
25
- const realTarget = await impl.realpath(target).catch(() => target)
26
- if (realTarget !== realHome && !realTarget.startsWith(realHome + path.sep)) {
27
- const error = new Error('key-file path must stay inside the home directory')
28
- error.code = OUTSIDE_HOME
29
- throw error
30
- }
31
-
32
- const dirents = await impl.readdir(realTarget, { withFileTypes: true })
33
- const entries = []
34
- for (const dirent of dirents) {
35
- const full = path.join(realTarget, dirent.name)
36
- const isDirectory = dirent.isDirectory()
37
- // Only regular files and directories are selectable; a socket or device node
38
- // in a home directory is never a private key.
39
- if (!isDirectory && !dirent.isFile()) continue
40
- entries.push({ name: dirent.name, path: full, isDirectory })
41
- }
42
- entries.sort((left, right) => {
43
- if (left.isDirectory !== right.isDirectory) return left.isDirectory ? -1 : 1
44
- return left.name.localeCompare(right.name)
45
- })
46
- const shown = entries.slice(0, MAX_ENTRIES)
47
- const parent = realTarget === realHome ? null : path.dirname(realTarget)
48
- return {
49
- path: realTarget,
50
- parent: parent ?? realHome,
51
- entries: shown,
52
- truncated: entries.length > shown.length,
53
- }
54
- }