dsh-remote-go 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/{client.js → dist/client.js} +7710 -8182
- package/dist/index.js +4 -0
- package/dist/src/admission.js +46 -0
- package/dist/src/api.js +442 -0
- package/dist/src/atomic-json.js +235 -0
- package/dist/src/bootstrap.js +106 -0
- package/dist/src/connect/attach.js +43 -0
- package/dist/src/connect/bootstrap.js +14 -0
- package/dist/src/connect/failures.js +44 -0
- package/dist/src/connect/guards.js +31 -0
- package/dist/src/connect/launch.js +80 -0
- package/dist/src/connect/links.js +70 -0
- package/dist/src/connect/ownership.js +220 -0
- package/dist/src/connect/pipeline.js +473 -0
- package/dist/src/connect/reattach.js +215 -0
- package/dist/src/connect/registry.js +11 -0
- package/dist/src/connect/repair.js +126 -0
- package/dist/src/connect/restart.js +316 -0
- package/dist/src/connect/stop.js +198 -0
- package/dist/src/connect/transport.js +109 -0
- package/dist/src/connect/verify.js +39 -0
- package/dist/src/connect/watchdog.js +76 -0
- package/dist/src/connect-log.js +162 -0
- package/dist/src/connect-progress.js +142 -0
- package/{src → dist/src}/constants.js +30 -56
- package/dist/src/context.js +117 -0
- package/dist/src/diagnostics.js +102 -0
- package/dist/src/download-jobs.js +230 -0
- package/dist/src/errors.js +243 -0
- package/dist/src/events.js +390 -0
- package/dist/src/host-lifecycle.js +504 -0
- package/dist/src/host-registry.js +232 -0
- package/dist/src/host-runtime.js +86 -0
- package/dist/src/host-view.js +75 -0
- package/dist/src/index.js +216 -0
- package/dist/src/kernel-adapter.js +434 -0
- package/dist/src/key-files.js +52 -0
- package/dist/src/known-hosts.js +125 -0
- package/dist/src/layout.js +43 -0
- package/dist/src/local-download.js +380 -0
- package/dist/src/local-ssh.js +30 -0
- package/dist/src/local-version.js +101 -0
- package/dist/src/node/download.js +160 -0
- package/dist/src/node-runtime.js +346 -0
- package/dist/src/probe.js +96 -0
- package/dist/src/prompts.js +270 -0
- package/dist/src/proxy/cookies.js +136 -0
- package/dist/src/proxy/headers.js +262 -0
- package/dist/src/proxy/http.js +142 -0
- package/dist/src/proxy/index.js +135 -0
- package/dist/src/proxy/limits.js +8 -0
- package/dist/src/proxy/routes.js +39 -0
- package/dist/src/proxy/upgrade.js +175 -0
- package/dist/src/redact.js +104 -0
- package/dist/src/remote-files.js +72 -0
- package/dist/src/remote-path.js +123 -0
- package/dist/src/remote-proc.js +339 -0
- package/dist/src/remote-web/registry.js +147 -0
- package/dist/src/remote-web/resolve.js +310 -0
- package/dist/src/remote-web/start.js +227 -0
- package/dist/src/remote-web/stop.js +93 -0
- package/dist/src/request-trust.js +87 -0
- package/dist/src/runtime/dispatch.js +310 -0
- package/dist/src/runtime/effects.js +91 -0
- package/dist/src/runtime/events.js +35 -0
- package/dist/src/runtime/fsm.js +120 -0
- package/dist/src/runtime/rules.js +565 -0
- package/dist/src/secrets.js +142 -0
- package/dist/src/service.js +406 -0
- package/dist/src/settings.js +144 -0
- package/dist/src/ssh-config.js +276 -0
- package/dist/src/ssh-failures.js +122 -0
- package/dist/src/ssh-port.js +4 -0
- package/dist/src/ssh-sftp.js +297 -0
- package/dist/src/ssh.js +477 -0
- package/dist/src/store.js +191 -0
- package/dist/src/tool-shared.js +181 -0
- package/dist/src/tools-exec-policy.js +167 -0
- package/dist/src/tools-exec.js +371 -0
- package/dist/src/tools-report.js +424 -0
- package/dist/src/tools.js +411 -0
- package/dist/src/tunnel.js +129 -0
- package/dist/src/util.js +149 -0
- package/dist/src/version.js +114 -0
- package/dist/src/watchdog-bus.js +29 -0
- package/dist/src/watchdog.js +156 -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/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,46 @@
|
|
|
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
|
+
* 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
|
+
*/
|
|
15
|
+
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
|
+
export function createAdmission(ctx, logger = console) {
|
|
29
|
+
const warn = typeof logger.warn === 'function' ? logger.warn.bind(logger) : () => { };
|
|
30
|
+
const kernel = createKernelAdapter(ctx);
|
|
31
|
+
return (req) => {
|
|
32
|
+
const result = kernel.requestRejection(req);
|
|
33
|
+
if (result.state === 'ok')
|
|
34
|
+
return result.value ?? undefined;
|
|
35
|
+
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
|
+
if (result.reason === 'lookup-failed') {
|
|
39
|
+
warn('[dsh-remote-go] DSH connection lookup failed; the local fence stays the only gate:', result.detail);
|
|
40
|
+
}
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
warn('[dsh-remote-go] DSH connection admission failed; rejecting the request:', result.detail);
|
|
44
|
+
return 500;
|
|
45
|
+
};
|
|
46
|
+
}
|
package/dist/src/api.js
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
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
|
+
/** HTTP status for one `invalid-input` refusal: an oversized body is not a business conflict. */
|
|
9
|
+
const PAYLOAD_TOO_LARGE = 413;
|
|
10
|
+
/** `/version` and `/diagnostics/self` share one version row. */
|
|
11
|
+
const VERSION_ROW = { version: PLUGIN_VERSION, apiVersion: API_VERSION };
|
|
12
|
+
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
|
+
*/
|
|
18
|
+
export function statusForErrorCode(code) {
|
|
19
|
+
if (code === 'invalid-input')
|
|
20
|
+
return 400;
|
|
21
|
+
if (code === 'internal')
|
|
22
|
+
return 500;
|
|
23
|
+
return 409;
|
|
24
|
+
}
|
|
25
|
+
export function createApi(options) {
|
|
26
|
+
const { service } = options;
|
|
27
|
+
const logger = options.logger ?? console;
|
|
28
|
+
const kernelAdmit = typeof options.admit === 'function' ? options.admit : null;
|
|
29
|
+
// Both SSE channels: subscriber sets, caps, heartbeat, 150 ms coalescing and cursor replay.
|
|
30
|
+
const hub = createEventHub({ service, logger });
|
|
31
|
+
const crossSite = () => ({
|
|
32
|
+
ok: false,
|
|
33
|
+
status: 403,
|
|
34
|
+
error: toErrorView(errors.invalidInput('origin', { zh: '跨站请求被拒绝。', en: 'Cross-site requests are rejected.' })),
|
|
35
|
+
});
|
|
36
|
+
/** The listener origin as a URL, or null while the kernel cannot name it yet. */
|
|
37
|
+
function parseOrigin(value) {
|
|
38
|
+
if (typeof value !== 'string' || value === '')
|
|
39
|
+
return null;
|
|
40
|
+
try {
|
|
41
|
+
return new URL(value);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
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
|
+
/** Response body for an admission rejection: the kernel decided, and this route never ran. */
|
|
60
|
+
function admissionView(status) {
|
|
61
|
+
// A gate that could not decide is this plugin's problem, not a client mistake.
|
|
62
|
+
if (status === 500) {
|
|
63
|
+
return { ok: false, error: toErrorView(errors.internal('the DSH connection admission check failed')) };
|
|
64
|
+
}
|
|
65
|
+
const detail = status === 401
|
|
66
|
+
? {
|
|
67
|
+
zh: '这次请求没有通过 DSH 的浏览器会话认证(会话失效或未登录)。',
|
|
68
|
+
en: 'The request did not pass DSH browser-session authentication (no session, or it expired).',
|
|
69
|
+
}
|
|
70
|
+
: {
|
|
71
|
+
zh: '请求没有通过 DSH 的 Host / Origin 准入检查。',
|
|
72
|
+
en: 'The request did not pass DSH Host / Origin admission.',
|
|
73
|
+
};
|
|
74
|
+
return { ok: false, error: toErrorView(errors.invalidInput('request', detail)) };
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Browser trust for same-origin reads (used by SSE, which cannot set custom
|
|
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
|
+
*/
|
|
90
|
+
function authorizeOrigin(req) {
|
|
91
|
+
const local = parseOrigin(options.getOrigin());
|
|
92
|
+
const origin = req.headers.origin;
|
|
93
|
+
if (typeof origin === 'string' && origin !== '') {
|
|
94
|
+
if (local === null || !sameServerOrigin(origin, local))
|
|
95
|
+
return crossSite();
|
|
96
|
+
}
|
|
97
|
+
if (req.headers['sec-fetch-site'] === 'cross-site')
|
|
98
|
+
return crossSite();
|
|
99
|
+
// An origin the kernel cannot name yet is no reason to reject local traffic; the kernel's own
|
|
100
|
+
// admission (when present) has already judged Host, and this fence is the fallback.
|
|
101
|
+
if (local !== null && !sameServerHost(req.headers.host, local))
|
|
102
|
+
return crossSite();
|
|
103
|
+
return { ok: true };
|
|
104
|
+
}
|
|
105
|
+
function authorize(req) {
|
|
106
|
+
const origin = authorizeOrigin(req);
|
|
107
|
+
if (!origin.ok)
|
|
108
|
+
return origin;
|
|
109
|
+
if (req.headers[API_HEADER] !== '1') {
|
|
110
|
+
return {
|
|
111
|
+
ok: false,
|
|
112
|
+
status: 403,
|
|
113
|
+
error: toErrorView(errors.invalidInput(API_HEADER, {
|
|
114
|
+
zh: '请求缺少本地插件标识头。',
|
|
115
|
+
en: 'The request is missing the local plugin header.',
|
|
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;
|
|
129
|
+
}
|
|
130
|
+
function readJson(req) {
|
|
131
|
+
return new Promise((resolve, reject) => {
|
|
132
|
+
const chunks = [];
|
|
133
|
+
let size = 0;
|
|
134
|
+
let refused = false;
|
|
135
|
+
req.on('data', (chunk) => {
|
|
136
|
+
if (refused)
|
|
137
|
+
return;
|
|
138
|
+
size += chunk.length;
|
|
139
|
+
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
|
+
refused = true;
|
|
144
|
+
chunks.length = 0;
|
|
145
|
+
reject(payloadTooLarge());
|
|
146
|
+
req.resume();
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
chunks.push(Buffer.from(chunk));
|
|
150
|
+
});
|
|
151
|
+
req.on('end', () => {
|
|
152
|
+
if (refused)
|
|
153
|
+
return;
|
|
154
|
+
if (chunks.length === 0) {
|
|
155
|
+
resolve({});
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
const text = Buffer.concat(chunks).toString('utf8').trim();
|
|
160
|
+
resolve(text === '' ? {} : JSON.parse(text));
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
reject(errors.invalidInput('body', { zh: '请求体不是合法 JSON。', en: 'The request body is not valid JSON.' }));
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
req.on('error', reject);
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
function sendJson(res, status, payload) {
|
|
170
|
+
const body = JSON.stringify(payload);
|
|
171
|
+
res.writeHead(status, {
|
|
172
|
+
'content-type': 'application/json; charset=utf-8',
|
|
173
|
+
'cache-control': 'no-store',
|
|
174
|
+
'content-length': Buffer.byteLength(body),
|
|
175
|
+
});
|
|
176
|
+
res.end(body);
|
|
177
|
+
}
|
|
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
|
+
*/
|
|
183
|
+
function sseRoute(path, method) {
|
|
184
|
+
if (method !== 'GET')
|
|
185
|
+
return null;
|
|
186
|
+
if (path === '/events')
|
|
187
|
+
return 'state';
|
|
188
|
+
if (path === '/events/logs')
|
|
189
|
+
return 'logs';
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
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
|
+
const ROUTES = {
|
|
195
|
+
// A liveness probe only: no state, no version, nothing worth reading without a session.
|
|
196
|
+
'GET /health': () => ({ ok: true }),
|
|
197
|
+
'GET /state': () => ({ ok: true, state: service.snapshot() }),
|
|
198
|
+
'GET /version': () => ({ ok: true, ...VERSION_ROW, hostVersion: service.localVersion }),
|
|
199
|
+
'GET /ssh/aliases': async () => ({ ok: true, ...(await service.discoverSshAliases()) }),
|
|
200
|
+
'GET /keyfile/list': async (req, url) => ({
|
|
201
|
+
ok: true,
|
|
202
|
+
...(await service.listKeyFiles(url.searchParams.get('path') ?? '')),
|
|
203
|
+
}),
|
|
204
|
+
// Machine paths (`home`, `stateDir`) and the client-module row are troubleshooting data,
|
|
205
|
+
// not the user's business: redact them like any other diagnostic export.
|
|
206
|
+
'GET /diagnostics/self': () => redactObject({
|
|
207
|
+
ok: true,
|
|
208
|
+
plugin: PLUGIN_ROW,
|
|
209
|
+
at: nowIso(),
|
|
210
|
+
...(typeof options.diagnostics === 'function' ? options.diagnostics() : {}),
|
|
211
|
+
}),
|
|
212
|
+
'POST /hosts': async (req) => {
|
|
213
|
+
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
|
+
return { ok: true, host: await service.saveHost((body.host ?? body)) };
|
|
217
|
+
},
|
|
218
|
+
'POST /settings': async (req) => {
|
|
219
|
+
const body = await readJson(req);
|
|
220
|
+
return { ok: true, settings: await service.saveSettings(body.patch ?? body) };
|
|
221
|
+
},
|
|
222
|
+
'POST /local-version': async (req) => {
|
|
223
|
+
const { version } = await readJson(req);
|
|
224
|
+
// The client only backfills a *missing* probe result; the service decides whether this
|
|
225
|
+
// one may be adopted (unknown locally, and not below DSH's `engines.dsh` floor).
|
|
226
|
+
return { ok: true, accepted: service.setLocalVersion(String(version ?? ''), 'client') };
|
|
227
|
+
},
|
|
228
|
+
'POST /active': async (req) => {
|
|
229
|
+
const { id } = await readJson(req);
|
|
230
|
+
service.setActiveHost(typeof id === 'string' ? id : null);
|
|
231
|
+
return { ok: true };
|
|
232
|
+
},
|
|
233
|
+
};
|
|
234
|
+
// `/hosts/:id` and `/hosts/:id/<action>`, keyed the same way.
|
|
235
|
+
const HOST_ACTIONS = {
|
|
236
|
+
DELETE: async (id) => {
|
|
237
|
+
await service.removeHost(id);
|
|
238
|
+
return { ok: true };
|
|
239
|
+
},
|
|
240
|
+
'POST connect': async (id, req) => {
|
|
241
|
+
const body = await readJson(req);
|
|
242
|
+
const result = await service.connect(id, {
|
|
243
|
+
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
|
+
rememberPassword: body.rememberPassword !== false,
|
|
247
|
+
});
|
|
248
|
+
return { ok: true, ...result };
|
|
249
|
+
},
|
|
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
|
+
'POST password': async (id, req) => {
|
|
254
|
+
const body = await readJson(req);
|
|
255
|
+
const result = await service.saveHostPassword(id, {
|
|
256
|
+
password: typeof body.password === 'string' ? body.password : undefined,
|
|
257
|
+
clear: body.clear === true,
|
|
258
|
+
});
|
|
259
|
+
return { ok: true, ...result };
|
|
260
|
+
},
|
|
261
|
+
'POST conflict': async (id, req) => {
|
|
262
|
+
const { action } = await readJson(req);
|
|
263
|
+
return { ok: true, ...(await service.confirmConflict(id, { action })) };
|
|
264
|
+
},
|
|
265
|
+
'POST disconnect': async (id, req) => {
|
|
266
|
+
const { stopRemote } = await readJson(req);
|
|
267
|
+
await service.disconnect(id, { stopRemote: stopRemote === true });
|
|
268
|
+
return { ok: true };
|
|
269
|
+
},
|
|
270
|
+
'POST reconnect': async (id) => {
|
|
271
|
+
await service.reconnect(id);
|
|
272
|
+
return { ok: true };
|
|
273
|
+
},
|
|
274
|
+
'POST restart': async (id) => ({ ok: true, ...(await service.restart(id)) }),
|
|
275
|
+
'POST stop-remote': async (id) => ({ ok: true, ...(await service.stopRemote(id)) }),
|
|
276
|
+
'POST fingerprint': async (id, req) => {
|
|
277
|
+
const body = await readJson(req);
|
|
278
|
+
await service.confirmFingerprint(id, {
|
|
279
|
+
accept: body.accept === true,
|
|
280
|
+
remember: body.remember === true,
|
|
281
|
+
sha256: typeof body.sha256 === 'string' ? body.sha256 : undefined,
|
|
282
|
+
});
|
|
283
|
+
return { ok: true };
|
|
284
|
+
},
|
|
285
|
+
'POST diagnose': async (id) => ({ ok: true, report: await service.diagnose(id) }),
|
|
286
|
+
'GET open': (id) => ({ ok: true, ...service.openInfo(id) }),
|
|
287
|
+
'POST activate': (id) => {
|
|
288
|
+
service.setActiveHost(id);
|
|
289
|
+
return { ok: true };
|
|
290
|
+
},
|
|
291
|
+
};
|
|
292
|
+
/** Resolve `/hosts/:id[/action]` to `{ id, run }`, or null for an unknown shape. */
|
|
293
|
+
function hostHandler(hostPath, method) {
|
|
294
|
+
const segments = hostPath.split('/').filter(Boolean);
|
|
295
|
+
if (segments[0] !== 'hosts' || segments.length < 2)
|
|
296
|
+
return null;
|
|
297
|
+
const key = segments[2] ? `${method} ${segments[2]}` : method;
|
|
298
|
+
if (!Object.hasOwn(HOST_ACTIONS, key))
|
|
299
|
+
return null;
|
|
300
|
+
let id;
|
|
301
|
+
try {
|
|
302
|
+
id = decodeURIComponent(segments[1]);
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
// A malformed escape (`/hosts/%E0%A4%A/activate`) is a client mistake, not an internal
|
|
306
|
+
// failure: answer 400 with a readable field error instead of leaking URIError as 500.
|
|
307
|
+
throw errors.invalidInput('id', {
|
|
308
|
+
zh: '主机 id 不是合法的 URL 编码。',
|
|
309
|
+
en: 'The host id is not valid URL encoding.',
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
return { id, run: HOST_ACTIONS[key] };
|
|
313
|
+
}
|
|
314
|
+
async function handler(req, res) {
|
|
315
|
+
try {
|
|
316
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
317
|
+
if (!url.pathname.startsWith(API_PREFIX)) {
|
|
318
|
+
sendJson(res, 404, {
|
|
319
|
+
ok: false,
|
|
320
|
+
error: toErrorView(errors.invalidInput('path', { zh: '未知 API 路径。', en: 'Unknown API path.' })),
|
|
321
|
+
});
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const path = url.pathname.slice(API_PREFIX.length) || '/';
|
|
325
|
+
const method = (req.method ?? 'GET').toUpperCase();
|
|
326
|
+
// `/health` stays the documented unauthenticated liveness probe (it carries no state), and
|
|
327
|
+
// still passes the Host/Origin fence below. Everything else passes DSH's own admission
|
|
328
|
+
// first, so a rebound page or an unauthenticated local caller cannot read state or change it.
|
|
329
|
+
const probe = path === '/health' && method === 'GET';
|
|
330
|
+
if (!probe) {
|
|
331
|
+
const rejection = admission(req);
|
|
332
|
+
if (rejection !== undefined) {
|
|
333
|
+
sendJson(res, rejection, admissionView(rejection));
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
if (probe) {
|
|
338
|
+
const trust = authorizeOrigin(req);
|
|
339
|
+
if (!trust.ok) {
|
|
340
|
+
sendJson(res, trust.status, { ok: false, error: trust.error });
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
sendJson(res, 200, ROUTES['GET /health']());
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
// SSE cannot carry the custom header. It already passed DSH's admission above; the fence
|
|
347
|
+
// here covers kernels without the Connection service, and browsers block a cross-origin
|
|
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.
|
|
350
|
+
const sse = sseRoute(path, method);
|
|
351
|
+
if (sse !== null) {
|
|
352
|
+
const originOnly = authorizeOrigin(req);
|
|
353
|
+
if (!originOnly.ok) {
|
|
354
|
+
sendJson(res, originOnly.status, { ok: false, error: originOnly.error });
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
await service.init();
|
|
358
|
+
if (sse === 'logs')
|
|
359
|
+
hub.handleLogs(req, res);
|
|
360
|
+
else
|
|
361
|
+
hub.handleState(req, res);
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const auth = authorize(req);
|
|
365
|
+
if (!auth.ok) {
|
|
366
|
+
sendJson(res, auth.status, { ok: false, error: auth.error });
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
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
|
+
const segments = path.split('/').filter(Boolean);
|
|
373
|
+
if (method === 'POST' && path === '/downloads') {
|
|
374
|
+
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
|
+
const job = await service.startRemoteDownload(body.hostId, body.path, {
|
|
378
|
+
destination: body.destination,
|
|
379
|
+
});
|
|
380
|
+
sendJson(res, 200, { ok: true, job });
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
if (segments[0] === 'downloads' && segments.length >= 2 && segments.length <= 3) {
|
|
384
|
+
let jobId = '';
|
|
385
|
+
try {
|
|
386
|
+
jobId = decodeURIComponent(segments[1]);
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
throw errors.invalidInput('id', {
|
|
390
|
+
zh: '下载任务 id 不是合法的 URL 编码。',
|
|
391
|
+
en: 'The download job id is not valid URL encoding.',
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
if (method === 'GET' && segments.length === 3 && segments[2] === 'status') {
|
|
395
|
+
sendJson(res, 200, { ok: true, job: await service.remoteDownloadStatus(jobId) });
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
if (method === 'DELETE' && segments.length === 2) {
|
|
399
|
+
await service.cancelRemoteDownload(jobId);
|
|
400
|
+
sendJson(res, 200, { ok: true });
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const routeKey = `${method} ${path}`;
|
|
405
|
+
if (Object.hasOwn(ROUTES, routeKey)) {
|
|
406
|
+
sendJson(res, 200, await ROUTES[routeKey](req, url));
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
const host = hostHandler(path, method);
|
|
410
|
+
if (host) {
|
|
411
|
+
sendJson(res, 200, await host.run(host.id, req));
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
sendJson(res, 404, {
|
|
415
|
+
ok: false,
|
|
416
|
+
error: toErrorView(errors.invalidInput('path', { zh: `未知路径 ${method} ${path}`, en: `Unknown path ${method} ${path}` })),
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
catch (error) {
|
|
420
|
+
const view = toErrorView(error);
|
|
421
|
+
const status = Number.isInteger(error?.httpStatus)
|
|
422
|
+
? error.httpStatus
|
|
423
|
+
: isRemoteGoError(error)
|
|
424
|
+
? statusForErrorCode(view.code)
|
|
425
|
+
: 500;
|
|
426
|
+
logger.error?.('[dsh-remote-go] API error:', error);
|
|
427
|
+
try {
|
|
428
|
+
sendJson(res, status, { ok: false, error: view });
|
|
429
|
+
}
|
|
430
|
+
catch {
|
|
431
|
+
// swallow-ok: the response is already gone; a failed write cannot be reported on it
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return {
|
|
436
|
+
handler,
|
|
437
|
+
dispose() {
|
|
438
|
+
// One entry point for the whole listener teardown: the hub owns both channel sets.
|
|
439
|
+
hub.dispose();
|
|
440
|
+
},
|
|
441
|
+
};
|
|
442
|
+
}
|