dsh-remote-go 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/{client.js → dist/client.js} +7144 -8367
- package/dist/index.js +4 -0
- package/dist/src/admission.js +21 -0
- package/dist/src/api.js +380 -0
- package/dist/src/atomic-json.js +201 -0
- package/dist/src/bootstrap.js +96 -0
- package/dist/src/connect/attach.js +21 -0
- package/dist/src/connect/bootstrap.js +8 -0
- package/dist/src/connect/failures.js +29 -0
- package/dist/src/connect/guards.js +36 -0
- package/dist/src/connect/launch.js +70 -0
- package/dist/src/connect/links.js +54 -0
- package/dist/src/connect/ownership.js +139 -0
- package/dist/src/connect/pipeline.js +376 -0
- package/dist/src/connect/reattach.js +191 -0
- package/dist/src/connect/registry.js +10 -0
- package/dist/src/connect/repair.js +97 -0
- package/dist/src/connect/restart.js +255 -0
- package/dist/src/connect/stop.js +164 -0
- package/dist/src/connect/transport.js +101 -0
- package/dist/src/connect/verify.js +30 -0
- package/dist/src/connect/watchdog.js +44 -0
- package/dist/src/connect-log.js +137 -0
- package/dist/src/connect-progress.js +110 -0
- package/dist/src/constants.js +29 -0
- package/dist/src/context.js +96 -0
- package/dist/src/diagnostics.js +133 -0
- package/dist/src/download-jobs.js +221 -0
- package/dist/src/errors.js +228 -0
- package/dist/src/events.js +326 -0
- package/dist/src/host-lifecycle.js +368 -0
- package/dist/src/host-registry.js +181 -0
- package/dist/src/host-runtime.js +77 -0
- package/dist/src/host-view.js +52 -0
- package/dist/src/index.js +196 -0
- package/dist/src/kernel-adapter.js +388 -0
- package/dist/src/key-files.js +39 -0
- package/dist/src/known-hosts.js +104 -0
- package/dist/src/layout.js +26 -0
- package/dist/src/local-download.js +311 -0
- package/dist/src/local-ssh.js +23 -0
- package/dist/src/local-version.js +87 -0
- package/dist/src/node/download.js +157 -0
- package/dist/src/node-runtime.js +327 -0
- package/dist/src/probe.js +95 -0
- package/dist/src/prompts.js +198 -0
- package/dist/src/proxy/cookies.js +102 -0
- package/dist/src/proxy/headers.js +167 -0
- package/dist/src/proxy/http.js +134 -0
- package/dist/src/proxy/index.js +121 -0
- package/dist/src/proxy/limits.js +6 -0
- package/dist/src/proxy/routes.js +32 -0
- package/dist/src/proxy/upgrade.js +160 -0
- package/dist/src/redact.js +85 -0
- package/dist/src/remote-files.js +60 -0
- package/dist/src/remote-path.js +82 -0
- package/dist/src/remote-proc.js +271 -0
- package/dist/src/remote-web/registry.js +107 -0
- package/dist/src/remote-web/resolve.js +229 -0
- package/dist/src/remote-web/start.js +190 -0
- package/dist/src/remote-web/stop.js +74 -0
- package/dist/src/request-trust.js +70 -0
- package/dist/src/runtime/dispatch.js +200 -0
- package/dist/src/runtime/effects.js +81 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +70 -0
- package/dist/src/runtime/rules.js +480 -0
- package/dist/src/secrets.js +119 -0
- package/dist/src/service.js +300 -0
- package/dist/src/settings.js +143 -0
- package/dist/src/ssh-config.js +257 -0
- package/dist/src/ssh-failures.js +71 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +258 -0
- package/dist/src/ssh.js +395 -0
- package/dist/src/store.js +174 -0
- package/dist/src/tool-shared.js +146 -0
- package/dist/src/tools-exec-policy.js +121 -0
- package/dist/src/tools-exec.js +307 -0
- package/dist/src/tools-report.js +357 -0
- package/dist/src/tools.js +337 -0
- package/dist/src/tunnel.js +111 -0
- package/dist/src/util.js +112 -0
- package/dist/src/version.js +108 -0
- package/dist/src/watchdog-bus.js +21 -0
- package/dist/src/watchdog.js +116 -0
- package/index.js +5 -4
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +37 -19
- package/src/admission.js +0 -43
- package/src/api.js +0 -536
- package/src/atomic-json.js +0 -225
- package/src/bootstrap.js +0 -113
- package/src/connect-log.js +0 -176
- package/src/connect-pipeline.js +0 -1900
- package/src/connect-progress.js +0 -155
- package/src/constants.js +0 -93
- package/src/diagnostics.js +0 -160
- package/src/download-jobs.js +0 -234
- package/src/errors.js +0 -412
- package/src/host-lifecycle.js +0 -604
- package/src/host-registry.js +0 -217
- package/src/host-runtime.js +0 -127
- package/src/host-view.js +0 -75
- package/src/index.js +0 -206
- package/src/key-files.js +0 -54
- package/src/known-hosts.js +0 -133
- package/src/layout.js +0 -53
- package/src/local-download.js +0 -381
- package/src/local-ssh.js +0 -27
- package/src/local-version.js +0 -88
- package/src/node-runtime.js +0 -521
- package/src/probe.js +0 -101
- package/src/prompts.js +0 -229
- package/src/redact.js +0 -68
- package/src/remote-files.js +0 -71
- package/src/remote-path.js +0 -137
- package/src/remote-proc.js +0 -343
- package/src/remote-proxy.js +0 -815
- package/src/remote-web.js +0 -751
- package/src/request-trust.js +0 -89
- package/src/secrets.js +0 -109
- package/src/service.js +0 -459
- package/src/settings.js +0 -163
- package/src/ssh-config.js +0 -271
- package/src/ssh.js +0 -731
- package/src/store.js +0 -193
- package/src/tools.js +0 -386
- package/src/tunnel.js +0 -132
- package/src/util.js +0 -153
- package/src/version.js +0 -103
- package/src/webapp.js +0 -43
- /package/{vendor → dist/vendor}/ssh2.bundle.cjs +0 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
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. */
|
|
4
|
+
import { createKernelAdapter } from './kernel-adapter.js';
|
|
5
|
+
export function createAdmission(ctx, logger = console) {
|
|
6
|
+
const warn = typeof logger.warn === 'function' ? logger.warn.bind(logger) : () => { };
|
|
7
|
+
const kernel = createKernelAdapter(ctx);
|
|
8
|
+
return (req) => {
|
|
9
|
+
const result = kernel.requestRejection(req);
|
|
10
|
+
if (result.state === 'ok')
|
|
11
|
+
return result.value ?? undefined;
|
|
12
|
+
if (result.state === 'absent') {
|
|
13
|
+
if (result.reason === 'lookup-failed') {
|
|
14
|
+
warn('[dsh-remote-go] DSH connection lookup failed; the local fence stays the only gate:', result.detail);
|
|
15
|
+
}
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
warn('[dsh-remote-go] DSH connection admission failed; rejecting the request:', result.detail);
|
|
19
|
+
return 500;
|
|
20
|
+
};
|
|
21
|
+
}
|
package/dist/src/api.js
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { API_HEADER, API_PREFIX, API_VERSION, PLUGIN_VERSION } from './constants.js';
|
|
2
|
+
import { errors, isRemoteGoError, toErrorView } from './errors.js';
|
|
3
|
+
import { createEventHub } from './events.js';
|
|
4
|
+
import { redactObject } from './redact.js';
|
|
5
|
+
import { sameServerHost, sameServerOrigin } from './request-trust.js';
|
|
6
|
+
import { nowIso } from './util.js';
|
|
7
|
+
const MAX_BODY_BYTES = 1 * 1024 * 1024;
|
|
8
|
+
/** An oversized body is the caller's mistake, not a business conflict (409). */
|
|
9
|
+
const PAYLOAD_TOO_LARGE = 413;
|
|
10
|
+
const VERSION_ROW = { version: PLUGIN_VERSION, apiVersion: API_VERSION };
|
|
11
|
+
const PLUGIN_ROW = { id: 'dsh-remote-go', version: PLUGIN_VERSION };
|
|
12
|
+
/** The HTTP status for an ErrorView: only `invalid-input` (400) and `internal` (500) are special, the rest is 409. */
|
|
13
|
+
export function statusForErrorCode(code) {
|
|
14
|
+
if (code === 'invalid-input')
|
|
15
|
+
return 400;
|
|
16
|
+
if (code === 'internal')
|
|
17
|
+
return 500;
|
|
18
|
+
return 409;
|
|
19
|
+
}
|
|
20
|
+
export function createApi(options) {
|
|
21
|
+
const { service, logger = console } = options;
|
|
22
|
+
const kernelAdmit = typeof options.admit === 'function' ? options.admit : null;
|
|
23
|
+
// Both SSE channels: subscriber sets, caps, heartbeat, 150 ms coalescing and cursor replay.
|
|
24
|
+
const hub = createEventHub({ service, logger });
|
|
25
|
+
const crossSite = () => ({
|
|
26
|
+
ok: false,
|
|
27
|
+
status: 403,
|
|
28
|
+
error: toErrorView(errors.invalidInput('origin', { zh: '跨站请求被拒绝。', en: 'Cross-site requests are rejected.' })),
|
|
29
|
+
});
|
|
30
|
+
function parseOrigin(value) {
|
|
31
|
+
if (typeof value !== 'string' || value === '')
|
|
32
|
+
return null;
|
|
33
|
+
try {
|
|
34
|
+
return new URL(value);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Response body for an admission rejection: the kernel decided, and this route never ran. */
|
|
41
|
+
function admissionView(status) {
|
|
42
|
+
// A gate that could not decide is this plugin's problem, not a client mistake.
|
|
43
|
+
if (status === 500) {
|
|
44
|
+
return { ok: false, error: toErrorView(errors.internal('the DSH connection admission check failed')) };
|
|
45
|
+
}
|
|
46
|
+
const detail = status === 401
|
|
47
|
+
? {
|
|
48
|
+
zh: '这次请求没有通过 DSH 的浏览器会话认证(会话失效或未登录)。',
|
|
49
|
+
en: 'The request did not pass DSH browser-session authentication (no session, or it expired).',
|
|
50
|
+
}
|
|
51
|
+
: {
|
|
52
|
+
zh: '请求没有通过 DSH 的 Host / Origin 准入检查。',
|
|
53
|
+
en: 'The request did not pass DSH Host / Origin admission.',
|
|
54
|
+
};
|
|
55
|
+
return { ok: false, error: toErrorView(errors.invalidInput('request', detail)) };
|
|
56
|
+
}
|
|
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`. */
|
|
59
|
+
function authorizeOrigin(req) {
|
|
60
|
+
const local = parseOrigin(options.getOrigin());
|
|
61
|
+
const origin = req.headers.origin;
|
|
62
|
+
if (typeof origin === 'string' && origin !== '') {
|
|
63
|
+
if (local === null || !sameServerOrigin(origin, local))
|
|
64
|
+
return crossSite();
|
|
65
|
+
}
|
|
66
|
+
if (req.headers['sec-fetch-site'] === 'cross-site')
|
|
67
|
+
return crossSite();
|
|
68
|
+
// An unknown local origin is no reason to reject: admission (when present) already judged Host.
|
|
69
|
+
if (local !== null && !sameServerHost(req.headers.host, local))
|
|
70
|
+
return crossSite();
|
|
71
|
+
return { ok: true };
|
|
72
|
+
}
|
|
73
|
+
function authorize(req) {
|
|
74
|
+
const origin = authorizeOrigin(req);
|
|
75
|
+
if (!origin.ok)
|
|
76
|
+
return origin;
|
|
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
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function readJson(req) {
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
const chunks = [];
|
|
91
|
+
let size = 0;
|
|
92
|
+
let refused = false;
|
|
93
|
+
req.on('data', (chunk) => {
|
|
94
|
+
if (refused)
|
|
95
|
+
return;
|
|
96
|
+
size += chunk.length;
|
|
97
|
+
if (size > MAX_BODY_BYTES) {
|
|
98
|
+
refused = true;
|
|
99
|
+
chunks.length = 0;
|
|
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);
|
|
108
|
+
req.resume();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
chunks.push(Buffer.from(chunk));
|
|
112
|
+
});
|
|
113
|
+
req.on('end', () => {
|
|
114
|
+
if (refused)
|
|
115
|
+
return;
|
|
116
|
+
if (chunks.length === 0) {
|
|
117
|
+
resolve({});
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const text = Buffer.concat(chunks).toString('utf8').trim();
|
|
122
|
+
resolve(text === '' ? {} : JSON.parse(text));
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
reject(errors.invalidInput('body', { zh: '请求体不是合法 JSON。', en: 'The request body is not valid JSON.' }));
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
req.on('error', reject);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
function sendJson(res, status, payload) {
|
|
132
|
+
const body = JSON.stringify(payload);
|
|
133
|
+
res.writeHead(status, {
|
|
134
|
+
'content-type': 'application/json; charset=utf-8',
|
|
135
|
+
'cache-control': 'no-store',
|
|
136
|
+
'content-length': Buffer.byteLength(body),
|
|
137
|
+
});
|
|
138
|
+
res.end(body);
|
|
139
|
+
}
|
|
140
|
+
/** Which SSE channel a GET path names, or null; both routes share one pre-condition. */
|
|
141
|
+
function sseRoute(path, method) {
|
|
142
|
+
if (method !== 'GET')
|
|
143
|
+
return null;
|
|
144
|
+
if (path === '/events')
|
|
145
|
+
return 'state';
|
|
146
|
+
if (path === '/events/logs')
|
|
147
|
+
return 'logs';
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
const ROUTES = {
|
|
151
|
+
// A liveness probe only: no state, no version, nothing worth reading without a session.
|
|
152
|
+
'GET /health': () => ({ ok: true }),
|
|
153
|
+
'GET /state': () => ({ ok: true, state: service.snapshot() }),
|
|
154
|
+
'GET /version': () => ({ ok: true, ...VERSION_ROW, hostVersion: service.localVersion }),
|
|
155
|
+
'GET /ssh/aliases': async () => ({ ok: true, ...(await service.discoverSshAliases()) }),
|
|
156
|
+
'GET /keyfile/list': async (req, url) => ({
|
|
157
|
+
ok: true,
|
|
158
|
+
...(await service.listKeyFiles(url.searchParams.get('path') ?? '')),
|
|
159
|
+
}),
|
|
160
|
+
// Machine paths and the client-module row are troubleshooting data: redact them like any export.
|
|
161
|
+
'GET /diagnostics/self': () => redactObject({
|
|
162
|
+
ok: true,
|
|
163
|
+
plugin: PLUGIN_ROW,
|
|
164
|
+
at: nowIso(),
|
|
165
|
+
...(typeof options.diagnostics === 'function' ? options.diagnostics() : {}),
|
|
166
|
+
}),
|
|
167
|
+
'POST /hosts': async (req) => {
|
|
168
|
+
const body = await readJson(req);
|
|
169
|
+
return { ok: true, host: await service.saveHost((body.host ?? body)) };
|
|
170
|
+
},
|
|
171
|
+
'POST /settings': async (req) => {
|
|
172
|
+
const body = await readJson(req);
|
|
173
|
+
return { ok: true, settings: await service.saveSettings(body.patch ?? body) };
|
|
174
|
+
},
|
|
175
|
+
'POST /local-version': async (req) => {
|
|
176
|
+
const { version } = await readJson(req);
|
|
177
|
+
// The client backfills only a missing probe: the service adopts it when unknown and above the engines floor.
|
|
178
|
+
return { ok: true, accepted: service.setLocalVersion(String(version ?? ''), 'client') };
|
|
179
|
+
},
|
|
180
|
+
'POST /active': async (req) => {
|
|
181
|
+
const { id } = await readJson(req);
|
|
182
|
+
service.setActiveHost(typeof id === 'string' ? id : null);
|
|
183
|
+
return { ok: true };
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
const HOST_ACTIONS = {
|
|
187
|
+
DELETE: async (id) => {
|
|
188
|
+
await service.removeHost(id);
|
|
189
|
+
return { ok: true };
|
|
190
|
+
},
|
|
191
|
+
'POST connect': async (id, req) => {
|
|
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.
|
|
194
|
+
const result = await service.connect(id, {
|
|
195
|
+
password: typeof body.password === 'string' ? body.password : undefined,
|
|
196
|
+
rememberPassword: body.rememberPassword !== false,
|
|
197
|
+
});
|
|
198
|
+
return { ok: true, ...result };
|
|
199
|
+
},
|
|
200
|
+
'POST password': async (id, req) => {
|
|
201
|
+
const body = await readJson(req);
|
|
202
|
+
const result = await service.saveHostPassword(id, {
|
|
203
|
+
password: typeof body.password === 'string' ? body.password : undefined,
|
|
204
|
+
clear: body.clear === true,
|
|
205
|
+
});
|
|
206
|
+
return { ok: true, ...result };
|
|
207
|
+
},
|
|
208
|
+
'POST conflict': async (id, req) => {
|
|
209
|
+
const { action } = await readJson(req);
|
|
210
|
+
return { ok: true, ...(await service.confirmConflict(id, { action })) };
|
|
211
|
+
},
|
|
212
|
+
'POST disconnect': async (id, req) => {
|
|
213
|
+
const { stopRemote } = await readJson(req);
|
|
214
|
+
await service.disconnect(id, { stopRemote: stopRemote === true });
|
|
215
|
+
return { ok: true };
|
|
216
|
+
},
|
|
217
|
+
'POST reconnect': async (id) => {
|
|
218
|
+
await service.reconnect(id);
|
|
219
|
+
return { ok: true };
|
|
220
|
+
},
|
|
221
|
+
'POST restart': async (id) => ({ ok: true, ...(await service.restart(id)) }),
|
|
222
|
+
'POST stop-remote': async (id) => ({ ok: true, ...(await service.stopRemote(id)) }),
|
|
223
|
+
'POST fingerprint': async (id, req) => {
|
|
224
|
+
const body = await readJson(req);
|
|
225
|
+
await service.confirmFingerprint(id, {
|
|
226
|
+
accept: body.accept === true,
|
|
227
|
+
remember: body.remember === true,
|
|
228
|
+
sha256: typeof body.sha256 === 'string' ? body.sha256 : undefined,
|
|
229
|
+
});
|
|
230
|
+
return { ok: true };
|
|
231
|
+
},
|
|
232
|
+
'POST diagnose': async (id) => ({ ok: true, report: await service.diagnose(id) }),
|
|
233
|
+
'GET open': (id) => ({ ok: true, ...service.openInfo(id) }),
|
|
234
|
+
'POST activate': (id) => {
|
|
235
|
+
service.setActiveHost(id);
|
|
236
|
+
return { ok: true };
|
|
237
|
+
},
|
|
238
|
+
};
|
|
239
|
+
function hostHandler(hostPath, method) {
|
|
240
|
+
const segments = hostPath.split('/').filter(Boolean);
|
|
241
|
+
if (segments[0] !== 'hosts' || segments.length < 2)
|
|
242
|
+
return null;
|
|
243
|
+
const key = segments[2] ? `${method} ${segments[2]}` : method;
|
|
244
|
+
if (!Object.hasOwn(HOST_ACTIONS, key))
|
|
245
|
+
return null;
|
|
246
|
+
let id;
|
|
247
|
+
try {
|
|
248
|
+
id = decodeURIComponent(segments[1]);
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
// A malformed escape is a client mistake: answer 400 with a field error instead of leaking URIError as 500.
|
|
252
|
+
throw errors.invalidInput('id', {
|
|
253
|
+
zh: '主机 id 不是合法的 URL 编码。',
|
|
254
|
+
en: 'The host id is not valid URL encoding.',
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
return { id, run: HOST_ACTIONS[key] };
|
|
258
|
+
}
|
|
259
|
+
async function handler(req, res) {
|
|
260
|
+
try {
|
|
261
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
262
|
+
if (!url.pathname.startsWith(API_PREFIX)) {
|
|
263
|
+
sendJson(res, 404, {
|
|
264
|
+
ok: false,
|
|
265
|
+
error: toErrorView(errors.invalidInput('path', { zh: '未知 API 路径。', en: 'Unknown API path.' })),
|
|
266
|
+
});
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
const path = url.pathname.slice(API_PREFIX.length) || '/';
|
|
270
|
+
const method = (req.method ?? 'GET').toUpperCase();
|
|
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.
|
|
273
|
+
const probe = path === '/health' && method === 'GET';
|
|
274
|
+
if (!probe) {
|
|
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));
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
if (probe) {
|
|
283
|
+
const trust = authorizeOrigin(req);
|
|
284
|
+
if (!trust.ok) {
|
|
285
|
+
sendJson(res, trust.status, { ok: false, error: trust.error });
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
sendJson(res, 200, ROUTES['GET /health']());
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
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).
|
|
293
|
+
const sse = sseRoute(path, method);
|
|
294
|
+
if (sse !== null) {
|
|
295
|
+
const originOnly = authorizeOrigin(req);
|
|
296
|
+
if (!originOnly.ok) {
|
|
297
|
+
sendJson(res, originOnly.status, { ok: false, error: originOnly.error });
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
await service.init();
|
|
301
|
+
if (sse === 'logs')
|
|
302
|
+
hub.handleLogs(req, res);
|
|
303
|
+
else
|
|
304
|
+
hub.handleState(req, res);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
const auth = authorize(req);
|
|
308
|
+
if (!auth.ok) {
|
|
309
|
+
sendJson(res, auth.status, { ok: false, error: auth.error });
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
await service.init();
|
|
313
|
+
const segments = path.split('/').filter(Boolean);
|
|
314
|
+
if (method === 'POST' && path === '/downloads') {
|
|
315
|
+
const body = await readJson(req);
|
|
316
|
+
const job = await service.startRemoteDownload(body.hostId, body.path, {
|
|
317
|
+
destination: body.destination,
|
|
318
|
+
});
|
|
319
|
+
sendJson(res, 200, { ok: true, job });
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (segments[0] === 'downloads' && segments.length >= 2 && segments.length <= 3) {
|
|
323
|
+
let jobId = '';
|
|
324
|
+
try {
|
|
325
|
+
jobId = decodeURIComponent(segments[1]);
|
|
326
|
+
}
|
|
327
|
+
catch {
|
|
328
|
+
throw errors.invalidInput('id', {
|
|
329
|
+
zh: '下载任务 id 不是合法的 URL 编码。',
|
|
330
|
+
en: 'The download job id is not valid URL encoding.',
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
if (method === 'GET' && segments.length === 3 && segments[2] === 'status') {
|
|
334
|
+
sendJson(res, 200, { ok: true, job: await service.remoteDownloadStatus(jobId) });
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
if (method === 'DELETE' && segments.length === 2) {
|
|
338
|
+
await service.cancelRemoteDownload(jobId);
|
|
339
|
+
sendJson(res, 200, { ok: true });
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
const routeKey = `${method} ${path}`;
|
|
344
|
+
if (Object.hasOwn(ROUTES, routeKey)) {
|
|
345
|
+
sendJson(res, 200, await ROUTES[routeKey](req, url));
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
const host = hostHandler(path, method);
|
|
349
|
+
if (host) {
|
|
350
|
+
sendJson(res, 200, await host.run(host.id, req));
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
sendJson(res, 404, {
|
|
354
|
+
ok: false,
|
|
355
|
+
error: toErrorView(errors.invalidInput('path', { zh: `未知路径 ${method} ${path}`, en: `Unknown path ${method} ${path}` })),
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
catch (error) {
|
|
359
|
+
const view = toErrorView(error);
|
|
360
|
+
const status = Number.isInteger(error?.httpStatus)
|
|
361
|
+
? error.httpStatus
|
|
362
|
+
: isRemoteGoError(error)
|
|
363
|
+
? statusForErrorCode(view.code)
|
|
364
|
+
: 500;
|
|
365
|
+
logger.error?.('[dsh-remote-go] API error:', error);
|
|
366
|
+
try {
|
|
367
|
+
sendJson(res, status, { ok: false, error: view });
|
|
368
|
+
}
|
|
369
|
+
catch {
|
|
370
|
+
// swallow-ok: the response is already gone; a failed write cannot be reported on it
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return {
|
|
375
|
+
handler,
|
|
376
|
+
dispose() {
|
|
377
|
+
hub.dispose();
|
|
378
|
+
},
|
|
379
|
+
};
|
|
380
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/** Atomic JSON persistence: 0700 dir, 0600 file, fsynced temp, rename retry and a cross-process lock; a bad file is reported, never thrown. */
|
|
2
|
+
import { promises as fs } from 'node:fs';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { sleep } from './util.js';
|
|
7
|
+
const RENAME_RETRY_ATTEMPTS = 5;
|
|
8
|
+
const RENAME_RETRY_BASE_MS = 20;
|
|
9
|
+
const LOCK_STALE_MS = 10_000;
|
|
10
|
+
const LOCK_WAIT_MS = 20_000;
|
|
11
|
+
const LOCK_RETRY_MS = 10;
|
|
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. */
|
|
14
|
+
const LOCK_TRANSIENT_MS = 250;
|
|
15
|
+
const LOCK_UNLINK_ATTEMPTS = 3;
|
|
16
|
+
/** In-process chains keyed by lock path; the value is the always-settled tail so a rejected write never poisons the next waiter. */
|
|
17
|
+
const LOCAL_CHAINS = new Map();
|
|
18
|
+
/** Run `task` under the cross-process lock, serialized with every in-process holder of the same lock path. */
|
|
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
|
+
};
|
|
29
|
+
const previous = LOCAL_CHAINS.get(lockFile) ?? Promise.resolve();
|
|
30
|
+
const run = previous.then(start, start);
|
|
31
|
+
LOCAL_CHAINS.set(lockFile, run.catch(() => undefined));
|
|
32
|
+
return run;
|
|
33
|
+
}
|
|
34
|
+
async function acquireLock(lockFile, options) {
|
|
35
|
+
const fsImpl = options.fs ?? fs;
|
|
36
|
+
const staleMs = options.staleMs ?? LOCK_STALE_MS;
|
|
37
|
+
const waitMs = options.waitMs ?? LOCK_WAIT_MS;
|
|
38
|
+
const retryMs = options.retryMs ?? LOCK_RETRY_MS;
|
|
39
|
+
const started = Date.now();
|
|
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.
|
|
42
|
+
let sawLock = false;
|
|
43
|
+
while (true) {
|
|
44
|
+
try {
|
|
45
|
+
const handle = await fsImpl.open(lockFile, 'wx', 0o600);
|
|
46
|
+
return async () => {
|
|
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).
|
|
51
|
+
for (let attempt = 0; attempt < LOCK_UNLINK_ATTEMPTS; attempt += 1) {
|
|
52
|
+
try {
|
|
53
|
+
await fsImpl.unlink(lockFile);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
catch (unlinkError) {
|
|
57
|
+
const unlinkCode = unlinkError?.code;
|
|
58
|
+
if (unlinkCode === 'ENOENT' || attempt === LOCK_UNLINK_ATTEMPTS - 1)
|
|
59
|
+
return;
|
|
60
|
+
await sleep(retryMs);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
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.
|
|
68
|
+
const code = error?.code;
|
|
69
|
+
if (code !== 'EEXIST' && code !== 'EPERM' && code !== 'EACCES' && code !== 'EBUSY')
|
|
70
|
+
throw error;
|
|
71
|
+
if (code !== 'EEXIST' && !sawLock && Date.now() - started > LOCK_TRANSIENT_MS) {
|
|
72
|
+
if (!(await lockExists(fsImpl, lockFile)))
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
if (code === 'EEXIST' || (await lockExists(fsImpl, lockFile)))
|
|
76
|
+
sawLock = true;
|
|
77
|
+
await breakStaleLock(fsImpl, lockFile, staleMs);
|
|
78
|
+
if (Date.now() - started > waitMs) {
|
|
79
|
+
const timeout = new Error('timed out waiting for another process to release the store lock');
|
|
80
|
+
timeout.code = 'ELOCKTIMEOUT';
|
|
81
|
+
throw timeout;
|
|
82
|
+
}
|
|
83
|
+
await sleep(retryMs);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async function breakStaleLock(fsImpl, lockFile, staleMs) {
|
|
88
|
+
try {
|
|
89
|
+
const info = await fsImpl.stat(lockFile);
|
|
90
|
+
if (Date.now() - info.mtimeMs > staleMs)
|
|
91
|
+
await removeQuietly(fsImpl, lockFile);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// swallow-ok: the lock disappeared or cannot be inspected; the create retries
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
export async function writeJsonAtomic(file, value, options = {}) {
|
|
98
|
+
const fsImpl = options.fs ?? fs;
|
|
99
|
+
const logger = options.logger ?? console;
|
|
100
|
+
const dir = options.dir ?? path.dirname(file);
|
|
101
|
+
const dirMode = options.dirMode ?? 0o700;
|
|
102
|
+
const fileMode = options.fileMode ?? 0o600;
|
|
103
|
+
try {
|
|
104
|
+
await fsImpl.mkdir(dir, { recursive: true, mode: dirMode });
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
logger.warn?.(`[dsh-remote-go] cannot create ${dir}:`, error);
|
|
108
|
+
}
|
|
109
|
+
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
110
|
+
const text = `${JSON.stringify(value, null, 2)}\n`;
|
|
111
|
+
let handle = null;
|
|
112
|
+
try {
|
|
113
|
+
handle = await fsImpl.open(tmp, 'wx', fileMode);
|
|
114
|
+
await handle.writeFile(text, 'utf8');
|
|
115
|
+
await handle.sync();
|
|
116
|
+
await handle.close();
|
|
117
|
+
handle = null;
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
// The temp file is removed right below, so a close error here is not fixable.
|
|
121
|
+
if (handle)
|
|
122
|
+
await handle.close().catch(() => { });
|
|
123
|
+
await removeQuietly(fsImpl, tmp);
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
await renameWithRetry(fsImpl, tmp, file);
|
|
127
|
+
await syncDir(fsImpl, dir);
|
|
128
|
+
}
|
|
129
|
+
async function renameWithRetry(fsImpl, tmp, file) {
|
|
130
|
+
for (let attempt = 1; attempt <= RENAME_RETRY_ATTEMPTS; attempt += 1) {
|
|
131
|
+
try {
|
|
132
|
+
await fsImpl.rename(tmp, file);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
const code = error?.code;
|
|
137
|
+
const retryable = code === 'EPERM' || code === 'EBUSY' || code === 'EACCES';
|
|
138
|
+
if (retryable && attempt < RENAME_RETRY_ATTEMPTS) {
|
|
139
|
+
await sleep(RENAME_RETRY_BASE_MS * attempt);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
await removeQuietly(fsImpl, tmp);
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async function syncDir(fsImpl, dir) {
|
|
148
|
+
let handle = null;
|
|
149
|
+
try {
|
|
150
|
+
handle = await fsImpl.open(dir, 'r');
|
|
151
|
+
await handle.sync();
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
// swallow-ok: directory fsync is not supported on every platform or filesystem
|
|
155
|
+
}
|
|
156
|
+
finally {
|
|
157
|
+
if (handle)
|
|
158
|
+
await handle.close().catch(() => { });
|
|
159
|
+
}
|
|
160
|
+
}
|
|
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. */
|
|
163
|
+
export async function readJsonFile(file, options = {}) {
|
|
164
|
+
const fsImpl = options.fs ?? fs;
|
|
165
|
+
const logger = options.logger ?? console;
|
|
166
|
+
let text;
|
|
167
|
+
try {
|
|
168
|
+
if (!existsSync(file))
|
|
169
|
+
return { status: 'missing', value: null };
|
|
170
|
+
text = await fsImpl.readFile(file, 'utf8');
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
logger.warn?.(`[dsh-remote-go] cannot read ${path.basename(file)}:`, error);
|
|
174
|
+
return { status: 'unreadable', value: null };
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
return { status: 'ok', value: JSON.parse(text) };
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
logger.warn?.(`[dsh-remote-go] ${path.basename(file)} is not valid JSON:`, error);
|
|
181
|
+
return { status: 'corrupt', value: null };
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
async function removeQuietly(fsImpl, target) {
|
|
185
|
+
try {
|
|
186
|
+
await fsImpl.unlink(target);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
// swallow-ok: a missing temp file is the success case for this cleanup
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async function lockExists(fsImpl, lockFile) {
|
|
193
|
+
try {
|
|
194
|
+
await fsImpl.stat(lockFile);
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
// swallow-ok: a lock that cannot be inspected is treated as absent
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
}
|