dsh-remote-go 0.3.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.
- package/dist/client.js +1344 -2095
- package/dist/src/admission.js +3 -28
- package/dist/src/api.js +37 -99
- package/dist/src/atomic-json.js +32 -66
- package/dist/src/bootstrap.js +17 -27
- package/dist/src/connect/attach.js +3 -25
- package/dist/src/connect/bootstrap.js +2 -8
- package/dist/src/connect/failures.js +3 -18
- package/dist/src/connect/guards.js +13 -8
- package/dist/src/connect/launch.js +11 -21
- package/dist/src/connect/links.js +11 -27
- package/dist/src/connect/ownership.js +33 -114
- package/dist/src/connect/pipeline.js +61 -158
- package/dist/src/connect/reattach.js +20 -44
- package/dist/src/connect/registry.js +0 -1
- package/dist/src/connect/repair.js +8 -37
- package/dist/src/connect/restart.js +36 -97
- package/dist/src/connect/stop.js +16 -50
- package/dist/src/connect/transport.js +10 -18
- package/dist/src/connect/verify.js +3 -12
- package/dist/src/connect/watchdog.js +6 -38
- package/dist/src/connect-log.js +16 -41
- package/dist/src/connect-progress.js +13 -45
- package/dist/src/constants.js +2 -40
- package/dist/src/context.js +10 -31
- package/dist/src/diagnostics.js +56 -25
- package/dist/src/download-jobs.js +11 -20
- package/dist/src/errors.js +175 -190
- package/dist/src/events.js +20 -84
- package/dist/src/host-lifecycle.js +39 -175
- package/dist/src/host-registry.js +27 -78
- package/dist/src/host-runtime.js +0 -9
- package/dist/src/host-view.js +6 -29
- package/dist/src/index.js +15 -35
- package/dist/src/kernel-adapter.js +34 -80
- package/dist/src/key-files.js +10 -23
- package/dist/src/known-hosts.js +13 -34
- package/dist/src/layout.js +3 -20
- package/dist/src/local-download.js +94 -163
- package/dist/src/local-ssh.js +12 -19
- package/dist/src/local-version.js +35 -49
- package/dist/src/node/download.js +1 -4
- package/dist/src/node-runtime.js +19 -38
- package/dist/src/probe.js +6 -7
- package/dist/src/prompts.js +56 -128
- package/dist/src/proxy/cookies.js +26 -60
- package/dist/src/proxy/headers.js +30 -125
- package/dist/src/proxy/http.js +33 -41
- package/dist/src/proxy/index.js +20 -34
- package/dist/src/proxy/limits.js +4 -6
- package/dist/src/proxy/routes.js +10 -17
- package/dist/src/proxy/upgrade.js +27 -42
- package/dist/src/redact.js +14 -33
- package/dist/src/remote-files.js +9 -21
- package/dist/src/remote-path.js +21 -62
- package/dist/src/remote-proc.js +35 -103
- package/dist/src/remote-web/registry.js +10 -50
- package/dist/src/remote-web/resolve.js +23 -104
- package/dist/src/remote-web/start.js +27 -64
- package/dist/src/remote-web/stop.js +6 -25
- package/dist/src/request-trust.js +15 -32
- package/dist/src/runtime/dispatch.js +33 -143
- package/dist/src/runtime/effects.js +7 -17
- package/dist/src/runtime/events.js +1 -1
- package/dist/src/runtime/fsm.js +11 -61
- package/dist/src/runtime/rules.js +113 -198
- package/dist/src/secrets.js +15 -38
- package/dist/src/service.js +22 -128
- package/dist/src/settings.js +41 -42
- package/dist/src/ssh-config.js +22 -41
- package/dist/src/ssh-failures.js +23 -74
- package/dist/src/ssh-sftp.js +47 -86
- package/dist/src/ssh.js +95 -177
- package/dist/src/store.js +31 -48
- package/dist/src/tool-shared.js +17 -52
- package/dist/src/tools-exec-policy.js +33 -79
- package/dist/src/tools-exec.js +87 -151
- package/dist/src/tools-report.js +100 -167
- package/dist/src/tools.js +59 -133
- package/dist/src/tunnel.js +9 -27
- package/dist/src/util.js +19 -56
- package/dist/src/version.js +6 -12
- package/dist/src/watchdog-bus.js +0 -8
- package/dist/src/watchdog.js +7 -47
- package/package.json +1 -1
package/dist/src/admission.js
CHANGED
|
@@ -1,30 +1,7 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
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
|
-
* The service itself is read through `kernel-adapter.ts`, which reports the three states this gate
|
|
10
|
-
* has to treat differently: `ok` lets the kernel decide, `absent` hands the request to the caller's
|
|
11
|
-
* own fence (exactly like a kernel that never had the service), and `changed` — a moved member, a
|
|
12
|
-
* judgement that throws, a verdict that is not a status — is **rejected with 500**. A check that
|
|
13
|
-
* cannot decide must never admit (invariant B9).
|
|
14
|
-
*/
|
|
1
|
+
/** DSH's own admission for the routes this plugin serves: `Host`/`Origin` fence plus browser authentication against a
|
|
2
|
+
* live Peer. Read through `kernel-adapter.ts`: `ok` decides, `absent` hands over to the caller's fence, `changed` is
|
|
3
|
+
* 500 — a check that cannot decide must never admit. */
|
|
15
4
|
import { createKernelAdapter } from './kernel-adapter.js';
|
|
16
|
-
/**
|
|
17
|
-
* Build the admission gate for one plugin activation.
|
|
18
|
-
*
|
|
19
|
-
* `connection` is optional and has to be read through `ctx.get`: Cordis throws when a plugin reads
|
|
20
|
-
* a service its fiber did not inject, and an older kernel may not provide the service at all. In
|
|
21
|
-
* both cases the gate returns `undefined`, which hands the request to the caller's own fence
|
|
22
|
-
* instead of going dark. A gate that cannot judge the request returns `500` — failing closed,
|
|
23
|
-
* because a check that cannot decide must never admit.
|
|
24
|
-
* @param ctx - the plugin context (only `get` is read, and a test passes a fake).
|
|
25
|
-
* @param logger - the warning sink; a lookup failure is warned, a missing optional service is not.
|
|
26
|
-
* @returns the per-request gate.
|
|
27
|
-
*/
|
|
28
5
|
export function createAdmission(ctx, logger = console) {
|
|
29
6
|
const warn = typeof logger.warn === 'function' ? logger.warn.bind(logger) : () => { };
|
|
30
7
|
const kernel = createKernelAdapter(ctx);
|
|
@@ -33,8 +10,6 @@ export function createAdmission(ctx, logger = console) {
|
|
|
33
10
|
if (result.state === 'ok')
|
|
34
11
|
return result.value ?? undefined;
|
|
35
12
|
if (result.state === 'absent') {
|
|
36
|
-
// A lookup that threw is worth a warning (the plugin may be running against a kernel whose
|
|
37
|
-
// reflection moved); a service this composition never had is the documented fallback.
|
|
38
13
|
if (result.reason === 'lookup-failed') {
|
|
39
14
|
warn('[dsh-remote-go] DSH connection lookup failed; the local fence stays the only gate:', result.detail);
|
|
40
15
|
}
|
package/dist/src/api.js
CHANGED
|
@@ -5,16 +5,11 @@ import { redactObject } from './redact.js';
|
|
|
5
5
|
import { sameServerHost, sameServerOrigin } from './request-trust.js';
|
|
6
6
|
import { nowIso } from './util.js';
|
|
7
7
|
const MAX_BODY_BYTES = 1 * 1024 * 1024;
|
|
8
|
-
/**
|
|
8
|
+
/** An oversized body is the caller's mistake, not a business conflict (409). */
|
|
9
9
|
const PAYLOAD_TOO_LARGE = 413;
|
|
10
|
-
/** `/version` and `/diagnostics/self` share one version row. */
|
|
11
10
|
const VERSION_ROW = { version: PLUGIN_VERSION, apiVersion: API_VERSION };
|
|
12
11
|
const PLUGIN_ROW = { id: 'dsh-remote-go', version: PLUGIN_VERSION };
|
|
13
|
-
/**
|
|
14
|
-
* The HTTP status one ErrorView maps to (docs/api.md). `internal` used to fall through to 409,
|
|
15
|
-
* which made a plugin bug look like a state conflict; only the two explicit codes are special,
|
|
16
|
-
* everything else is a business refusal of the current state.
|
|
17
|
-
*/
|
|
12
|
+
/** The HTTP status for an ErrorView: only `invalid-input` (400) and `internal` (500) are special, the rest is 409. */
|
|
18
13
|
export function statusForErrorCode(code) {
|
|
19
14
|
if (code === 'invalid-input')
|
|
20
15
|
return 400;
|
|
@@ -23,8 +18,7 @@ export function statusForErrorCode(code) {
|
|
|
23
18
|
return 409;
|
|
24
19
|
}
|
|
25
20
|
export function createApi(options) {
|
|
26
|
-
const { service } = options;
|
|
27
|
-
const logger = options.logger ?? console;
|
|
21
|
+
const { service, logger = console } = options;
|
|
28
22
|
const kernelAdmit = typeof options.admit === 'function' ? options.admit : null;
|
|
29
23
|
// Both SSE channels: subscriber sets, caps, heartbeat, 150 ms coalescing and cursor replay.
|
|
30
24
|
const hub = createEventHub({ service, logger });
|
|
@@ -33,7 +27,6 @@ export function createApi(options) {
|
|
|
33
27
|
status: 403,
|
|
34
28
|
error: toErrorView(errors.invalidInput('origin', { zh: '跨站请求被拒绝。', en: 'Cross-site requests are rejected.' })),
|
|
35
29
|
});
|
|
36
|
-
/** The listener origin as a URL, or null while the kernel cannot name it yet. */
|
|
37
30
|
function parseOrigin(value) {
|
|
38
31
|
if (typeof value !== 'string' || value === '')
|
|
39
32
|
return null;
|
|
@@ -44,18 +37,6 @@ export function createApi(options) {
|
|
|
44
37
|
return null;
|
|
45
38
|
}
|
|
46
39
|
}
|
|
47
|
-
/**
|
|
48
|
-
* The kernel's own admission (`ctx.connection.requestRejection`): its Host/Origin fence plus
|
|
49
|
-
* browser authentication against a live Peer — the gate every DSH route passes. Absent on a
|
|
50
|
-
* kernel without the Connection service, where the marker-header fence below stays the fallback.
|
|
51
|
-
* @returns rejection status, or undefined when the route may proceed.
|
|
52
|
-
*/
|
|
53
|
-
function admission(req) {
|
|
54
|
-
if (kernelAdmit === null)
|
|
55
|
-
return undefined;
|
|
56
|
-
const rejection = kernelAdmit(req);
|
|
57
|
-
return typeof rejection === 'number' ? rejection : undefined;
|
|
58
|
-
}
|
|
59
40
|
/** Response body for an admission rejection: the kernel decided, and this route never ran. */
|
|
60
41
|
function admissionView(status) {
|
|
61
42
|
// A gate that could not decide is this plugin's problem, not a client mistake.
|
|
@@ -73,20 +54,8 @@ export function createApi(options) {
|
|
|
73
54
|
};
|
|
74
55
|
return { ok: false, error: toErrorView(errors.invalidInput('request', detail)) };
|
|
75
56
|
}
|
|
76
|
-
/**
|
|
77
|
-
*
|
|
78
|
-
* headers): an absent Origin is a non-browser local caller; a present Origin
|
|
79
|
-
* must be this GUI's origin and the request must not be cross-site. The Host
|
|
80
|
-
* fence is checked for both kinds of caller, because a DNS-rebinding page
|
|
81
|
-
* reaches the socket under its own hostname: it sends no Origin, its
|
|
82
|
-
* Fetch-Metadata says same-origin, and `Host` is the one header it cannot forge.
|
|
83
|
-
*
|
|
84
|
-
* The Origin comparison is the shared `sameServerOrigin`, not a string compare: the kernel
|
|
85
|
-
* names its listener as `127.0.0.1:<port>`, while a user may open the GUI on
|
|
86
|
-
* `http://localhost:<port>`, and `localhost` / `127.0.0.1` / `[::1]` are the same server.
|
|
87
|
-
* The old equality check locked those users out of every write while `/state` still worked
|
|
88
|
-
* without an Origin.
|
|
89
|
-
*/
|
|
57
|
+
/** Browser trust for same-origin reads (SSE cannot set custom headers): a present Origin must be this GUI, and the
|
|
58
|
+
* Host fence is checked for both kinds of caller because a DNS-rebinding page cannot forge `Host`. */
|
|
90
59
|
function authorizeOrigin(req) {
|
|
91
60
|
const local = parseOrigin(options.getOrigin());
|
|
92
61
|
const origin = req.headers.origin;
|
|
@@ -96,8 +65,7 @@ export function createApi(options) {
|
|
|
96
65
|
}
|
|
97
66
|
if (req.headers['sec-fetch-site'] === 'cross-site')
|
|
98
67
|
return crossSite();
|
|
99
|
-
// An
|
|
100
|
-
// admission (when present) has already judged Host, and this fence is the fallback.
|
|
68
|
+
// An unknown local origin is no reason to reject: admission (when present) already judged Host.
|
|
101
69
|
if (local !== null && !sameServerHost(req.headers.host, local))
|
|
102
70
|
return crossSite();
|
|
103
71
|
return { ok: true };
|
|
@@ -106,26 +74,16 @@ export function createApi(options) {
|
|
|
106
74
|
const origin = authorizeOrigin(req);
|
|
107
75
|
if (!origin.ok)
|
|
108
76
|
return origin;
|
|
109
|
-
if (req.headers[API_HEADER]
|
|
110
|
-
return {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
return { ok: true };
|
|
120
|
-
}
|
|
121
|
-
/** The 413 the API answers once a body crosses `MAX_BODY_BYTES`. */
|
|
122
|
-
function payloadTooLarge() {
|
|
123
|
-
const error = errors.invalidInput('body', {
|
|
124
|
-
zh: `请求体超过上限(${MAX_BODY_BYTES} 字节)。`,
|
|
125
|
-
en: `The request body exceeds the limit (${MAX_BODY_BYTES} bytes).`,
|
|
126
|
-
});
|
|
127
|
-
error.httpStatus = PAYLOAD_TOO_LARGE;
|
|
128
|
-
return error;
|
|
77
|
+
if (req.headers[API_HEADER] === '1')
|
|
78
|
+
return { ok: true };
|
|
79
|
+
return {
|
|
80
|
+
ok: false,
|
|
81
|
+
status: 403,
|
|
82
|
+
error: toErrorView(errors.invalidInput(API_HEADER, {
|
|
83
|
+
zh: '请求缺少本地插件标识头。',
|
|
84
|
+
en: 'The request is missing the local plugin header.',
|
|
85
|
+
})),
|
|
86
|
+
};
|
|
129
87
|
}
|
|
130
88
|
function readJson(req) {
|
|
131
89
|
return new Promise((resolve, reject) => {
|
|
@@ -137,12 +95,16 @@ export function createApi(options) {
|
|
|
137
95
|
return;
|
|
138
96
|
size += chunk.length;
|
|
139
97
|
if (size > MAX_BODY_BYTES) {
|
|
140
|
-
// Answer 413 with a JSON body *before* the socket goes away. Destroying the request
|
|
141
|
-
// here (the old behavior) made the client see ECONNRESET instead of the refusal, and
|
|
142
|
-
// the rest of the body is drained rather than buffered so the response can flush.
|
|
143
98
|
refused = true;
|
|
144
99
|
chunks.length = 0;
|
|
145
|
-
|
|
100
|
+
// Answer 413 with a JSON body *before* the socket goes away: destroying the request made the client see
|
|
101
|
+
// ECONNRESET instead of the refusal. The rest is drained, not buffered.
|
|
102
|
+
const error = errors.invalidInput('body', {
|
|
103
|
+
zh: `请求体超过上限(${MAX_BODY_BYTES} 字节)。`,
|
|
104
|
+
en: `The request body exceeds the limit (${MAX_BODY_BYTES} bytes).`,
|
|
105
|
+
});
|
|
106
|
+
error.httpStatus = PAYLOAD_TOO_LARGE;
|
|
107
|
+
reject(error);
|
|
146
108
|
req.resume();
|
|
147
109
|
return;
|
|
148
110
|
}
|
|
@@ -175,11 +137,7 @@ export function createApi(options) {
|
|
|
175
137
|
});
|
|
176
138
|
res.end(body);
|
|
177
139
|
}
|
|
178
|
-
/**
|
|
179
|
-
* Which SSE channel a GET path names, or null. Both routes pass the same pre-condition: DSH's
|
|
180
|
-
* admission (above) plus the Origin/Host fence, because an EventSource cannot set the marker
|
|
181
|
-
* header. Keeping the pair in one place is what stops the two routes from drifting apart.
|
|
182
|
-
*/
|
|
140
|
+
/** Which SSE channel a GET path names, or null; both routes share one pre-condition. */
|
|
183
141
|
function sseRoute(path, method) {
|
|
184
142
|
if (method !== 'GET')
|
|
185
143
|
return null;
|
|
@@ -189,8 +147,6 @@ export function createApi(options) {
|
|
|
189
147
|
return 'logs';
|
|
190
148
|
return null;
|
|
191
149
|
}
|
|
192
|
-
// One entry per route: `(req, url) => response body`. The dispatcher owns auth,
|
|
193
|
-
// init, status codes and the error envelope, so handlers only shape data.
|
|
194
150
|
const ROUTES = {
|
|
195
151
|
// A liveness probe only: no state, no version, nothing worth reading without a session.
|
|
196
152
|
'GET /health': () => ({ ok: true }),
|
|
@@ -201,8 +157,7 @@ export function createApi(options) {
|
|
|
201
157
|
ok: true,
|
|
202
158
|
...(await service.listKeyFiles(url.searchParams.get('path') ?? '')),
|
|
203
159
|
}),
|
|
204
|
-
// Machine paths
|
|
205
|
-
// not the user's business: redact them like any other diagnostic export.
|
|
160
|
+
// Machine paths and the client-module row are troubleshooting data: redact them like any export.
|
|
206
161
|
'GET /diagnostics/self': () => redactObject({
|
|
207
162
|
ok: true,
|
|
208
163
|
plugin: PLUGIN_ROW,
|
|
@@ -211,8 +166,6 @@ export function createApi(options) {
|
|
|
211
166
|
}),
|
|
212
167
|
'POST /hosts': async (req) => {
|
|
213
168
|
const body = await readJson(req);
|
|
214
|
-
// The store's own sanitizer is the validator; the body is only restated as the document
|
|
215
|
-
// shape it accepts (a JSON body can be anything, and this route never parses it further).
|
|
216
169
|
return { ok: true, host: await service.saveHost((body.host ?? body)) };
|
|
217
170
|
},
|
|
218
171
|
'POST /settings': async (req) => {
|
|
@@ -221,8 +174,7 @@ export function createApi(options) {
|
|
|
221
174
|
},
|
|
222
175
|
'POST /local-version': async (req) => {
|
|
223
176
|
const { version } = await readJson(req);
|
|
224
|
-
// The client only
|
|
225
|
-
// one may be adopted (unknown locally, and not below DSH's `engines.dsh` floor).
|
|
177
|
+
// The client backfills only a missing probe: the service adopts it when unknown and above the engines floor.
|
|
226
178
|
return { ok: true, accepted: service.setLocalVersion(String(version ?? ''), 'client') };
|
|
227
179
|
},
|
|
228
180
|
'POST /active': async (req) => {
|
|
@@ -231,7 +183,6 @@ export function createApi(options) {
|
|
|
231
183
|
return { ok: true };
|
|
232
184
|
},
|
|
233
185
|
};
|
|
234
|
-
// `/hosts/:id` and `/hosts/:id/<action>`, keyed the same way.
|
|
235
186
|
const HOST_ACTIONS = {
|
|
236
187
|
DELETE: async (id) => {
|
|
237
188
|
await service.removeHost(id);
|
|
@@ -239,17 +190,13 @@ export function createApi(options) {
|
|
|
239
190
|
},
|
|
240
191
|
'POST connect': async (id, req) => {
|
|
241
192
|
const body = await readJson(req);
|
|
193
|
+
// Remembering is the default when a password is supplied; the Client sends false only with its box unchecked.
|
|
242
194
|
const result = await service.connect(id, {
|
|
243
195
|
password: typeof body.password === 'string' ? body.password : undefined,
|
|
244
|
-
// Remembering is the default for a password that is actually supplied; the Client
|
|
245
|
-
// sends false only when its "remember" box is unchecked.
|
|
246
196
|
rememberPassword: body.rememberPassword !== false,
|
|
247
197
|
});
|
|
248
198
|
return { ok: true, ...result };
|
|
249
199
|
},
|
|
250
|
-
// Remember (or forget) the SSH password without connecting: the wizard's save action and
|
|
251
|
-
// an explicit credential refresh. The value never enters hosts.json; `available:false`
|
|
252
|
-
// means nothing can be persisted here.
|
|
253
200
|
'POST password': async (id, req) => {
|
|
254
201
|
const body = await readJson(req);
|
|
255
202
|
const result = await service.saveHostPassword(id, {
|
|
@@ -289,7 +236,6 @@ export function createApi(options) {
|
|
|
289
236
|
return { ok: true };
|
|
290
237
|
},
|
|
291
238
|
};
|
|
292
|
-
/** Resolve `/hosts/:id[/action]` to `{ id, run }`, or null for an unknown shape. */
|
|
293
239
|
function hostHandler(hostPath, method) {
|
|
294
240
|
const segments = hostPath.split('/').filter(Boolean);
|
|
295
241
|
if (segments[0] !== 'hosts' || segments.length < 2)
|
|
@@ -302,8 +248,7 @@ export function createApi(options) {
|
|
|
302
248
|
id = decodeURIComponent(segments[1]);
|
|
303
249
|
}
|
|
304
250
|
catch {
|
|
305
|
-
// A malformed escape
|
|
306
|
-
// failure: answer 400 with a readable field error instead of leaking URIError as 500.
|
|
251
|
+
// A malformed escape is a client mistake: answer 400 with a field error instead of leaking URIError as 500.
|
|
307
252
|
throw errors.invalidInput('id', {
|
|
308
253
|
zh: '主机 id 不是合法的 URL 编码。',
|
|
309
254
|
en: 'The host id is not valid URL encoding.',
|
|
@@ -323,14 +268,14 @@ export function createApi(options) {
|
|
|
323
268
|
}
|
|
324
269
|
const path = url.pathname.slice(API_PREFIX.length) || '/';
|
|
325
270
|
const method = (req.method ?? 'GET').toUpperCase();
|
|
326
|
-
// `/health`
|
|
327
|
-
//
|
|
328
|
-
// first, so a rebound page or an unauthenticated local caller cannot read state or change it.
|
|
271
|
+
// `/health` is the one unauthenticated probe (it carries no state) but still passes the Host fence; the rest of
|
|
272
|
+
// the routes pass DSH's own admission first.
|
|
329
273
|
const probe = path === '/health' && method === 'GET';
|
|
330
274
|
if (!probe) {
|
|
331
|
-
const rejection =
|
|
332
|
-
|
|
333
|
-
|
|
275
|
+
const rejection = kernelAdmit === null ? undefined : kernelAdmit(req);
|
|
276
|
+
const rejected = typeof rejection === 'number' ? rejection : undefined;
|
|
277
|
+
if (rejected !== undefined) {
|
|
278
|
+
sendJson(res, rejected, admissionView(rejected));
|
|
334
279
|
return;
|
|
335
280
|
}
|
|
336
281
|
}
|
|
@@ -343,10 +288,8 @@ export function createApi(options) {
|
|
|
343
288
|
sendJson(res, 200, ROUTES['GET /health']());
|
|
344
289
|
return;
|
|
345
290
|
}
|
|
346
|
-
// SSE cannot carry the custom header
|
|
347
|
-
//
|
|
348
|
-
// EventSource anyway because these routes never send CORS headers. The state channel
|
|
349
|
-
// (`/events`) and the connect-log channel (`/events/logs`) share this one pre-condition.
|
|
291
|
+
// SSE cannot carry the custom header; it already passed admission, and this fence covers kernels without
|
|
292
|
+
// `connection` (browsers block a cross-origin EventSource anyway).
|
|
350
293
|
const sse = sseRoute(path, method);
|
|
351
294
|
if (sse !== null) {
|
|
352
295
|
const originOnly = authorizeOrigin(req);
|
|
@@ -367,13 +310,9 @@ export function createApi(options) {
|
|
|
367
310
|
return;
|
|
368
311
|
}
|
|
369
312
|
await service.init();
|
|
370
|
-
// Download jobs save through the Host directly; no binary response route is
|
|
371
|
-
// needed, so these handlers only shape JSON.
|
|
372
313
|
const segments = path.split('/').filter(Boolean);
|
|
373
314
|
if (method === 'POST' && path === '/downloads') {
|
|
374
315
|
const body = await readJson(req);
|
|
375
|
-
// Both paths are opaque strings the job layer validates (`runtimeOf` refuses an unknown
|
|
376
|
-
// id, the downloader refuses a bad path); the body is a JSON document, not a schema.
|
|
377
316
|
const job = await service.startRemoteDownload(body.hostId, body.path, {
|
|
378
317
|
destination: body.destination,
|
|
379
318
|
});
|
|
@@ -435,7 +374,6 @@ export function createApi(options) {
|
|
|
435
374
|
return {
|
|
436
375
|
handler,
|
|
437
376
|
dispose() {
|
|
438
|
-
// One entry point for the whole listener teardown: the hub owns both channel sets.
|
|
439
377
|
hub.dispose();
|
|
440
378
|
},
|
|
441
379
|
};
|
package/dist/src/atomic-json.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Atomic JSON persistence: 0700 dir, 0600 file, fsynced temp, rename retry and a cross-process lock; a bad file is reported, never thrown.
|
|
3
|
-
*/
|
|
1
|
+
/** Atomic JSON persistence: 0700 dir, 0600 file, fsynced temp, rename retry and a cross-process lock; a bad file is reported, never thrown. */
|
|
4
2
|
import { promises as fs } from 'node:fs';
|
|
5
3
|
import { existsSync } from 'node:fs';
|
|
6
4
|
import { randomUUID } from 'node:crypto';
|
|
@@ -11,59 +9,45 @@ const RENAME_RETRY_BASE_MS = 20;
|
|
|
11
9
|
const LOCK_STALE_MS = 10_000;
|
|
12
10
|
const LOCK_WAIT_MS = 20_000;
|
|
13
11
|
const LOCK_RETRY_MS = 10;
|
|
14
|
-
/**
|
|
15
|
-
*
|
|
16
|
-
* Windows reports mid-create/mid-delete races as EPERM/EACCES, but those codes also
|
|
17
|
-
* mean a lock that can never be created (ACL denial, read-only mount); past this
|
|
18
|
-
* window the original error is surfaced instead of a misleading timeout.
|
|
19
|
-
*/
|
|
12
|
+
/** How long a non-`EEXIST` lock error counts as contention with no lock present: Windows reports mid-create races as
|
|
13
|
+
* EPERM/EACCES, but those codes also mean an impossible lock (ACL denial, read-only mount); past this it surfaces. */
|
|
20
14
|
const LOCK_TRANSIENT_MS = 250;
|
|
21
15
|
const LOCK_UNLINK_ATTEMPTS = 3;
|
|
22
|
-
/**
|
|
23
|
-
* In-process chains keyed by lock path; the value is the always-settled tail so a
|
|
24
|
-
* rejected write never poisons the next waiter.
|
|
25
|
-
*/
|
|
16
|
+
/** In-process chains keyed by lock path; the value is the always-settled tail so a rejected write never poisons the next waiter. */
|
|
26
17
|
const LOCAL_CHAINS = new Map();
|
|
27
|
-
/**
|
|
28
|
-
* Run `task` under the cross-process lock, serialized with every in-process holder
|
|
29
|
-
* of the same lock path.
|
|
30
|
-
*/
|
|
18
|
+
/** Run `task` under the cross-process lock, serialized with every in-process holder of the same lock path. */
|
|
31
19
|
export function withProcessLock(lockFile, options, task) {
|
|
20
|
+
const start = async () => {
|
|
21
|
+
const release = await acquireLock(lockFile, options ?? {});
|
|
22
|
+
try {
|
|
23
|
+
return await task();
|
|
24
|
+
}
|
|
25
|
+
finally {
|
|
26
|
+
await release();
|
|
27
|
+
}
|
|
28
|
+
};
|
|
32
29
|
const previous = LOCAL_CHAINS.get(lockFile) ?? Promise.resolve();
|
|
33
|
-
const run = previous.then(
|
|
30
|
+
const run = previous.then(start, start);
|
|
34
31
|
LOCAL_CHAINS.set(lockFile, run.catch(() => undefined));
|
|
35
32
|
return run;
|
|
36
33
|
}
|
|
37
|
-
async function runExclusive(lockFile, options, task) {
|
|
38
|
-
const release = await acquireLock(lockFile, options);
|
|
39
|
-
try {
|
|
40
|
-
return await task();
|
|
41
|
-
}
|
|
42
|
-
finally {
|
|
43
|
-
await release();
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
34
|
async function acquireLock(lockFile, options) {
|
|
47
35
|
const fsImpl = options.fs ?? fs;
|
|
48
36
|
const staleMs = options.staleMs ?? LOCK_STALE_MS;
|
|
49
37
|
const waitMs = options.waitMs ?? LOCK_WAIT_MS;
|
|
50
38
|
const retryMs = options.retryMs ?? LOCK_RETRY_MS;
|
|
51
39
|
const started = Date.now();
|
|
52
|
-
// Only a lock we never once observed can be a permanent permission error: under
|
|
53
|
-
//
|
|
40
|
+
// Only a lock we never once observed can be a permanent permission error: under real contention
|
|
41
|
+
// the lock is created and unlinked constantly.
|
|
54
42
|
let sawLock = false;
|
|
55
43
|
while (true) {
|
|
56
44
|
try {
|
|
57
45
|
const handle = await fsImpl.open(lockFile, 'wx', 0o600);
|
|
58
46
|
return async () => {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
// swallow-ok: a failed close on a released lock handle is not actionable here
|
|
64
|
-
}
|
|
65
|
-
// A leaked lock costs the next writer a full stale wait, so retry the unlink
|
|
66
|
-
// (Windows can hold it briefly after close).
|
|
47
|
+
// A failed close on a released lock handle is not actionable here.
|
|
48
|
+
await handle.close().catch(() => { });
|
|
49
|
+
// A leaked lock costs the next writer a full stale wait, so retry the unlink (Windows can
|
|
50
|
+
// hold it briefly after close).
|
|
67
51
|
for (let attempt = 0; attempt < LOCK_UNLINK_ATTEMPTS; attempt += 1) {
|
|
68
52
|
try {
|
|
69
53
|
await fsImpl.unlink(lockFile);
|
|
@@ -71,9 +55,7 @@ async function acquireLock(lockFile, options) {
|
|
|
71
55
|
}
|
|
72
56
|
catch (unlinkError) {
|
|
73
57
|
const unlinkCode = unlinkError?.code;
|
|
74
|
-
if (unlinkCode === 'ENOENT')
|
|
75
|
-
return;
|
|
76
|
-
if (attempt === LOCK_UNLINK_ATTEMPTS - 1)
|
|
58
|
+
if (unlinkCode === 'ENOENT' || attempt === LOCK_UNLINK_ATTEMPTS - 1)
|
|
77
59
|
return;
|
|
78
60
|
await sleep(retryMs);
|
|
79
61
|
}
|
|
@@ -81,8 +63,8 @@ async function acquireLock(lockFile, options) {
|
|
|
81
63
|
};
|
|
82
64
|
}
|
|
83
65
|
catch (error) {
|
|
84
|
-
// Windows reports contention on an exclusive create as EPERM/EACCES/EBUSY
|
|
85
|
-
//
|
|
66
|
+
// Windows reports contention on an exclusive create as EPERM/EACCES/EBUSY rather than EEXIST
|
|
67
|
+
// when the other process is mid-create or mid-delete.
|
|
86
68
|
const code = error?.code;
|
|
87
69
|
if (code !== 'EEXIST' && code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY')
|
|
88
70
|
throw error;
|
|
@@ -135,14 +117,9 @@ export async function writeJsonAtomic(file, value, options = {}) {
|
|
|
135
117
|
handle = null;
|
|
136
118
|
}
|
|
137
119
|
catch (error) {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
}
|
|
142
|
-
catch {
|
|
143
|
-
// swallow-ok: the temp file is removed right below; a close error is not fixable
|
|
144
|
-
}
|
|
145
|
-
}
|
|
120
|
+
// The temp file is removed right below, so a close error here is not fixable.
|
|
121
|
+
if (handle)
|
|
122
|
+
await handle.close().catch(() => { });
|
|
146
123
|
await removeQuietly(fsImpl, tmp);
|
|
147
124
|
throw error;
|
|
148
125
|
}
|
|
@@ -177,24 +154,12 @@ async function syncDir(fsImpl, dir) {
|
|
|
177
154
|
// swallow-ok: directory fsync is not supported on every platform or filesystem
|
|
178
155
|
}
|
|
179
156
|
finally {
|
|
180
|
-
if (handle)
|
|
181
|
-
|
|
182
|
-
await handle.close();
|
|
183
|
-
}
|
|
184
|
-
catch {
|
|
185
|
-
// swallow-ok: the directory handle is best effort, like the fsync above
|
|
186
|
-
}
|
|
187
|
-
}
|
|
157
|
+
if (handle)
|
|
158
|
+
await handle.close().catch(() => { });
|
|
188
159
|
}
|
|
189
160
|
}
|
|
190
|
-
/**
|
|
191
|
-
*
|
|
192
|
-
*
|
|
193
|
-
* The three outcomes are deliberately distinct: `missing` (never written), `corrupt` (the bytes
|
|
194
|
-
* are not JSON — the caller may quarantine them and recover) and `unreadable` (the file exists
|
|
195
|
-
* but could not be read: EACCES/EPERM/EISDIR/IO). A merely unreadable file must not be renamed
|
|
196
|
-
* away: that would turn a transient permission problem into a lost host list.
|
|
197
|
-
*/
|
|
161
|
+
/** Read one JSON state file. The outcomes are distinct: `missing` (never written), `corrupt` (not JSON — the caller
|
|
162
|
+
* may quarantine and recover) and `unreadable` (EACCES/EPERM/EISDIR/IO); that one is never renamed away. */
|
|
198
163
|
export async function readJsonFile(file, options = {}) {
|
|
199
164
|
const fsImpl = options.fs ?? fs;
|
|
200
165
|
const logger = options.logger ?? console;
|
|
@@ -230,6 +195,7 @@ async function lockExists(fsImpl, lockFile) {
|
|
|
230
195
|
return true;
|
|
231
196
|
}
|
|
232
197
|
catch {
|
|
198
|
+
// swallow-ok: a lock that cannot be inspected is treated as absent
|
|
233
199
|
return false;
|
|
234
200
|
}
|
|
235
201
|
}
|
package/dist/src/bootstrap.js
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
*/
|
|
1
|
+
/** Remote runtime preparation: `npx` pinned to the local DSH version against the remote's real `$DSH_HOME`; the
|
|
2
|
+
* executor runs only fixed templates. */
|
|
4
3
|
import { errors } from './errors.js';
|
|
5
4
|
import { headTail, shellQuote } from './util.js';
|
|
6
5
|
import { isNodeVersionSupported, normalizeVersion, parseVersion, versionsEqual } from './version.js';
|
|
7
6
|
export function assertSupportedRemote(facts) {
|
|
8
|
-
if (facts.os !== 'Linux')
|
|
7
|
+
if (facts.os !== 'Linux')
|
|
9
8
|
throw errors.unsupportedOs(`${facts.os} ${facts.arch}`.trim());
|
|
10
|
-
}
|
|
11
9
|
}
|
|
12
10
|
export function planNpx(input) {
|
|
13
11
|
const targetVersion = normalizeVersion(input.targetVersion);
|
|
@@ -18,25 +16,25 @@ export function planNpx(input) {
|
|
|
18
16
|
});
|
|
19
17
|
}
|
|
20
18
|
assertSupportedRemote(input.facts);
|
|
21
|
-
|
|
19
|
+
const facts = input.facts;
|
|
20
|
+
if (!isNodeVersionSupported(facts.nodeVersion)) {
|
|
22
21
|
throw errors.remoteDshMissing({
|
|
23
|
-
zh: `远端 Node 不可用或版本过低(需要 ≥ 24.9.0,检测到 ${
|
|
24
|
-
en: `The remote Node is missing or too old (>= 24.9.0 required, detected ${
|
|
22
|
+
zh: `远端 Node 不可用或版本过低(需要 ≥ 24.9.0,检测到 ${facts.nodeVersion ?? '无'}),自动准备也没有完成。请检查远端网络,或在远端安装 Node 后重试。`,
|
|
23
|
+
en: `The remote Node is missing or too old (>= 24.9.0 required, detected ${facts.nodeVersion ?? 'none'}) and automatic preparation did not finish. Check the remote network, or install Node on the remote and retry.`,
|
|
25
24
|
});
|
|
26
25
|
}
|
|
27
|
-
if (!
|
|
26
|
+
if (!facts.npxPath) {
|
|
28
27
|
throw errors.remoteDshMissing({
|
|
29
28
|
zh: '远端没有找到 npx。请安装 npm(随 Node 一起提供),或把 npm 的 bin 目录加入远程 shell 的 PATH。',
|
|
30
29
|
en: 'npx was not found on the remote. Install npm (shipped with Node) or add its bin directory to the remote shell PATH.',
|
|
31
30
|
});
|
|
32
31
|
}
|
|
33
|
-
if (!
|
|
32
|
+
if (!facts.curlPath && !facts.wgetPath) {
|
|
34
33
|
throw errors.remoteDshMissing({
|
|
35
34
|
zh: '远端既没有 curl 也没有 wget,无法在启动后探活远端界面。请安装其中之一。',
|
|
36
35
|
en: 'The remote has neither curl nor wget, so the remote UI cannot be health-checked after start. Install one of them.',
|
|
37
36
|
});
|
|
38
37
|
}
|
|
39
|
-
const nodeBinDir = input.facts.nodePath ? input.facts.nodePath.replace(/\/node$/, '') : undefined;
|
|
40
38
|
return {
|
|
41
39
|
level: 'npx',
|
|
42
40
|
profile: input.profile,
|
|
@@ -47,22 +45,16 @@ export function planNpx(input) {
|
|
|
47
45
|
},
|
|
48
46
|
start: {
|
|
49
47
|
kind: 'npx',
|
|
50
|
-
npxPath:
|
|
51
|
-
nodePath:
|
|
52
|
-
nodeBinDir,
|
|
48
|
+
npxPath: facts.npxPath,
|
|
49
|
+
nodePath: facts.nodePath ?? undefined,
|
|
50
|
+
nodeBinDir: facts.nodePath ? facts.nodePath.replace(/\/node$/, '') : undefined,
|
|
53
51
|
targetVersion,
|
|
54
52
|
},
|
|
55
53
|
};
|
|
56
54
|
}
|
|
57
|
-
/**
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
* of inside the detached start script.
|
|
61
|
-
*
|
|
62
|
-
* `npm_config_loglevel=http` is deliberate: over an SSH channel npm has no TTY and
|
|
63
|
-
* would otherwise print nothing until it finishes. At `http` it reports fetches
|
|
64
|
-
* on stderr, which the caller turns into progress.
|
|
65
|
-
*/
|
|
55
|
+
/** The npx preflight: resolve and run the exact package once, so a first-run download happens in the foreground.
|
|
56
|
+
* `npm_config_loglevel=http` makes npm report fetches on stderr without a TTY; the caller turns those lines into
|
|
57
|
+
* progress. */
|
|
66
58
|
export function buildPreflightCommand(plan) {
|
|
67
59
|
const pathPrefix = plan.start.nodeBinDir ? `PATH=${shellQuote(plan.start.nodeBinDir)}:"$PATH" ` : '';
|
|
68
60
|
return `set -eu
|
|
@@ -77,8 +69,7 @@ export async function verifyNpxVersion(ssh, plan, options = {}) {
|
|
|
77
69
|
onStderr: options.onStderr,
|
|
78
70
|
});
|
|
79
71
|
// `timeoutMs: 0` means "no timeout" (a cold npx download is unbounded by design); only a
|
|
80
|
-
// caller-supplied deadline can time out, and that is a network condition, not a missing
|
|
81
|
-
// remote runtime (L).
|
|
72
|
+
// caller-supplied deadline can time out, and that is a network condition, not a missing runtime.
|
|
82
73
|
if (result.timedOut === true) {
|
|
83
74
|
throw errors.network({
|
|
84
75
|
zh: `远端 npx 预检超过 ${Math.round(timeoutMs / 1000)} 秒没有完成,可能是下载很慢或远端负载过高。`,
|
|
@@ -99,8 +90,7 @@ export async function verifyNpxVersion(ssh, plan, options = {}) {
|
|
|
99
90
|
.map((line) => line.trim())
|
|
100
91
|
.filter(Boolean);
|
|
101
92
|
const reported = normalizeVersion(lines[lines.length - 1] ?? '');
|
|
102
|
-
if (!versionsEqual(reported, plan.targetVersion))
|
|
93
|
+
if (!versionsEqual(reported, plan.targetVersion))
|
|
103
94
|
throw errors.versionMismatch(plan.targetVersion, reported || 'unknown');
|
|
104
|
-
}
|
|
105
95
|
return reported;
|
|
106
96
|
}
|
|
@@ -1,40 +1,18 @@
|
|
|
1
1
|
import { dispatch, scopeFactsFor } from '../runtime/dispatch.js';
|
|
2
2
|
import { createRuntimeEffects } from '../runtime/effects.js';
|
|
3
3
|
import { nowIso } from '../util.js';
|
|
4
|
-
/**
|
|
5
|
-
* Publish the connected state and start watching the remote for its own restarts.
|
|
6
|
-
*
|
|
7
|
-
* The whole attach is one `connect.succeeded` transition: status/phase/progress/error, the
|
|
8
|
-
* retry-budget reset, the stale "stop not confirmed" warning, the idle disarm, the heartbeat arm,
|
|
9
|
-
* `uiReady`/`viewRev`, the link-block repair-budget reset and `activeHostId`.
|
|
10
|
-
* @param ctx - service context.
|
|
11
|
-
* @param runtime - the runtime that just reached `ready`.
|
|
12
|
-
*/
|
|
4
|
+
/** Publish the connected state: one transition owns status/phase/progress/error, the retry-budget reset, the idle disarm, the heartbeat arm and `activeHostId`. */
|
|
13
5
|
export async function markConnected(ctx, runtime) {
|
|
14
6
|
const event = { type: 'connect.succeeded' };
|
|
15
|
-
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), {
|
|
16
|
-
caller: 'script',
|
|
17
|
-
});
|
|
7
|
+
await dispatch(createRuntimeEffects(ctx), runtime, event, scopeFactsFor(ctx, runtime, event), { caller: 'script' });
|
|
18
8
|
}
|
|
19
|
-
/** Bounded diagnostics trail of restarts and re-attached ports (never sent to the client). */
|
|
20
9
|
export function recordRestart(runtime, entry) {
|
|
21
10
|
const history = Array.isArray(runtime.restarts) ? runtime.restarts : [];
|
|
22
11
|
history.push({ at: nowIso(), ...entry });
|
|
23
12
|
runtime.restarts = history.slice(-10);
|
|
24
13
|
}
|
|
25
|
-
/**
|
|
26
|
-
* Put a host back into its connected state without pretending the launch URL changed.
|
|
27
|
-
*
|
|
28
|
-
* One `restart.resumed` transition (`keptInstance` when the managed stop was not confirmed, which
|
|
29
|
-
* is what puts the "no new instance was started" warning back on the card).
|
|
30
|
-
* @param ctx - service context.
|
|
31
|
-
* @param runtime - the runtime the restart action owns.
|
|
32
|
-
* @param keptInstance - whether the old remote instance was kept on purpose.
|
|
33
|
-
* @returns whether the link was still there to resume.
|
|
34
|
-
*/
|
|
14
|
+
/** Put a host back into its connected state without pretending the launch URL changed: one `restart.resumed` transition (`keptInstance` restores the "no new instance was started" warning). */
|
|
35
15
|
export async function resumeConnected(ctx, runtime, keptInstance = false) {
|
|
36
|
-
// A late action must never resurrect a link that was torn down or replaced while it waited:
|
|
37
|
-
// the token is checked by callers, and these are the other three proofs that it still exists.
|
|
38
16
|
if (runtime.desired !== 'connected' || runtime.ssh?.connected !== true || runtime.tunnel === null)
|
|
39
17
|
return false;
|
|
40
18
|
const event = { type: 'restart.resumed', ...(keptInstance ? { keptInstance: true } : {}) };
|