dsh-remote-go 0.1.0 → 0.2.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.
- package/README.md +56 -95
- package/client.js +3121 -330
- package/locale/en.json +2 -2
- package/locale/zh.json +2 -2
- package/package.json +12 -11
- package/src/admission.js +43 -0
- package/src/api.js +219 -23
- package/src/atomic-json.js +19 -2
- package/src/bootstrap.js +14 -1
- package/src/connect-log.js +145 -8
- package/src/connect-pipeline.js +1545 -108
- package/src/connect-progress.js +28 -8
- package/src/constants.js +65 -3
- package/src/diagnostics.js +3 -0
- package/src/download-jobs.js +17 -0
- package/src/errors.js +98 -2
- package/src/host-lifecycle.js +434 -17
- package/src/host-registry.js +78 -6
- package/src/host-runtime.js +74 -0
- package/src/host-view.js +28 -4
- package/src/index.js +47 -3
- package/src/key-files.js +6 -1
- package/src/known-hosts.js +50 -11
- package/src/layout.js +28 -10
- package/src/local-download.js +232 -13
- package/src/probe.js +13 -1
- package/src/prompts.js +114 -17
- package/src/redact.js +17 -3
- package/src/remote-files.js +2 -2
- package/src/remote-path.js +64 -0
- package/src/remote-proc.js +135 -0
- package/src/remote-proxy.js +815 -0
- package/src/remote-web.js +479 -28
- package/src/request-trust.js +89 -0
- package/src/secrets.js +38 -8
- package/src/service.js +222 -13
- package/src/settings.js +30 -2
- package/src/ssh.js +108 -29
- package/src/store.js +58 -8
- package/src/tools.js +386 -0
- package/src/tunnel.js +60 -1
- package/src/webapp.js +15 -0
- package/vendor/THIRD_PARTY_NOTICES.md +27 -1
- package/vendor/ssh2-entry.mjs +0 -12
package/locale/en.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
|
-
"title": "dsh
|
|
4
|
-
"description": "Use a remote DSH over SSH
|
|
3
|
+
"title": "dsh-remote-go",
|
|
4
|
+
"description": "Use a remote DSH over SSH inside your local DSH: the sidebar host bar switches between Local and each host, the remote UI takes over the whole window and comes back without reloading; the connect flow shows staged progress and a live log, and you can restart or stop the remote DSH, download remote files and folders, and expose a read-only host list to local AI sessions. The remote runs on a plugin-managed Node with npx pinned to the local version, keeping its data in the remote ~/.dsh."
|
|
5
5
|
}
|
|
6
6
|
}
|
package/locale/zh.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"meta": {
|
|
3
|
-
"title": "dsh
|
|
4
|
-
"description": "
|
|
3
|
+
"title": "dsh-remote-go",
|
|
4
|
+
"description": "在本地 DSH 里通过 SSH 使用远端 DSH:侧边栏主机条在「本地」与各主机间切换,远端界面整窗接管、切回不重载;连接过程有阶段进度和实时日志,可重启/关闭远端 DSH、下载远端文件与文件夹,并向本地 AI 会话提供只读主机列表。远端由插件自带的 Node + npx 按本机版本启动,数据留在远端 ~/.dsh。"
|
|
5
5
|
}
|
|
6
6
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-remote-go",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "DSH
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "DSH 插件:在本地 DSH 里通过 SSH 使用远端 DSH(主机条切换、整窗接管、连接进度与日志、重启/关闭远端、远端文件下载、只读主机列表;插件自带 Node + npx,数据留在远端 ~/.dsh) | DSH plugin: use a remote DSH over SSH inside your local DSH (host switcher, full-window UI, connect progress and log, remote restart/stop, remote file downloads, read-only host list; plugin-managed Node + npx, data stays in the remote ~/.dsh)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"deepseek",
|
|
7
7
|
"harness",
|
|
@@ -40,7 +40,8 @@
|
|
|
40
40
|
"index.js",
|
|
41
41
|
"client.js",
|
|
42
42
|
"src",
|
|
43
|
-
"vendor",
|
|
43
|
+
"vendor/ssh2.bundle.cjs",
|
|
44
|
+
"vendor/THIRD_PARTY_NOTICES.md",
|
|
44
45
|
"locale",
|
|
45
46
|
"cordis.patch.yml",
|
|
46
47
|
"README.md",
|
|
@@ -65,10 +66,9 @@
|
|
|
65
66
|
},
|
|
66
67
|
"dependencies": {},
|
|
67
68
|
"devDependencies": {
|
|
68
|
-
"@deepseek-ai/dsh-plugin-market-index": "0.2.2-rc.2",
|
|
69
69
|
"esbuild": "^0.28.2",
|
|
70
70
|
"js-yaml": "^5.5.0",
|
|
71
|
-
"prettier": "^3.10.
|
|
71
|
+
"prettier": "^3.10.1",
|
|
72
72
|
"puppeteer-core": "^25.17.0",
|
|
73
73
|
"react": "^19.3.1",
|
|
74
74
|
"react-dom": "^19.3.1",
|
|
@@ -79,9 +79,11 @@
|
|
|
79
79
|
"test:unit": "node --test \"test/unit/*.test.js\"",
|
|
80
80
|
"test:web": "node --test \"test/integration/web.e2e.js\"",
|
|
81
81
|
"test:desktop": "node --test \"test/integration/desktop.e2e.js\"",
|
|
82
|
-
"test:integration": "node --test \"test/integration/*.test.js\" \"test/integration/*.e2e.js\"",
|
|
82
|
+
"test:integration": "node --test --test-concurrency=1 \"test/integration/*.test.js\" \"test/integration/*.e2e.js\"",
|
|
83
|
+
"test:integration:local": "node --test --test-concurrency=1 test/integration/sim.test.js test/integration/remote-restart.test.js test/integration/stop-remote.test.js",
|
|
84
|
+
"test:integration:external": "node --test --test-concurrency=1 test/integration/client-ui.test.js test/integration/remote-proxy.test.js test/integration/web.e2e.js test/integration/browser-carrier.test.js test/integration/guest-tools.e2e.js test/integration/stop-remote.browser.test.js",
|
|
83
85
|
"sim:remote": "node e2e/sim/simulated-remote.mjs --self-test",
|
|
84
|
-
"test:coverage": "node
|
|
86
|
+
"test:coverage": "node scripts/check-coverage.mjs",
|
|
85
87
|
"lint": "node scripts/check-repo.mjs",
|
|
86
88
|
"check:repo": "node scripts/check-repo.mjs",
|
|
87
89
|
"check:syntax": "node scripts/check-syntax.mjs",
|
|
@@ -89,12 +91,11 @@
|
|
|
89
91
|
"check:pr-title": "node scripts/check-pr-title.mjs",
|
|
90
92
|
"format": "prettier --write .",
|
|
91
93
|
"format:check": "prettier --check .",
|
|
92
|
-
"
|
|
94
|
+
"gate": "node scripts/check-repo.mjs && prettier --check . && node scripts/check-syntax.mjs && node scripts/check-workflows.mjs && node scripts/pack-check.mjs && node scripts/check-coverage.mjs",
|
|
95
|
+
"verify": "node scripts/check-repo.mjs && prettier --check . && node scripts/check-syntax.mjs && node scripts/check-workflows.mjs && node scripts/pack-check.mjs && node scripts/check-coverage.mjs && node --test --test-concurrency=1 \"test/integration/*.test.js\" \"test/integration/*.e2e.js\"",
|
|
93
96
|
"build:vendor": "node scripts/build-vendor.mjs",
|
|
94
|
-
"market:entry": "node scripts/market-entry.mjs",
|
|
95
|
-
"market:check": "node scripts/market-entry.mjs --check",
|
|
96
97
|
"pack:check": "node scripts/pack-check.mjs",
|
|
97
98
|
"pack:check:tarball": "node scripts/pack-check.mjs --find artifacts",
|
|
98
|
-
"prepack": "node scripts/
|
|
99
|
+
"prepack": "node scripts/build-vendor.mjs && git diff --exit-code -- vendor/"
|
|
99
100
|
}
|
|
100
101
|
}
|
package/src/admission.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH's own admission for the routes this plugin serves.
|
|
3
|
+
*
|
|
4
|
+
* The kernel decides whether a request may reach a Host feature at all: its `Host`/`Origin` fence
|
|
5
|
+
* plus browser authentication against a live Peer (`ctx.connection.requestRejection`). This module
|
|
6
|
+
* is the one place that turns that service into a per-request function, so the local API and the
|
|
7
|
+
* same-origin proxy share the gate and both failure modes stay testable.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Build the admission gate for one plugin activation.
|
|
12
|
+
*
|
|
13
|
+
* `connection` is optional and has to be read through `ctx.get`: Cordis throws when a plugin reads
|
|
14
|
+
* a service its fiber did not inject, and an older kernel may not provide the service at all. In
|
|
15
|
+
* both cases the gate returns `undefined`, which hands the request to the caller's own fence
|
|
16
|
+
* instead of going dark. A gate that throws while judging a request returns `500` — failing closed,
|
|
17
|
+
* because a check that cannot decide must never admit.
|
|
18
|
+
*
|
|
19
|
+
* @param {object} ctx - plugin context; only `ctx.get` is read, and it may be missing in tests.
|
|
20
|
+
* @param {{ warn?: (...args: any[]) => void }} [logger]
|
|
21
|
+
* @returns {(req: { headers: object }) => (number | undefined)} rejection status, or undefined to admit.
|
|
22
|
+
*/
|
|
23
|
+
export function createAdmission(ctx, logger = console) {
|
|
24
|
+
const warn = typeof logger.warn === 'function' ? logger.warn.bind(logger) : () => {}
|
|
25
|
+
|
|
26
|
+
return (req) => {
|
|
27
|
+
let connection = null
|
|
28
|
+
try {
|
|
29
|
+
connection = typeof ctx?.get === 'function' ? ctx.get('connection') : null
|
|
30
|
+
} catch (error) {
|
|
31
|
+
// A failed lookup says nothing about this request, so the caller's own fence decides it.
|
|
32
|
+
warn('[dsh-remote-go] DSH connection lookup failed; the local fence stays the only gate:', error)
|
|
33
|
+
return undefined
|
|
34
|
+
}
|
|
35
|
+
if (!connection || typeof connection.requestRejection !== 'function') return undefined
|
|
36
|
+
try {
|
|
37
|
+
return connection.requestRejection(req)
|
|
38
|
+
} catch (error) {
|
|
39
|
+
warn('[dsh-remote-go] DSH connection admission failed; rejecting the request:', error)
|
|
40
|
+
return 500
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/api.js
CHANGED
|
@@ -1,24 +1,80 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Local HTTP API for the browser half (contract: docs/api.md); every request
|
|
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.
|
|
3
4
|
*/
|
|
4
5
|
import { API_HEADER, API_PREFIX, API_VERSION, PLUGIN_VERSION } from './constants.js'
|
|
5
6
|
import { errors, isRemoteGoError, toErrorView } from './errors.js'
|
|
7
|
+
import { redactObject } from './redact.js'
|
|
8
|
+
import { sameServerHost, sameServerOrigin } from './request-trust.js'
|
|
6
9
|
import { nowIso } from './util.js'
|
|
7
10
|
|
|
8
11
|
const MAX_BODY_BYTES = 1 * 1024 * 1024
|
|
9
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
|
+
|
|
10
28
|
/** Rows shared by the `/version` and `/diagnostics/self` responses. */
|
|
11
29
|
const VERSION_ROW = { version: PLUGIN_VERSION, apiVersion: API_VERSION }
|
|
12
30
|
const PLUGIN_ROW = { id: 'dsh-remote-go', version: PLUGIN_VERSION }
|
|
13
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
|
+
|
|
14
45
|
export function createApi(options) {
|
|
15
46
|
const { service } = options
|
|
16
47
|
const logger = options.logger ?? console
|
|
17
48
|
const sseClients = new Set()
|
|
49
|
+
const kernelAdmit = typeof options.admit === 'function' ? options.admit : null
|
|
18
50
|
|
|
19
|
-
/**
|
|
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
|
+
*/
|
|
20
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
|
+
}
|
|
21
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
|
+
}
|
|
22
78
|
try {
|
|
23
79
|
client.write(frame)
|
|
24
80
|
} catch {
|
|
@@ -31,6 +87,11 @@ export function createApi(options) {
|
|
|
31
87
|
service.on('state', broadcastState)
|
|
32
88
|
const broadcastDownload = (job) => writeAll(`event: download\ndata: ${JSON.stringify(job)}\n\n`)
|
|
33
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)
|
|
34
95
|
|
|
35
96
|
const heartbeat = setInterval(() => writeAll('event: ping\ndata: {}\n\n'), 15_000)
|
|
36
97
|
heartbeat.unref?.()
|
|
@@ -43,18 +104,72 @@ export function createApi(options) {
|
|
|
43
104
|
),
|
|
44
105
|
})
|
|
45
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
|
+
|
|
46
149
|
/**
|
|
47
150
|
* Browser trust for same-origin reads (used by SSE, which cannot set custom
|
|
48
151
|
* headers): an absent Origin is a non-browser local caller; a present Origin
|
|
49
|
-
* must be this GUI's origin and the request must not be cross-site.
|
|
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.
|
|
50
162
|
*/
|
|
51
163
|
function authorizeOrigin(req) {
|
|
164
|
+
const local = parseOrigin(options.getOrigin())
|
|
52
165
|
const origin = req.headers.origin
|
|
53
166
|
if (typeof origin === 'string' && origin !== '') {
|
|
54
|
-
|
|
55
|
-
if (!expected || origin.replace(/\/$/, '') !== expected.replace(/\/$/, '')) return crossSite()
|
|
167
|
+
if (local === null || !sameServerOrigin(origin, local)) return crossSite()
|
|
56
168
|
}
|
|
57
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()
|
|
58
173
|
return { ok: true }
|
|
59
174
|
}
|
|
60
175
|
|
|
@@ -76,20 +191,38 @@ export function createApi(options) {
|
|
|
76
191
|
return { ok: true }
|
|
77
192
|
}
|
|
78
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
|
+
|
|
79
204
|
function readJson(req) {
|
|
80
205
|
return new Promise((resolve, reject) => {
|
|
81
206
|
const chunks = []
|
|
82
207
|
let size = 0
|
|
208
|
+
let refused = false
|
|
83
209
|
req.on('data', (chunk) => {
|
|
210
|
+
if (refused) return
|
|
84
211
|
size += chunk.length
|
|
85
212
|
if (size > MAX_BODY_BYTES) {
|
|
86
|
-
|
|
87
|
-
|
|
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()
|
|
88
220
|
return
|
|
89
221
|
}
|
|
90
222
|
chunks.push(Buffer.from(chunk))
|
|
91
223
|
})
|
|
92
224
|
req.on('end', () => {
|
|
225
|
+
if (refused) return
|
|
93
226
|
if (chunks.length === 0) {
|
|
94
227
|
resolve({})
|
|
95
228
|
return
|
|
@@ -118,6 +251,16 @@ export function createApi(options) {
|
|
|
118
251
|
}
|
|
119
252
|
|
|
120
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
|
+
}
|
|
121
264
|
res.writeHead(200, {
|
|
122
265
|
'content-type': 'text/event-stream; charset=utf-8',
|
|
123
266
|
'cache-control': 'no-cache, no-transform',
|
|
@@ -134,7 +277,8 @@ export function createApi(options) {
|
|
|
134
277
|
// One entry per route: `(req, url) => response body`. The dispatcher owns auth,
|
|
135
278
|
// init, status codes and the error envelope, so handlers only shape data.
|
|
136
279
|
const ROUTES = {
|
|
137
|
-
|
|
280
|
+
// A liveness probe only: no state, no version, nothing worth reading without a session.
|
|
281
|
+
'GET /health': () => ({ ok: true }),
|
|
138
282
|
'GET /state': () => ({ ok: true, state: service.snapshot() }),
|
|
139
283
|
'GET /version': () => ({ ok: true, ...VERSION_ROW, hostVersion: service.localVersion }),
|
|
140
284
|
'GET /ssh/aliases': async () => ({ ok: true, ...(await service.discoverSshAliases()) }),
|
|
@@ -142,12 +286,15 @@ export function createApi(options) {
|
|
|
142
286
|
ok: true,
|
|
143
287
|
...(await service.listKeyFiles(url.searchParams.get('path') ?? '')),
|
|
144
288
|
}),
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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
|
+
}),
|
|
151
298
|
'POST /hosts': async (req) => {
|
|
152
299
|
const body = await readJson(req)
|
|
153
300
|
return { ok: true, host: await service.saveHost(body.host ?? body) }
|
|
@@ -158,8 +305,9 @@ export function createApi(options) {
|
|
|
158
305
|
},
|
|
159
306
|
'POST /local-version': async (req) => {
|
|
160
307
|
const { version } = await readJson(req)
|
|
161
|
-
service
|
|
162
|
-
|
|
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') }
|
|
163
311
|
},
|
|
164
312
|
'POST /active': async (req) => {
|
|
165
313
|
const { id } = await readJson(req)
|
|
@@ -178,7 +326,20 @@ export function createApi(options) {
|
|
|
178
326
|
const body = await readJson(req)
|
|
179
327
|
const result = await service.connect(id, {
|
|
180
328
|
password: typeof body.password === 'string' ? body.password : undefined,
|
|
181
|
-
|
|
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,
|
|
182
343
|
})
|
|
183
344
|
return { ok: true, ...result }
|
|
184
345
|
},
|
|
@@ -195,6 +356,8 @@ export function createApi(options) {
|
|
|
195
356
|
await service.reconnect(id)
|
|
196
357
|
return { ok: true }
|
|
197
358
|
},
|
|
359
|
+
'POST restart': async (id) => ({ ok: true, ...(await service.restart(id)) }),
|
|
360
|
+
'POST stop-remote': async (id) => ({ ok: true, ...(await service.stopRemote(id)) }),
|
|
198
361
|
'POST fingerprint': async (id, req) => {
|
|
199
362
|
const body = await readJson(req)
|
|
200
363
|
await service.confirmFingerprint(id, {
|
|
@@ -218,7 +381,18 @@ export function createApi(options) {
|
|
|
218
381
|
if (segments[0] !== 'hosts' || segments.length < 2) return null
|
|
219
382
|
const key = segments[2] ? `${method} ${segments[2]}` : method
|
|
220
383
|
if (!Object.hasOwn(HOST_ACTIONS, key)) return null
|
|
221
|
-
|
|
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] }
|
|
222
396
|
}
|
|
223
397
|
|
|
224
398
|
async function handler(req, res) {
|
|
@@ -234,14 +408,31 @@ export function createApi(options) {
|
|
|
234
408
|
const path = url.pathname.slice(API_PREFIX.length) || '/'
|
|
235
409
|
const method = (req.method ?? 'GET').toUpperCase()
|
|
236
410
|
|
|
237
|
-
|
|
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
|
+
}
|
|
238
429
|
sendJson(res, 200, ROUTES['GET /health']())
|
|
239
430
|
return
|
|
240
431
|
}
|
|
241
432
|
|
|
242
|
-
// SSE cannot carry the custom header
|
|
243
|
-
//
|
|
244
|
-
// EventSource
|
|
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.
|
|
245
436
|
if (path === '/events' && method === 'GET') {
|
|
246
437
|
const originOnly = authorizeOrigin(req)
|
|
247
438
|
if (!originOnly.ok) {
|
|
@@ -313,7 +504,11 @@ export function createApi(options) {
|
|
|
313
504
|
})
|
|
314
505
|
} catch (error) {
|
|
315
506
|
const view = toErrorView(error)
|
|
316
|
-
const status =
|
|
507
|
+
const status = Number.isInteger(error?.httpStatus)
|
|
508
|
+
? error.httpStatus
|
|
509
|
+
: isRemoteGoError(error)
|
|
510
|
+
? statusForErrorCode(view.code)
|
|
511
|
+
: 500
|
|
317
512
|
logger.error?.('[dsh-remote-go] API error:', error)
|
|
318
513
|
try {
|
|
319
514
|
sendJson(res, status, { ok: false, error: view })
|
|
@@ -328,6 +523,7 @@ export function createApi(options) {
|
|
|
328
523
|
dispose() {
|
|
329
524
|
service.removeListener('state', broadcastState)
|
|
330
525
|
service.removeListener('download', broadcastDownload)
|
|
526
|
+
service.removeListener('remote-unreachable', broadcastRemoteUnreachable)
|
|
331
527
|
clearInterval(heartbeat)
|
|
332
528
|
for (const client of sseClients) {
|
|
333
529
|
try {
|
package/src/atomic-json.js
CHANGED
|
@@ -179,15 +179,32 @@ async function syncDir(fsImpl, dir) {
|
|
|
179
179
|
}
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
+
/**
|
|
183
|
+
* Read one JSON state file.
|
|
184
|
+
*
|
|
185
|
+
* The three outcomes are deliberately distinct: `missing` (never written), `corrupt` (the bytes
|
|
186
|
+
* are not JSON — the caller may quarantine them and recover) and `unreadable` (the file exists
|
|
187
|
+
* but could not be read: EACCES/EPERM/EISDIR/IO). A merely unreadable file must not be renamed
|
|
188
|
+
* away: that would turn a transient permission problem into a lost host list.
|
|
189
|
+
* @param {string} file
|
|
190
|
+
* @param {{ fs?: object, logger?: object }} [options]
|
|
191
|
+
* @returns {Promise<{ status: 'ok', value: any } | { status: 'missing'|'corrupt'|'unreadable', value: null }>}
|
|
192
|
+
*/
|
|
182
193
|
export async function readJsonFile(file, options = {}) {
|
|
183
194
|
const fsImpl = options.fs ?? fs
|
|
184
195
|
const logger = options.logger ?? console
|
|
196
|
+
let text
|
|
185
197
|
try {
|
|
186
198
|
if (!existsSync(file)) return { status: 'missing', value: null }
|
|
187
|
-
|
|
188
|
-
return { status: 'ok', value: JSON.parse(text) }
|
|
199
|
+
text = await fsImpl.readFile(file, 'utf8')
|
|
189
200
|
} catch (error) {
|
|
190
201
|
logger.warn?.(`[dsh-remote-go] cannot read ${path.basename(file)}:`, error)
|
|
202
|
+
return { status: 'unreadable', value: null }
|
|
203
|
+
}
|
|
204
|
+
try {
|
|
205
|
+
return { status: 'ok', value: JSON.parse(text) }
|
|
206
|
+
} catch (error) {
|
|
207
|
+
logger.warn?.(`[dsh-remote-go] ${path.basename(file)} is not valid JSON:`, error)
|
|
191
208
|
return { status: 'corrupt', value: null }
|
|
192
209
|
}
|
|
193
210
|
}
|
package/src/bootstrap.js
CHANGED
|
@@ -73,12 +73,25 @@ ${pathPrefix}npm_config_loglevel=http ${shellQuote(plan.start.npxPath)} -y @deep
|
|
|
73
73
|
}
|
|
74
74
|
|
|
75
75
|
export async function verifyNpxVersion(ssh, plan, options = {}) {
|
|
76
|
+
const timeoutMs = options.timeoutMs ?? 0
|
|
76
77
|
const result = await ssh.exec(buildPreflightCommand(plan), {
|
|
77
|
-
timeoutMs
|
|
78
|
+
timeoutMs,
|
|
78
79
|
maxBytes: options.maxBytes ?? 4 * 1024 * 1024,
|
|
79
80
|
onStdout: options.onStdout,
|
|
80
81
|
onStderr: options.onStderr,
|
|
81
82
|
})
|
|
83
|
+
// `timeoutMs: 0` means "no timeout" (a cold npx download is unbounded by design); only a
|
|
84
|
+
// caller-supplied deadline can time out, and that is a network condition, not a missing
|
|
85
|
+
// remote runtime (L).
|
|
86
|
+
if (result.timedOut === true) {
|
|
87
|
+
throw errors.network(
|
|
88
|
+
{
|
|
89
|
+
zh: `远端 npx 预检超过 ${Math.round(timeoutMs / 1000)} 秒没有完成,可能是下载很慢或远端负载过高。`,
|
|
90
|
+
en: `The remote npx preflight did not finish within ${Math.round(timeoutMs / 1000)}s; the download may be slow or the remote overloaded.`,
|
|
91
|
+
},
|
|
92
|
+
{ technical: `reason=preflight-timeout timeoutMs=${timeoutMs}` },
|
|
93
|
+
)
|
|
94
|
+
}
|
|
82
95
|
const combined = `${result.stdout}\n${result.stderr}`
|
|
83
96
|
if (result.code !== 0) {
|
|
84
97
|
const failure = errors.remoteDshMissing({
|