dsh-remote-go 0.2.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 (134) hide show
  1. package/README.md +11 -3
  2. package/{client.js → dist/client.js} +7710 -8182
  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/{src → dist/src}/constants.js +30 -56
  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 +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/diagnostics.js +0 -160
  100. package/src/download-jobs.js +0 -234
  101. package/src/errors.js +0 -412
  102. package/src/host-lifecycle.js +0 -604
  103. package/src/host-registry.js +0 -217
  104. package/src/host-runtime.js +0 -127
  105. package/src/host-view.js +0 -75
  106. package/src/index.js +0 -206
  107. package/src/key-files.js +0 -54
  108. package/src/known-hosts.js +0 -133
  109. package/src/layout.js +0 -53
  110. package/src/local-download.js +0 -381
  111. package/src/local-ssh.js +0 -27
  112. package/src/local-version.js +0 -88
  113. package/src/node-runtime.js +0 -521
  114. package/src/probe.js +0 -101
  115. package/src/prompts.js +0 -229
  116. package/src/redact.js +0 -68
  117. package/src/remote-files.js +0 -71
  118. package/src/remote-path.js +0 -137
  119. package/src/remote-proc.js +0 -343
  120. package/src/remote-proxy.js +0 -815
  121. package/src/remote-web.js +0 -751
  122. package/src/request-trust.js +0 -89
  123. package/src/secrets.js +0 -109
  124. package/src/service.js +0 -459
  125. package/src/settings.js +0 -163
  126. package/src/ssh-config.js +0 -271
  127. package/src/ssh.js +0 -731
  128. package/src/store.js +0 -193
  129. package/src/tools.js +0 -386
  130. package/src/tunnel.js +0 -132
  131. package/src/util.js +0 -153
  132. package/src/version.js +0 -103
  133. package/src/webapp.js +0 -43
  134. /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
package/src/api.js DELETED
@@ -1,536 +0,0 @@
1
- /**
2
- * Local HTTP API for the browser half (contract: docs/api.md); every request passes DSH's own
3
- * admission when the kernel provides it, then the marker header and, with an Origin, same-origin.
4
- */
5
- import { API_HEADER, API_PREFIX, API_VERSION, PLUGIN_VERSION } from './constants.js'
6
- import { errors, isRemoteGoError, toErrorView } from './errors.js'
7
- import { redactObject } from './redact.js'
8
- import { sameServerHost, sameServerOrigin } from './request-trust.js'
9
- import { nowIso } from './util.js'
10
-
11
- const MAX_BODY_BYTES = 1 * 1024 * 1024
12
-
13
- /** HTTP status for one `invalid-input` refusal: an oversized body is not a business conflict. */
14
- const PAYLOAD_TOO_LARGE = 413
15
-
16
- /**
17
- * At most this many live `/events` streams are served; a new one evicts the oldest, so a page
18
- * that leaks EventSources cannot grow this set without bound.
19
- */
20
- const MAX_SSE_CLIENTS = 8
21
-
22
- /** One SSE frame may not exceed this many bytes (a runaway snapshot is dropped, not buffered). */
23
- const MAX_SSE_FRAME_BYTES = 1 * 1024 * 1024
24
-
25
- /** A subscriber whose unsent backlog passes this is gone: drop it instead of buffering forever. */
26
- const MAX_SSE_BUFFERED_BYTES = 1 * 1024 * 1024
27
-
28
- /** Rows shared by the `/version` and `/diagnostics/self` responses. */
29
- const VERSION_ROW = { version: PLUGIN_VERSION, apiVersion: API_VERSION }
30
- const PLUGIN_ROW = { id: 'dsh-remote-go', version: PLUGIN_VERSION }
31
-
32
- /**
33
- * The HTTP status one ErrorView maps to (docs/api.md). `internal` used to fall through to 409,
34
- * which made a plugin bug look like a state conflict; only the two explicit codes are special,
35
- * everything else is a business refusal of the current state.
36
- * @param {string} code
37
- * @returns {number}
38
- */
39
- export function statusForErrorCode(code) {
40
- if (code === 'invalid-input') return 400
41
- if (code === 'internal') return 500
42
- return 409
43
- }
44
-
45
- export function createApi(options) {
46
- const { service } = options
47
- const logger = options.logger ?? console
48
- const sseClients = new Set()
49
- const kernelAdmit = typeof options.admit === 'function' ? options.admit : null
50
-
51
- /**
52
- * Write one SSE frame to every subscriber, dropping the ones that already went away, are
53
- * too far behind, or are gone from the set by the time their turn comes.
54
- * @param {string} frame
55
- */
56
- function writeAll(frame) {
57
- const bytes = Buffer.byteLength(frame)
58
- if (bytes > MAX_SSE_FRAME_BYTES) {
59
- // One frame that no browser could render is not worth unbounded memory: the next state
60
- // change (or the client's own `/state` read) carries the same data at a smaller size.
61
- logger.warn?.(`[dsh-remote-go] dropped an ${bytes}-byte SSE frame`)
62
- return
63
- }
64
- for (const client of sseClients) {
65
- if (client.writableEnded === true || client.destroyed === true) {
66
- sseClients.delete(client)
67
- continue
68
- }
69
- // A slow consumer must not grow the process heap: once its queue is too deep it is
70
- // treated as gone, and the browser reconnects to a fresh stream.
71
- if (client.writableLength > MAX_SSE_BUFFERED_BYTES) {
72
- sseClients.delete(client)
73
- try {
74
- client.end()
75
- } catch {}
76
- continue
77
- }
78
- try {
79
- client.write(frame)
80
- } catch {
81
- sseClients.delete(client)
82
- }
83
- }
84
- }
85
-
86
- const broadcastState = () => writeAll(`event: state\ndata: ${JSON.stringify(service.snapshot())}\n\n`)
87
- service.on('state', broadcastState)
88
- const broadcastDownload = (job) => writeAll(`event: download\ndata: ${JSON.stringify(job)}\n\n`)
89
- service.on('download', broadcastDownload)
90
- // One frame per liveness episode transition (suspected / confirmed / recovered); the
91
- // progress line lives in `state`, this event only makes the transition observable.
92
- const broadcastRemoteUnreachable = (event) =>
93
- writeAll(`event: remote-unreachable\ndata: ${JSON.stringify(event)}\n\n`)
94
- service.on('remote-unreachable', broadcastRemoteUnreachable)
95
-
96
- const heartbeat = setInterval(() => writeAll('event: ping\ndata: {}\n\n'), 15_000)
97
- heartbeat.unref?.()
98
-
99
- const crossSite = () => ({
100
- ok: false,
101
- status: 403,
102
- error: toErrorView(
103
- errors.invalidInput('origin', { zh: '跨站请求被拒绝。', en: 'Cross-site requests are rejected.' }),
104
- ),
105
- })
106
-
107
- /** The listener origin as a URL, or null while the kernel cannot name it yet. */
108
- function parseOrigin(value) {
109
- if (typeof value !== 'string' || value === '') return null
110
- try {
111
- return new URL(value)
112
- } catch {
113
- return null
114
- }
115
- }
116
-
117
- /**
118
- * The kernel's own admission (`ctx.connection.requestRejection`): its Host/Origin fence plus
119
- * browser authentication against a live Peer — the gate every DSH route passes. Absent on a
120
- * kernel without the Connection service, where the marker-header fence below stays the fallback.
121
- * @param {{ headers: object }} req
122
- * @returns {number | undefined} rejection status, or undefined when the route may proceed.
123
- */
124
- function admission(req) {
125
- if (kernelAdmit === null) return undefined
126
- const rejection = kernelAdmit(req)
127
- return typeof rejection === 'number' ? rejection : undefined
128
- }
129
-
130
- /** Response body for an admission rejection: the kernel decided, and this route never ran. */
131
- function admissionView(status) {
132
- // A gate that could not decide is this plugin's problem, not a client mistake.
133
- if (status === 500) {
134
- return { ok: false, error: toErrorView(errors.internal('the DSH connection admission check failed')) }
135
- }
136
- const detail =
137
- status === 401
138
- ? {
139
- zh: '这次请求没有通过 DSH 的浏览器会话认证(会话失效或未登录)。',
140
- en: 'The request did not pass DSH browser-session authentication (no session, or it expired).',
141
- }
142
- : {
143
- zh: '请求没有通过 DSH 的 Host / Origin 准入检查。',
144
- en: 'The request did not pass DSH Host / Origin admission.',
145
- }
146
- return { ok: false, error: toErrorView(errors.invalidInput('request', detail)) }
147
- }
148
-
149
- /**
150
- * Browser trust for same-origin reads (used by SSE, which cannot set custom
151
- * headers): an absent Origin is a non-browser local caller; a present Origin
152
- * must be this GUI's origin and the request must not be cross-site. The Host
153
- * fence is checked for both kinds of caller, because a DNS-rebinding page
154
- * reaches the socket under its own hostname: it sends no Origin, its
155
- * Fetch-Metadata says same-origin, and `Host` is the one header it cannot forge.
156
- *
157
- * The Origin comparison is the shared `sameServerOrigin`, not a string compare: the kernel
158
- * names its listener as `127.0.0.1:<port>`, while a user may open the GUI on
159
- * `http://localhost:<port>`, and `localhost` / `127.0.0.1` / `[::1]` are the same server.
160
- * The old equality check locked those users out of every write while `/state` still worked
161
- * without an Origin.
162
- */
163
- function authorizeOrigin(req) {
164
- const local = parseOrigin(options.getOrigin())
165
- const origin = req.headers.origin
166
- if (typeof origin === 'string' && origin !== '') {
167
- if (local === null || !sameServerOrigin(origin, local)) return crossSite()
168
- }
169
- if (req.headers['sec-fetch-site'] === 'cross-site') return crossSite()
170
- // An origin the kernel cannot name yet is no reason to reject local traffic; the kernel's own
171
- // admission (when present) has already judged Host, and this fence is the fallback.
172
- if (local !== null && !sameServerHost(req.headers.host, local)) return crossSite()
173
- return { ok: true }
174
- }
175
-
176
- function authorize(req) {
177
- const origin = authorizeOrigin(req)
178
- if (!origin.ok) return origin
179
- if (req.headers[API_HEADER] !== '1') {
180
- return {
181
- ok: false,
182
- status: 403,
183
- error: toErrorView(
184
- errors.invalidInput(API_HEADER, {
185
- zh: '请求缺少本地插件标识头。',
186
- en: 'The request is missing the local plugin header.',
187
- }),
188
- ),
189
- }
190
- }
191
- return { ok: true }
192
- }
193
-
194
- /** The 413 the API answers once a body crosses `MAX_BODY_BYTES`. */
195
- function payloadTooLarge() {
196
- const error = errors.invalidInput('body', {
197
- zh: `请求体超过上限(${MAX_BODY_BYTES} 字节)。`,
198
- en: `The request body exceeds the limit (${MAX_BODY_BYTES} bytes).`,
199
- })
200
- error.httpStatus = PAYLOAD_TOO_LARGE
201
- return error
202
- }
203
-
204
- function readJson(req) {
205
- return new Promise((resolve, reject) => {
206
- const chunks = []
207
- let size = 0
208
- let refused = false
209
- req.on('data', (chunk) => {
210
- if (refused) return
211
- size += chunk.length
212
- if (size > MAX_BODY_BYTES) {
213
- // Answer 413 with a JSON body *before* the socket goes away. Destroying the request
214
- // here (the old behavior) made the client see ECONNRESET instead of the refusal, and
215
- // the rest of the body is drained rather than buffered so the response can flush.
216
- refused = true
217
- chunks.length = 0
218
- reject(payloadTooLarge())
219
- req.resume()
220
- return
221
- }
222
- chunks.push(Buffer.from(chunk))
223
- })
224
- req.on('end', () => {
225
- if (refused) return
226
- if (chunks.length === 0) {
227
- resolve({})
228
- return
229
- }
230
- try {
231
- const text = Buffer.concat(chunks).toString('utf8').trim()
232
- resolve(text === '' ? {} : JSON.parse(text))
233
- } catch {
234
- reject(
235
- errors.invalidInput('body', { zh: '请求体不是合法 JSON。', en: 'The request body is not valid JSON.' }),
236
- )
237
- }
238
- })
239
- req.on('error', reject)
240
- })
241
- }
242
-
243
- function sendJson(res, status, payload) {
244
- const body = JSON.stringify(payload)
245
- res.writeHead(status, {
246
- 'content-type': 'application/json; charset=utf-8',
247
- 'cache-control': 'no-store',
248
- 'content-length': Buffer.byteLength(body),
249
- })
250
- res.end(body)
251
- }
252
-
253
- function handleSse(req, res) {
254
- // A page that leaks EventSource connections must not pin the process: the oldest stream is
255
- // closed when the cap is reached, and the page reconnects to one fresh stream.
256
- while (sseClients.size >= MAX_SSE_CLIENTS) {
257
- const oldest = sseClients.values().next().value
258
- if (oldest === undefined) break
259
- sseClients.delete(oldest)
260
- try {
261
- oldest.end()
262
- } catch {}
263
- }
264
- res.writeHead(200, {
265
- 'content-type': 'text/event-stream; charset=utf-8',
266
- 'cache-control': 'no-cache, no-transform',
267
- connection: 'keep-alive',
268
- 'x-accel-buffering': 'no',
269
- })
270
- res.write(`event: state\ndata: ${JSON.stringify(service.snapshot())}\n\n`)
271
- sseClients.add(res)
272
- req.on('close', () => {
273
- sseClients.delete(res)
274
- })
275
- }
276
-
277
- // One entry per route: `(req, url) => response body`. The dispatcher owns auth,
278
- // init, status codes and the error envelope, so handlers only shape data.
279
- const ROUTES = {
280
- // A liveness probe only: no state, no version, nothing worth reading without a session.
281
- 'GET /health': () => ({ ok: true }),
282
- 'GET /state': () => ({ ok: true, state: service.snapshot() }),
283
- 'GET /version': () => ({ ok: true, ...VERSION_ROW, hostVersion: service.localVersion }),
284
- 'GET /ssh/aliases': async () => ({ ok: true, ...(await service.discoverSshAliases()) }),
285
- 'GET /keyfile/list': async (req, url) => ({
286
- ok: true,
287
- ...(await service.listKeyFiles(url.searchParams.get('path') ?? '')),
288
- }),
289
- // Machine paths (`home`, `stateDir`) and the client-module row are troubleshooting data,
290
- // not the user's business: redact them like any other diagnostic export.
291
- 'GET /diagnostics/self': () =>
292
- redactObject({
293
- ok: true,
294
- plugin: PLUGIN_ROW,
295
- at: nowIso(),
296
- ...(typeof options.diagnostics === 'function' ? options.diagnostics() : {}),
297
- }),
298
- 'POST /hosts': async (req) => {
299
- const body = await readJson(req)
300
- return { ok: true, host: await service.saveHost(body.host ?? body) }
301
- },
302
- 'POST /settings': async (req) => {
303
- const body = await readJson(req)
304
- return { ok: true, settings: await service.saveSettings(body.patch ?? body) }
305
- },
306
- 'POST /local-version': async (req) => {
307
- const { version } = await readJson(req)
308
- // The client only backfills a *missing* probe result; the service decides whether this
309
- // one may be adopted (unknown locally, and not below DSH's `engines.dsh` floor).
310
- return { ok: true, accepted: service.setLocalVersion(String(version ?? ''), 'client') }
311
- },
312
- 'POST /active': async (req) => {
313
- const { id } = await readJson(req)
314
- service.setActiveHost(typeof id === 'string' ? id : null)
315
- return { ok: true }
316
- },
317
- }
318
-
319
- // `/hosts/:id` and `/hosts/:id/<action>`, keyed the same way.
320
- const HOST_ACTIONS = {
321
- DELETE: async (id) => {
322
- await service.removeHost(id)
323
- return { ok: true }
324
- },
325
- 'POST connect': async (id, req) => {
326
- const body = await readJson(req)
327
- const result = await service.connect(id, {
328
- password: typeof body.password === 'string' ? body.password : undefined,
329
- // Remembering is the default for a password that is actually supplied; the Client
330
- // sends false only when its "remember" box is unchecked.
331
- rememberPassword: body.rememberPassword !== false,
332
- })
333
- return { ok: true, ...result }
334
- },
335
- // Remember (or forget) the SSH password without connecting: the wizard's save action and
336
- // an explicit credential refresh. The value never enters hosts.json; `available:false`
337
- // means nothing can be persisted here.
338
- 'POST password': async (id, req) => {
339
- const body = await readJson(req)
340
- const result = await service.saveHostPassword(id, {
341
- password: typeof body.password === 'string' ? body.password : undefined,
342
- clear: body.clear === true,
343
- })
344
- return { ok: true, ...result }
345
- },
346
- 'POST conflict': async (id, req) => {
347
- const { action } = await readJson(req)
348
- return { ok: true, ...(await service.confirmConflict(id, { action })) }
349
- },
350
- 'POST disconnect': async (id, req) => {
351
- const { stopRemote } = await readJson(req)
352
- await service.disconnect(id, { stopRemote: stopRemote === true })
353
- return { ok: true }
354
- },
355
- 'POST reconnect': async (id) => {
356
- await service.reconnect(id)
357
- return { ok: true }
358
- },
359
- 'POST restart': async (id) => ({ ok: true, ...(await service.restart(id)) }),
360
- 'POST stop-remote': async (id) => ({ ok: true, ...(await service.stopRemote(id)) }),
361
- 'POST fingerprint': async (id, req) => {
362
- const body = await readJson(req)
363
- await service.confirmFingerprint(id, {
364
- accept: body.accept === true,
365
- remember: body.remember === true,
366
- sha256: typeof body.sha256 === 'string' ? body.sha256 : undefined,
367
- })
368
- return { ok: true }
369
- },
370
- 'POST diagnose': async (id) => ({ ok: true, report: await service.diagnose(id) }),
371
- 'GET open': (id) => ({ ok: true, ...service.openInfo(id) }),
372
- 'POST activate': (id) => {
373
- service.setActiveHost(id)
374
- return { ok: true }
375
- },
376
- }
377
-
378
- /** Resolve `/hosts/:id[/action]` to `{ id, run }`, or null for an unknown shape. */
379
- function hostHandler(hostPath, method) {
380
- const segments = hostPath.split('/').filter(Boolean)
381
- if (segments[0] !== 'hosts' || segments.length < 2) return null
382
- const key = segments[2] ? `${method} ${segments[2]}` : method
383
- if (!Object.hasOwn(HOST_ACTIONS, key)) return null
384
- let id
385
- try {
386
- id = decodeURIComponent(segments[1])
387
- } catch {
388
- // A malformed escape (`/hosts/%E0%A4%A/activate`) is a client mistake, not an internal
389
- // failure: answer 400 with a readable field error instead of leaking URIError as 500.
390
- throw errors.invalidInput('id', {
391
- zh: '主机 id 不是合法的 URL 编码。',
392
- en: 'The host id is not valid URL encoding.',
393
- })
394
- }
395
- return { id, run: HOST_ACTIONS[key] }
396
- }
397
-
398
- async function handler(req, res) {
399
- try {
400
- const url = new URL(req.url ?? '/', 'http://127.0.0.1')
401
- if (!url.pathname.startsWith(API_PREFIX)) {
402
- sendJson(res, 404, {
403
- ok: false,
404
- error: toErrorView(errors.invalidInput('path', { zh: '未知 API 路径。', en: 'Unknown API path.' })),
405
- })
406
- return
407
- }
408
- const path = url.pathname.slice(API_PREFIX.length) || '/'
409
- const method = (req.method ?? 'GET').toUpperCase()
410
-
411
- // `/health` stays the documented unauthenticated liveness probe (it carries no state), and
412
- // still passes the Host/Origin fence below. Everything else passes DSH's own admission
413
- // first, so a rebound page or an unauthenticated local caller cannot read state or change it.
414
- const probe = path === '/health' && method === 'GET'
415
- if (!probe) {
416
- const rejection = admission(req)
417
- if (rejection !== undefined) {
418
- sendJson(res, rejection, admissionView(rejection))
419
- return
420
- }
421
- }
422
-
423
- if (probe) {
424
- const trust = authorizeOrigin(req)
425
- if (!trust.ok) {
426
- sendJson(res, trust.status, { ok: false, error: trust.error })
427
- return
428
- }
429
- sendJson(res, 200, ROUTES['GET /health']())
430
- return
431
- }
432
-
433
- // SSE cannot carry the custom header. It already passed DSH's admission above; the fence
434
- // here covers kernels without the Connection service, and browsers block a cross-origin
435
- // EventSource anyway because this route never sends CORS headers.
436
- if (path === '/events' && method === 'GET') {
437
- const originOnly = authorizeOrigin(req)
438
- if (!originOnly.ok) {
439
- sendJson(res, originOnly.status, { ok: false, error: originOnly.error })
440
- return
441
- }
442
- await service.init()
443
- handleSse(req, res)
444
- return
445
- }
446
-
447
- const auth = authorize(req)
448
- if (!auth.ok) {
449
- sendJson(res, auth.status, { ok: false, error: auth.error })
450
- return
451
- }
452
-
453
- await service.init()
454
-
455
- // Download jobs save through the Host directly; no binary response route is
456
- // needed, so these handlers only shape JSON.
457
- const segments = path.split('/').filter(Boolean)
458
- if (method === 'POST' && path === '/downloads') {
459
- const body = await readJson(req)
460
- const job = await service.startRemoteDownload(body.hostId, body.path, {
461
- destination: body.destination,
462
- })
463
- sendJson(res, 200, { ok: true, job })
464
- return
465
- }
466
- if (segments[0] === 'downloads' && segments.length >= 2 && segments.length <= 3) {
467
- let jobId = ''
468
- try {
469
- jobId = decodeURIComponent(segments[1])
470
- } catch {
471
- throw errors.invalidInput('id', {
472
- zh: '下载任务 id 不是合法的 URL 编码。',
473
- en: 'The download job id is not valid URL encoding.',
474
- })
475
- }
476
- if (method === 'GET' && segments.length === 3 && segments[2] === 'status') {
477
- sendJson(res, 200, { ok: true, job: await service.remoteDownloadStatus(jobId) })
478
- return
479
- }
480
- if (method === 'DELETE' && segments.length === 2) {
481
- await service.cancelRemoteDownload(jobId)
482
- sendJson(res, 200, { ok: true })
483
- return
484
- }
485
- }
486
-
487
- const routeKey = `${method} ${path}`
488
- if (Object.hasOwn(ROUTES, routeKey)) {
489
- sendJson(res, 200, await ROUTES[routeKey](req, url))
490
- return
491
- }
492
-
493
- const host = hostHandler(path, method)
494
- if (host) {
495
- sendJson(res, 200, await host.run(host.id, req))
496
- return
497
- }
498
-
499
- sendJson(res, 404, {
500
- ok: false,
501
- error: toErrorView(
502
- errors.invalidInput('path', { zh: `未知路径 ${method} ${path}`, en: `Unknown path ${method} ${path}` }),
503
- ),
504
- })
505
- } catch (error) {
506
- const view = toErrorView(error)
507
- const status = Number.isInteger(error?.httpStatus)
508
- ? error.httpStatus
509
- : isRemoteGoError(error)
510
- ? statusForErrorCode(view.code)
511
- : 500
512
- logger.error?.('[dsh-remote-go] API error:', error)
513
- try {
514
- sendJson(res, status, { ok: false, error: view })
515
- } catch {
516
- /* response already gone */
517
- }
518
- }
519
- }
520
-
521
- return {
522
- handler,
523
- dispose() {
524
- service.removeListener('state', broadcastState)
525
- service.removeListener('download', broadcastDownload)
526
- service.removeListener('remote-unreachable', broadcastRemoteUnreachable)
527
- clearInterval(heartbeat)
528
- for (const client of sseClients) {
529
- try {
530
- client.end()
531
- } catch {}
532
- }
533
- sseClients.clear()
534
- },
535
- }
536
- }