@aide-family/dsh-remote 0.0.0-stage → 0.6.2
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/LICENSE +21 -0
- package/README.md +793 -2
- package/bin/dsh-remote-terminal +82 -0
- package/cordis.patch.yml +3 -0
- package/docs/TERMINAL_ACTIONS.md +39 -0
- package/docs/assets/host-audit.png +0 -0
- package/docs/assets/host-manager.png +0 -0
- package/docs/assets/live-terminal.png +0 -0
- package/docs/assets/remote-ops.png +0 -0
- package/docs/assets/remote-terminal.png +0 -0
- package/docs/icon.svg +11 -0
- package/lib/api-helpers.js +325 -0
- package/lib/api.js +715 -0
- package/lib/approval.js +238 -0
- package/lib/audit.js +224 -0
- package/lib/client.js +4919 -0
- package/lib/config.js +762 -0
- package/lib/connection-profile.js +65 -0
- package/lib/host-registry.js +703 -0
- package/lib/host-store.js +139 -0
- package/lib/hosts.js +442 -0
- package/lib/index.js +419 -0
- package/lib/live-stream.js +121 -0
- package/lib/live.js +245 -0
- package/lib/policy/argv.js +77 -0
- package/lib/policy/command-guard.js +404 -0
- package/lib/policy/docker.js +140 -0
- package/lib/policy/index.js +21 -0
- package/lib/policy/inspection.js +111 -0
- package/lib/policy/kubectl.js +128 -0
- package/lib/policy/shell-command.js +525 -0
- package/lib/policy/shell-wrappers.js +143 -0
- package/lib/policy/ssh.js +53 -0
- package/lib/policy/sudo.js +38 -0
- package/lib/policy/systemctl.js +22 -0
- package/lib/policy/types.js +12 -0
- package/lib/prompt.js +29 -0
- package/lib/render.js +442 -0
- package/lib/runtime-deps.js +50 -0
- package/lib/ssh/auth.js +256 -0
- package/lib/ssh/connection.js +504 -0
- package/lib/ssh/errors.js +209 -0
- package/lib/ssh/exec.js +394 -0
- package/lib/ssh/known-hosts.js +313 -0
- package/lib/ssh/pty.js +472 -0
- package/lib/ssh/sftp.js +589 -0
- package/lib/ssh/transport.js +801 -0
- package/lib/ssh-config.js +395 -0
- package/lib/terminal/bridge.cjs +305 -0
- package/lib/terminal/connection-login.js +188 -0
- package/lib/terminal/manager.js +656 -0
- package/lib/terminal/node-launcher.js +211 -0
- package/lib/terminal/pty-session.js +673 -0
- package/lib/terminal/relay-socket.js +605 -0
- package/lib/terminal/relay.js +905 -0
- package/lib/terminal/scrollback.js +588 -0
- package/lib/terminal/tools.js +532 -0
- package/lib/tools.js +751 -0
- package/package.json +90 -4
package/lib/api.js
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host HTTP API behind the browser "Remote Ops" management page.
|
|
3
|
+
*
|
|
4
|
+
* Registered by `lib/index.js` on the DSH web server under
|
|
5
|
+
* `/dsh-remote/api` (prefix route). Every request must pass the Host connection
|
|
6
|
+
* fence (the same Host/Origin + browser-cookie check `/api` uses) and is
|
|
7
|
+
* answered from the plugin's own services:
|
|
8
|
+
*
|
|
9
|
+
* POST { method: "overview" } -> hosts / sessions / audit / terminal
|
|
10
|
+
* POST { method: "host.test", name } -> read-only connectivity probe
|
|
11
|
+
* POST { method: "host.create", host } -> persist a managed host
|
|
12
|
+
* POST { method: "host.update", name, host } -> update a managed host
|
|
13
|
+
* POST { method: "host.delete", name } -> remove a managed host
|
|
14
|
+
* POST { method: "audit.list", host?, limit?, offset?, full? } -> audit page
|
|
15
|
+
* POST { method: "terminal.open", name, sessionId? } -> open/reuse a user SSH PTY
|
|
16
|
+
* POST { method: "terminal.list", sessionId? } -> user terminal sessions
|
|
17
|
+
* POST { method: "terminal.close", sessionKey } -> close a user terminal session
|
|
18
|
+
* POST { method: "terminal.trace", stage, sessionId?, detail? } -> bounded client trace
|
|
19
|
+
* POST { method: "session.read", sessionId, offset?, count? } -> scrollback page
|
|
20
|
+
* POST { method: "session.close", sessionId } -> close a shell session
|
|
21
|
+
* POST { method: "audit.clear" } -> clear the audit trail
|
|
22
|
+
* POST { method: "live.emit", ... } -> dev-only live event injector
|
|
23
|
+
*
|
|
24
|
+
* Answers are `{ ok: true, result }` or `{ ok: false, error: { code, message } }`.
|
|
25
|
+
* The route is never registered without a web server (headless CLI runs have no
|
|
26
|
+
* management page), and it is fenced fail-closed when a connection service is
|
|
27
|
+
* mounted.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { createRequire } from "node:module";
|
|
31
|
+
import { homedir } from "node:os";
|
|
32
|
+
import { join } from "node:path";
|
|
33
|
+
|
|
34
|
+
import {
|
|
35
|
+
ApiError,
|
|
36
|
+
MAX_BODY_BYTES,
|
|
37
|
+
appendBoundedTraceLine,
|
|
38
|
+
authHintFor,
|
|
39
|
+
fail,
|
|
40
|
+
formatTarget,
|
|
41
|
+
isManaged,
|
|
42
|
+
mapManagerError,
|
|
43
|
+
mapTerminalError,
|
|
44
|
+
messageOf,
|
|
45
|
+
optionalAuditFull,
|
|
46
|
+
optionalAuditHost,
|
|
47
|
+
optionalAuditInteger,
|
|
48
|
+
optionalPositiveInt,
|
|
49
|
+
optionalTerminalSessionId,
|
|
50
|
+
readJsonBody,
|
|
51
|
+
remoteHostOf,
|
|
52
|
+
requireHostInput,
|
|
53
|
+
requireHostName,
|
|
54
|
+
requireString,
|
|
55
|
+
requireTerminalArg,
|
|
56
|
+
safeFlag,
|
|
57
|
+
writeJson,
|
|
58
|
+
} from "./api-helpers.js";
|
|
59
|
+
|
|
60
|
+
const requirePackage = createRequire(import.meta.url);
|
|
61
|
+
const VERSION = (() => {
|
|
62
|
+
try {
|
|
63
|
+
return requirePackage("../package.json").version ?? "0.0.0";
|
|
64
|
+
} catch {
|
|
65
|
+
return "0.0.0";
|
|
66
|
+
}
|
|
67
|
+
})();
|
|
68
|
+
|
|
69
|
+
/** Prefix registered on the DSH web server. */
|
|
70
|
+
export const API_PREFIX = "/dsh-remote/api";
|
|
71
|
+
/** Bound for a management connection test. */
|
|
72
|
+
const HOST_TEST_TIMEOUT_MS = 12_000;
|
|
73
|
+
const HOST_TEST_MAX_BYTES = 8_192;
|
|
74
|
+
/** Page cap for `audit.list` (the audit ring is bounded anyway). */
|
|
75
|
+
const AUDIT_MAX_LIMIT = 1_000;
|
|
76
|
+
/** Number of audit entries the lightweight `overview` carries (v0.5.1). */
|
|
77
|
+
const OVERVIEW_AUDIT_LIMIT = 20;
|
|
78
|
+
/** Stage shape accepted by `terminal.trace` (client diagnostics). */
|
|
79
|
+
const TRACE_STAGE_RE = /^[\w.:-]{1,64}$/u;
|
|
80
|
+
/** Maximum accepted `terminal.trace` detail length. */
|
|
81
|
+
const TRACE_DETAIL_MAX_CHARS = 2_000;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* @param {object} deps
|
|
85
|
+
* @param {object} deps.ctx Cordis context (for the optional connection fence).
|
|
86
|
+
* @param {object} deps.config Normalized plugin config.
|
|
87
|
+
* @param {object} deps.hosts Host store (`lib/host-store.js`).
|
|
88
|
+
* @param {object} deps.transport SSH transport.
|
|
89
|
+
* @param {object} [deps.manager] Shell manager (when terminal support is enabled).
|
|
90
|
+
* @param {object} deps.audit Audit log (`lib/audit.js`).
|
|
91
|
+
* @param {object} [deps.hub] Live command hub (`lib/live.js`), for the dev injector.
|
|
92
|
+
* @param {object} [deps.registry] Managed host registry (`lib/host-registry.js`).
|
|
93
|
+
* @param {object} [deps.relay] User terminal relay or a facade over it
|
|
94
|
+
* (`{ start?, open, list, close, socketPath, available? }`).
|
|
95
|
+
* @param {object} [deps.hostStore] Host store exposing `invalidate()`; defaults
|
|
96
|
+
* to `hosts` (same object in the plugin wiring).
|
|
97
|
+
* @param {string} [deps.debugLogPath] bounded client-trace file
|
|
98
|
+
* (`$DSH_HOME/remote/terminal-debug.log`); derived from `$DSH_HOME` when omitted.
|
|
99
|
+
* @param {{ warn?: (m: string) => void }} [deps.logger]
|
|
100
|
+
* @param {() => string} [deps.workspaceRoot] Session-independent project dir hint.
|
|
101
|
+
* @returns {(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => Promise<void>}
|
|
102
|
+
*/
|
|
103
|
+
export function createManagementApi({
|
|
104
|
+
ctx,
|
|
105
|
+
config,
|
|
106
|
+
hosts,
|
|
107
|
+
transport,
|
|
108
|
+
manager,
|
|
109
|
+
audit,
|
|
110
|
+
hub,
|
|
111
|
+
registry,
|
|
112
|
+
relay,
|
|
113
|
+
hostStore,
|
|
114
|
+
debugLogPath,
|
|
115
|
+
logger,
|
|
116
|
+
}) {
|
|
117
|
+
// The host store is the object that owns the discovery cache. Older
|
|
118
|
+
// compositions/tests pass only `hosts`; both are accepted.
|
|
119
|
+
const store = hostStore ?? hosts;
|
|
120
|
+
const traceLogPath =
|
|
121
|
+
typeof debugLogPath === "string" && debugLogPath.trim().length > 0
|
|
122
|
+
? debugLogPath.trim()
|
|
123
|
+
: join(
|
|
124
|
+
typeof process.env.DSH_HOME === "string" && process.env.DSH_HOME.trim().length > 0
|
|
125
|
+
? process.env.DSH_HOME.trim()
|
|
126
|
+
: join(homedir(), ".dsh"),
|
|
127
|
+
"remote",
|
|
128
|
+
"terminal-debug.log",
|
|
129
|
+
);
|
|
130
|
+
const warn = (message) => {
|
|
131
|
+
try {
|
|
132
|
+
logger?.warn?.(message);
|
|
133
|
+
} catch {
|
|
134
|
+
// ignore
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
async function dispatch(body, signal) {
|
|
139
|
+
const method = typeof body?.method === "string" ? body.method : "";
|
|
140
|
+
switch (method) {
|
|
141
|
+
case "overview":
|
|
142
|
+
return overview();
|
|
143
|
+
case "host.test":
|
|
144
|
+
return hostTest(requireString(body.name, "name"));
|
|
145
|
+
case "auth.password":
|
|
146
|
+
return authenticatePassword(body, signal);
|
|
147
|
+
case "host.create":
|
|
148
|
+
return hostCreate(body);
|
|
149
|
+
case "host.update":
|
|
150
|
+
return hostUpdate(body);
|
|
151
|
+
case "host.delete":
|
|
152
|
+
return hostDelete(body);
|
|
153
|
+
case "audit.list":
|
|
154
|
+
return auditList(body);
|
|
155
|
+
case "terminal.open":
|
|
156
|
+
return terminalOpen(body, signal);
|
|
157
|
+
case "terminal.list":
|
|
158
|
+
return terminalList(body);
|
|
159
|
+
case "terminal.close":
|
|
160
|
+
return terminalClose(body);
|
|
161
|
+
case "terminal.trace":
|
|
162
|
+
return terminalTrace(body);
|
|
163
|
+
case "session.read":
|
|
164
|
+
return sessionRead(
|
|
165
|
+
requireString(body.sessionId, "sessionId"),
|
|
166
|
+
optionalPositiveInt(body.offset, "offset"),
|
|
167
|
+
optionalPositiveInt(body.count, "count"),
|
|
168
|
+
);
|
|
169
|
+
case "session.close":
|
|
170
|
+
return sessionClose(requireString(body.sessionId, "sessionId"));
|
|
171
|
+
case "audit.clear":
|
|
172
|
+
return audit.clear();
|
|
173
|
+
case "live.emit":
|
|
174
|
+
return emitLiveDev(body);
|
|
175
|
+
default:
|
|
176
|
+
throw new ApiError("UNKNOWN_METHOD", `unknown management method ${JSON.stringify(method)}`, 404);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function overview() {
|
|
181
|
+
let listed = [];
|
|
182
|
+
try {
|
|
183
|
+
listed = await hosts.list({ refresh: true });
|
|
184
|
+
} catch (error) {
|
|
185
|
+
warn(`dsh-remote: management overview could not load hosts: ${messageOf(error)}`);
|
|
186
|
+
}
|
|
187
|
+
const hostViews = listed.map((host) => hostView(host));
|
|
188
|
+
const sessions = typeof manager?.adminList === "function" ? manager.adminList() : [];
|
|
189
|
+
return {
|
|
190
|
+
version: VERSION,
|
|
191
|
+
policy: config.policy,
|
|
192
|
+
allowHosts: config.allowHosts,
|
|
193
|
+
readonlyHosts: config.readonlyHosts,
|
|
194
|
+
sshConfigPath: config.sshConfigPath,
|
|
195
|
+
includeSshConfig: config.includeSshConfig,
|
|
196
|
+
terminalEnabled: config.terminalEnabled,
|
|
197
|
+
counts: { hosts: hostViews.length, sessions: sessions.length, audit: audit.size },
|
|
198
|
+
hosts: hostViews,
|
|
199
|
+
sessions: sessions.map((session) => ({
|
|
200
|
+
sessionId: session.sessionId,
|
|
201
|
+
host: session.host,
|
|
202
|
+
name: session.name ?? null,
|
|
203
|
+
status: session.status,
|
|
204
|
+
createdAt: session.createdAt ?? null,
|
|
205
|
+
})),
|
|
206
|
+
// v0.5.1: the overview only carries the newest 20 operations; the audit
|
|
207
|
+
// modal/export uses `audit.list` with its own (full) page.
|
|
208
|
+
audit: audit.list({ limit: OVERVIEW_AUDIT_LIMIT }),
|
|
209
|
+
live: {
|
|
210
|
+
enabled: config.liveTerminal !== false,
|
|
211
|
+
autoOpen: config.autoOpenLiveTerminal !== false,
|
|
212
|
+
devEvents: config.devLiveEvents === true,
|
|
213
|
+
},
|
|
214
|
+
terminal: await terminalOverview(),
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* One HostView for the browser: the resolved connection coordinates plus the
|
|
220
|
+
* policy flags and the v0.5 `managed` marker (editable/deletable on the page).
|
|
221
|
+
*
|
|
222
|
+
* @param {any} host
|
|
223
|
+
* @returns {object}
|
|
224
|
+
*/
|
|
225
|
+
function hostView(host) {
|
|
226
|
+
return {
|
|
227
|
+
name: host.name,
|
|
228
|
+
host: host.host,
|
|
229
|
+
target: formatTarget(host),
|
|
230
|
+
port: host.port ?? 22,
|
|
231
|
+
username: host.username ?? null,
|
|
232
|
+
source: host.source,
|
|
233
|
+
managed: isManaged(host),
|
|
234
|
+
description: host.description ?? null,
|
|
235
|
+
tags: host.tags ?? [],
|
|
236
|
+
// Non-secret connection references, exposed so the host edit form can
|
|
237
|
+
// prefill them (the registry update is a full replace). Never values.
|
|
238
|
+
identityFile: typeof host.identityFile === "string" ? host.identityFile : null,
|
|
239
|
+
passwordEnv: typeof host.passwordEnv === "string" ? host.passwordEnv : null,
|
|
240
|
+
passphraseEnv: typeof host.passphraseEnv === "string" ? host.passphraseEnv : null,
|
|
241
|
+
proxyJump: Array.isArray(host.proxyJump) ? host.proxyJump : [],
|
|
242
|
+
readonly: safeFlag(() => hosts.isReadonly(host), false),
|
|
243
|
+
allowed: safeFlag(() => hosts.isAllowed(host), true),
|
|
244
|
+
authHint: authHintFor(host),
|
|
245
|
+
...(host.viaHost ? { viaHost: host.viaHost, actions: host.actions?.map((action) => ({ ...action })) ?? [], terminalOnly: true } : {}),
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* v0.5 terminal surface for the panel: whether user terminals are enabled and
|
|
251
|
+
* the relay is listening, the socket the bridge connects to, and the live
|
|
252
|
+
* session views. The relay start is retried here (idempotent) so the first
|
|
253
|
+
* page load already sees a listening terminal when the socket comes up late.
|
|
254
|
+
*
|
|
255
|
+
* @returns {Promise<{enabled: boolean, available: boolean, socketPath: string | null, sessions: object[]}>}
|
|
256
|
+
*/
|
|
257
|
+
async function terminalOverview() {
|
|
258
|
+
const enabled = config.userTerminal !== false && config.terminalEnabled !== false;
|
|
259
|
+
if (relay === undefined || relay === null) {
|
|
260
|
+
return { enabled, available: false, socketPath: null, sessions: [] };
|
|
261
|
+
}
|
|
262
|
+
if (relay.available === false && typeof relay.start === "function") {
|
|
263
|
+
try {
|
|
264
|
+
await relay.start();
|
|
265
|
+
} catch (error) {
|
|
266
|
+
warn(`dsh-remote: interactive terminal is unavailable: ${messageOf(error)}`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
let sessions = [];
|
|
270
|
+
try {
|
|
271
|
+
const listed = relay.list({});
|
|
272
|
+
sessions = Array.isArray(listed) ? listed : [];
|
|
273
|
+
} catch (error) {
|
|
274
|
+
warn(`dsh-remote: could not list user terminal sessions: ${messageOf(error)}`);
|
|
275
|
+
}
|
|
276
|
+
return {
|
|
277
|
+
enabled,
|
|
278
|
+
available: relay.available !== false,
|
|
279
|
+
socketPath: typeof relay.socketPath === "string" ? relay.socketPath : null,
|
|
280
|
+
sessions,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Development-only live event injector used by the browser verification loop.
|
|
286
|
+
* It is reachable only when `devLiveEvents: true` is explicitly configured.
|
|
287
|
+
*
|
|
288
|
+
* @param {any} body
|
|
289
|
+
*/
|
|
290
|
+
async function emitLiveDev(body) {
|
|
291
|
+
if (hub === undefined || hub === null) {
|
|
292
|
+
throw new ApiError("METHOD_UNAVAILABLE", "the live terminal is disabled in this composition", 409);
|
|
293
|
+
}
|
|
294
|
+
if (config.devLiveEvents !== true) {
|
|
295
|
+
throw new ApiError("DEV_EVENTS_DISABLED", "live.emit is only available with devLiveEvents: true", 403);
|
|
296
|
+
}
|
|
297
|
+
const command = hub.begin({
|
|
298
|
+
sessionId: typeof body.sessionId === "string" ? body.sessionId : null,
|
|
299
|
+
tool: typeof body.tool === "string" ? body.tool : "remote_exec",
|
|
300
|
+
host: typeof body.host === "string" ? body.host : "testbox",
|
|
301
|
+
command: typeof body.command === "string" ? body.command : "echo dev-live-event",
|
|
302
|
+
kind: typeof body.kind === "string" ? body.kind : "exec",
|
|
303
|
+
});
|
|
304
|
+
const lines = Array.isArray(body.lines) ? body.lines : ["dev live output line 1", "dev live output line 2"];
|
|
305
|
+
for (const line of lines) {
|
|
306
|
+
command.output("stdout", `${String(line)}\n`);
|
|
307
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
308
|
+
}
|
|
309
|
+
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
310
|
+
command.end({ code: typeof body.code === "number" ? body.code : 0, durationMs: 900 });
|
|
311
|
+
return { id: command.id, emitted: lines.length };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function hostTest(name) {
|
|
315
|
+
let host;
|
|
316
|
+
try {
|
|
317
|
+
host = await hosts.find(name);
|
|
318
|
+
} catch (error) {
|
|
319
|
+
throw new ApiError("UNKNOWN_HOST", messageOf(error), 404);
|
|
320
|
+
}
|
|
321
|
+
if (!hosts.isAllowed(host)) {
|
|
322
|
+
throw new ApiError("HOST_NOT_ALLOWED", `Host ${host.name} is not allowed by the allowHosts policy`, 403);
|
|
323
|
+
}
|
|
324
|
+
if (host.viaHost) throw new ApiError("TERMINAL_ONLY_HOST", `Host ${host.name} is a terminal-only cluster shortcut. Connect its shared terminal to verify login; a probe would only test ${host.viaHost}.`, 409);
|
|
325
|
+
const signal = AbortSignal.timeout(HOST_TEST_TIMEOUT_MS);
|
|
326
|
+
let reachability;
|
|
327
|
+
try {
|
|
328
|
+
reachability = await transport.test(host, { signal, timeoutMs: HOST_TEST_TIMEOUT_MS });
|
|
329
|
+
} catch (error) {
|
|
330
|
+
reachability = { ok: false, latencyMs: 0, error: messageOf(error) };
|
|
331
|
+
}
|
|
332
|
+
if (reachability.ok !== true) {
|
|
333
|
+
return { name: host.name, ok: false, latencyMs: reachability.latencyMs ?? 0, error: reachability.error ?? "connection failed" };
|
|
334
|
+
}
|
|
335
|
+
try {
|
|
336
|
+
const result = await transport.exec(host, {
|
|
337
|
+
command: "uname -srm 2>/dev/null; hostname",
|
|
338
|
+
timeoutMs: HOST_TEST_TIMEOUT_MS,
|
|
339
|
+
maxBytes: HOST_TEST_MAX_BYTES,
|
|
340
|
+
signal,
|
|
341
|
+
});
|
|
342
|
+
return {
|
|
343
|
+
name: host.name,
|
|
344
|
+
ok: result.code === 0,
|
|
345
|
+
latencyMs: reachability.latencyMs ?? 0,
|
|
346
|
+
output: String(result.stdout ?? "").trim(),
|
|
347
|
+
};
|
|
348
|
+
} catch (error) {
|
|
349
|
+
return { name: host.name, ok: false, latencyMs: reachability.latencyMs ?? 0, error: messageOf(error) };
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// --- v0.5 managed hosts (host.create / host.update / host.delete) ------
|
|
354
|
+
|
|
355
|
+
/** @returns {any} */
|
|
356
|
+
function requireRegistry() {
|
|
357
|
+
if (registry === undefined || registry === null) {
|
|
358
|
+
throw fail("HOST_NOT_MANAGED", "managed hosts are not available in this composition");
|
|
359
|
+
}
|
|
360
|
+
return registry;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
async function hostCreate(body) {
|
|
364
|
+
const managed = requireRegistry();
|
|
365
|
+
const input = requireHostInput(body, "host.create");
|
|
366
|
+
let record;
|
|
367
|
+
try {
|
|
368
|
+
record = await managed.create(input);
|
|
369
|
+
} catch (error) {
|
|
370
|
+
throw await mapHostError(error, input?.name);
|
|
371
|
+
}
|
|
372
|
+
return { host: await hostViewAfterMutation(record) };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async function hostUpdate(body) {
|
|
376
|
+
const managed = requireRegistry();
|
|
377
|
+
const name = requireHostName(body?.name);
|
|
378
|
+
const input = requireHostInput(body, "host.update");
|
|
379
|
+
let record;
|
|
380
|
+
try {
|
|
381
|
+
record = await managed.update(name, input);
|
|
382
|
+
} catch (error) {
|
|
383
|
+
throw await mapHostError(error, name);
|
|
384
|
+
}
|
|
385
|
+
return { host: await hostViewAfterMutation(record) };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async function hostDelete(body) {
|
|
389
|
+
const managed = requireRegistry();
|
|
390
|
+
const name = requireHostName(body?.name);
|
|
391
|
+
try {
|
|
392
|
+
const deleted = await managed.delete(name);
|
|
393
|
+
if (deleted === false) {
|
|
394
|
+
const error = new Error(`managed host ${JSON.stringify(name)} does not exist`);
|
|
395
|
+
error.code = "HOST_NOT_FOUND";
|
|
396
|
+
throw error;
|
|
397
|
+
}
|
|
398
|
+
} catch (error) {
|
|
399
|
+
throw await mapHostError(error, name);
|
|
400
|
+
}
|
|
401
|
+
await reloadHosts();
|
|
402
|
+
return { deleted: true };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Build the reply HostView from the merged discovery list after a registry
|
|
407
|
+
* mutation, so the page sees exactly what a tool call sees (source/flags).
|
|
408
|
+
* Falls back to the raw registry record if discovery hiccups.
|
|
409
|
+
*
|
|
410
|
+
* @param {any} record
|
|
411
|
+
*/
|
|
412
|
+
async function hostViewAfterMutation(record) {
|
|
413
|
+
const name = String(record?.name ?? "");
|
|
414
|
+
const listed = await reloadHosts();
|
|
415
|
+
const merged = listed.find((host) => String(host.name).toLowerCase() === name.toLowerCase());
|
|
416
|
+
return hostView(merged ?? remoteHostOf(record));
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** Invalidate the host-store cache so the next list/find reloads the registry. */
|
|
420
|
+
async function reloadHosts() {
|
|
421
|
+
try {
|
|
422
|
+
if (typeof store?.invalidate === "function") store.invalidate();
|
|
423
|
+
} catch (error) {
|
|
424
|
+
warn(`dsh-remote: host cache invalidation failed: ${messageOf(error)}`);
|
|
425
|
+
}
|
|
426
|
+
try {
|
|
427
|
+
return await hosts.list({ refresh: true });
|
|
428
|
+
} catch (error) {
|
|
429
|
+
warn(`dsh-remote: host reload after a registry mutation failed: ${messageOf(error)}`);
|
|
430
|
+
return [];
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Map a registry error onto the documented host API error codes. A name that
|
|
436
|
+
* exists in the merged host list but is not registry-managed is reported as
|
|
437
|
+
* HOST_NOT_MANAGED rather than HOST_NOT_FOUND (the page can then explain that
|
|
438
|
+
* ~/.ssh/config hosts are read-only here).
|
|
439
|
+
*
|
|
440
|
+
* @param {unknown} error
|
|
441
|
+
* @param {unknown} name
|
|
442
|
+
* @returns {Promise<ApiError>}
|
|
443
|
+
*/
|
|
444
|
+
async function mapHostError(error, name) {
|
|
445
|
+
if (error instanceof ApiError) return error;
|
|
446
|
+
const code = typeof (/** @type {any} */ (error)?.code) === "string" ? /** @type {any} */ (error).code : "";
|
|
447
|
+
if (code === "HOST_EXISTS") return fail("HOST_EXISTS", messageOf(error));
|
|
448
|
+
if (code === "HOST_DISALLOWED") return fail("HOST_DISALLOWED", messageOf(error));
|
|
449
|
+
if (code === "HOST_NOT_MANAGED") return fail("HOST_NOT_MANAGED", messageOf(error));
|
|
450
|
+
if (code === "HOST_NOT_FOUND" || code === "UNKNOWN_HOST") {
|
|
451
|
+
const existing = await findHostQuietly(name);
|
|
452
|
+
if (existing !== undefined && !isManaged(existing)) {
|
|
453
|
+
return fail(
|
|
454
|
+
"HOST_NOT_MANAGED",
|
|
455
|
+
`host ${JSON.stringify(String(name ?? ""))} is not managed by dsh-remote; ` +
|
|
456
|
+
"only hosts added through the host manager can be edited or deleted",
|
|
457
|
+
);
|
|
458
|
+
}
|
|
459
|
+
return fail("HOST_NOT_FOUND", messageOf(error));
|
|
460
|
+
}
|
|
461
|
+
return fail("HOST_INVALID", messageOf(error));
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** @param {unknown} name */
|
|
465
|
+
async function findHostQuietly(name) {
|
|
466
|
+
if (typeof name !== "string" || name.trim() === "") return undefined;
|
|
467
|
+
try {
|
|
468
|
+
return await hosts.find(name);
|
|
469
|
+
} catch {
|
|
470
|
+
return undefined;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// --- v0.5 host-filtered audit (audit.list) ------------------------------
|
|
475
|
+
|
|
476
|
+
async function auditList(body) {
|
|
477
|
+
const host = optionalAuditHost(body?.host);
|
|
478
|
+
const limit = optionalAuditInteger(body?.limit, "limit", 1, AUDIT_MAX_LIMIT);
|
|
479
|
+
const offset = optionalAuditInteger(body?.offset, "offset", 0, Number.MAX_SAFE_INTEGER);
|
|
480
|
+
const full = optionalAuditFull(body?.full);
|
|
481
|
+
const filter = host === undefined ? {} : { host };
|
|
482
|
+
let entries;
|
|
483
|
+
let total;
|
|
484
|
+
try {
|
|
485
|
+
entries = audit.list({
|
|
486
|
+
...filter,
|
|
487
|
+
...(limit === undefined ? {} : { limit }),
|
|
488
|
+
...(offset === undefined ? {} : { offset }),
|
|
489
|
+
...(full === undefined ? {} : { full }),
|
|
490
|
+
});
|
|
491
|
+
total =
|
|
492
|
+
typeof audit.count === "function"
|
|
493
|
+
? audit.count(filter)
|
|
494
|
+
: Array.isArray(entries)
|
|
495
|
+
? entries.length
|
|
496
|
+
: 0;
|
|
497
|
+
} catch (error) {
|
|
498
|
+
throw fail("AUDIT_INVALID", messageOf(error));
|
|
499
|
+
}
|
|
500
|
+
return {
|
|
501
|
+
host: host ?? null,
|
|
502
|
+
total: Number.isSafeInteger(total) && total >= 0 ? total : 0,
|
|
503
|
+
entries: Array.isArray(entries) ? entries : [],
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// --- v0.5 interactive user terminal (terminal.*) ------------------------
|
|
508
|
+
|
|
509
|
+
/** @returns {any} */
|
|
510
|
+
function requireTerminal() {
|
|
511
|
+
if (relay === undefined || relay === null) {
|
|
512
|
+
throw fail("TERMINAL_DISABLED", "the interactive user terminal is not enabled in this composition");
|
|
513
|
+
}
|
|
514
|
+
return relay;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* The relay is started best-effort by the plugin wiring; a retry here recovers
|
|
519
|
+
* from a transient socket error without ever breaking the request path.
|
|
520
|
+
*
|
|
521
|
+
* @param {any} terminal
|
|
522
|
+
*/
|
|
523
|
+
async function ensureRelayStarted(terminal) {
|
|
524
|
+
if (typeof terminal.start !== "function") return;
|
|
525
|
+
try {
|
|
526
|
+
await terminal.start();
|
|
527
|
+
} catch (error) {
|
|
528
|
+
throw fail("TERMINAL_ERROR", `the terminal relay could not start: ${messageOf(error)}`);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// Human credential entry only; no Agent tool, audit payload, or disk storage.
|
|
533
|
+
async function authenticatePassword(body, signal) {
|
|
534
|
+
const name = requireHostName(body?.name);
|
|
535
|
+
if (typeof body?.password !== "string" || body.password.length === 0 || body.password.length > 4096) {
|
|
536
|
+
throw new ApiError("INVALID_ARGUMENT", "password must be a non-empty string of at most 4096 characters");
|
|
537
|
+
}
|
|
538
|
+
const host = await findHostQuietly(name);
|
|
539
|
+
if (!host) throw fail("HOST_NOT_FOUND", "host not found");
|
|
540
|
+
if (!hosts.isAllowed(host)) throw fail("HOST_DISALLOWED", "host is not allowed by allowHosts");
|
|
541
|
+
if (typeof transport?.authenticatePassword !== "function") {
|
|
542
|
+
throw fail("AUTH", "password login is not available in this composition");
|
|
543
|
+
}
|
|
544
|
+
try {
|
|
545
|
+
await transport.authenticatePassword(host, body.password, { signal });
|
|
546
|
+
return { authenticated: true, name: host.name };
|
|
547
|
+
} catch (error) {
|
|
548
|
+
// Never serialize a server-controlled message on a secret-bearing request.
|
|
549
|
+
if (error?.code === "HOST_KEY") throw fail("HOST_KEY", "SSH host key verification failed; check the trusted host key before retrying");
|
|
550
|
+
throw fail("AUTH", "SSH password authentication failed; verify the password or authentication method");
|
|
551
|
+
} finally {
|
|
552
|
+
delete body.password;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
async function terminalOpen(body, signal) {
|
|
557
|
+
const terminal = requireTerminal();
|
|
558
|
+
const name = requireTerminalArg(body?.name, "name");
|
|
559
|
+
const sessionId = optionalTerminalSessionId(body?.sessionId);
|
|
560
|
+
await ensureRelayStarted(terminal);
|
|
561
|
+
let opened;
|
|
562
|
+
try {
|
|
563
|
+
opened = await terminal.open({
|
|
564
|
+
hostName: name,
|
|
565
|
+
...(signal ? { signal } : {}),
|
|
566
|
+
...(sessionId === undefined ? {} : { sessionId }),
|
|
567
|
+
});
|
|
568
|
+
} catch (error) {
|
|
569
|
+
throw mapTerminalError(error);
|
|
570
|
+
}
|
|
571
|
+
if (opened === null || typeof opened !== "object" || opened.session === undefined) {
|
|
572
|
+
throw fail("TERMINAL_ERROR", "the terminal relay did not return a session");
|
|
573
|
+
}
|
|
574
|
+
return { shell: opened.shell, session: opened.session };
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
async function terminalList(body) {
|
|
578
|
+
const terminal = requireTerminal();
|
|
579
|
+
const sessionId = optionalTerminalSessionId(body?.sessionId);
|
|
580
|
+
let sessions;
|
|
581
|
+
try {
|
|
582
|
+
sessions = terminal.list(sessionId === undefined ? {} : { sessionId });
|
|
583
|
+
} catch (error) {
|
|
584
|
+
throw mapTerminalError(error);
|
|
585
|
+
}
|
|
586
|
+
return { sessions: Array.isArray(sessions) ? sessions : [] };
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* `terminal.trace` — fire-and-forget client diagnostics. The client records
|
|
591
|
+
* the tab/write/attach/timeout stages so a failed attach is diagnosable from
|
|
592
|
+
* disk; the line never enters the audit ring and I/O never fails the caller.
|
|
593
|
+
*
|
|
594
|
+
* @param {any} body
|
|
595
|
+
* @returns {{ ok: true }}
|
|
596
|
+
*/
|
|
597
|
+
function terminalTrace(body) {
|
|
598
|
+
const stage = typeof body?.stage === "string" ? body.stage : "";
|
|
599
|
+
if (!TRACE_STAGE_RE.test(stage)) {
|
|
600
|
+
throw new ApiError(
|
|
601
|
+
"INVALID_ARGUMENT",
|
|
602
|
+
"stage must be 1-64 characters of letters, digits, '_', '.', ':' or '-'",
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
const rawDetail = body?.detail;
|
|
606
|
+
const detail = rawDetail === undefined || rawDetail === null ? "" : String(rawDetail);
|
|
607
|
+
if (detail.length > TRACE_DETAIL_MAX_CHARS) {
|
|
608
|
+
throw new ApiError("INVALID_ARGUMENT", `detail must be at most ${TRACE_DETAIL_MAX_CHARS} characters`);
|
|
609
|
+
}
|
|
610
|
+
const sessionId = optionalTerminalSessionId(body?.sessionId);
|
|
611
|
+
// Best effort: a read-only/absent debug path never fails the action.
|
|
612
|
+
appendBoundedTraceLine(
|
|
613
|
+
traceLogPath,
|
|
614
|
+
JSON.stringify({ time: Date.now(), stage, sessionId: sessionId ?? null, detail }),
|
|
615
|
+
);
|
|
616
|
+
return { ok: true };
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
async function terminalClose(body) {
|
|
620
|
+
const terminal = requireTerminal();
|
|
621
|
+
const sessionKey = requireTerminalArg(body?.sessionKey, "sessionKey");
|
|
622
|
+
let closed;
|
|
623
|
+
try {
|
|
624
|
+
closed = await terminal.close(sessionKey);
|
|
625
|
+
} catch (error) {
|
|
626
|
+
throw mapTerminalError(error);
|
|
627
|
+
}
|
|
628
|
+
if (closed === false) {
|
|
629
|
+
throw fail("TERMINAL_NOT_FOUND", `no user terminal session ${JSON.stringify(sessionKey)}`);
|
|
630
|
+
}
|
|
631
|
+
return { closed: true };
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
async function sessionRead(sessionId, offset, count) {
|
|
635
|
+
if (typeof manager?.adminRead !== "function") {
|
|
636
|
+
throw new ApiError("METHOD_UNAVAILABLE", "remote shell sessions are not enabled in this composition", 409);
|
|
637
|
+
}
|
|
638
|
+
try {
|
|
639
|
+
const page = manager.adminRead({ sessionId, ...(offset === undefined ? {} : { offset }), ...(count === undefined ? {} : { count }) });
|
|
640
|
+
const session = typeof manager.adminGet === "function" ? manager.adminGet(sessionId) : undefined;
|
|
641
|
+
return {
|
|
642
|
+
sessionId,
|
|
643
|
+
host: session?.host ?? page.host ?? "—",
|
|
644
|
+
status: session?.status ?? null,
|
|
645
|
+
text: page.text ?? "",
|
|
646
|
+
totalLines: page.totalLines ?? 0,
|
|
647
|
+
lineBegin: page.lineBegin ?? 0,
|
|
648
|
+
lineEnd: page.lineEnd ?? 0,
|
|
649
|
+
truncated: page.truncated === true,
|
|
650
|
+
};
|
|
651
|
+
} catch (error) {
|
|
652
|
+
throw mapManagerError(error);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
async function sessionClose(sessionId) {
|
|
657
|
+
if (typeof manager?.adminClose !== "function") {
|
|
658
|
+
throw new ApiError("METHOD_UNAVAILABLE", "remote shell sessions are not enabled in this composition", 409);
|
|
659
|
+
}
|
|
660
|
+
try {
|
|
661
|
+
return await manager.adminClose({ sessionId, reason: "closed from the management page" });
|
|
662
|
+
} catch (error) {
|
|
663
|
+
throw mapManagerError(error);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
return async function handler(req, res) {
|
|
668
|
+
try {
|
|
669
|
+
// Fail closed on the shared Host/Origin + browser-cookie fence. Without a
|
|
670
|
+
// connection service (non-browser composition) the route is not mounted by
|
|
671
|
+
// lib/index.js at all, so a missing fence here is a configuration error.
|
|
672
|
+
const connection = ctx?.get?.("connection");
|
|
673
|
+
if (connection === undefined || connection === null || typeof connection.requestRejection !== "function") {
|
|
674
|
+
return writeJson(res, 503, {
|
|
675
|
+
ok: false,
|
|
676
|
+
error: { code: "FENCE_UNAVAILABLE", message: "browser trust checks are unavailable" },
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
const rejection = connection.requestRejection?.(req);
|
|
680
|
+
if (rejection !== undefined && rejection !== false && rejection !== null) {
|
|
681
|
+
return writeJson(res, 403, { ok: false, error: { code: "FORBIDDEN", message: "forbidden" } });
|
|
682
|
+
}
|
|
683
|
+
if (req.method !== "POST") {
|
|
684
|
+
res.setHeader("allow", "POST");
|
|
685
|
+
return writeJson(res, 405, { ok: false, error: { code: "METHOD_NOT_ALLOWED", message: "POST only" } });
|
|
686
|
+
}
|
|
687
|
+
const url = new URL(req.url ?? "/", "http://dsh.local");
|
|
688
|
+
if (url.pathname.replace(/\/+$/u, "") !== API_PREFIX) {
|
|
689
|
+
return writeJson(res, 404, { ok: false, error: { code: "NOT_FOUND", message: "unknown management route" } });
|
|
690
|
+
}
|
|
691
|
+
const body = await readJsonBody(req);
|
|
692
|
+
if (body.method === "auth.password") {
|
|
693
|
+
const controller = new AbortController();
|
|
694
|
+
const disconnect = () => { if (!res.writableEnded) controller.abort(); };
|
|
695
|
+
res.once("close", disconnect);
|
|
696
|
+
try {
|
|
697
|
+
const result = await dispatch(body, controller.signal);
|
|
698
|
+
return writeJson(res, 200, { ok: true, result });
|
|
699
|
+
} finally {
|
|
700
|
+
res.removeListener("close", disconnect);
|
|
701
|
+
delete body.password;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
const result = await dispatch(body);
|
|
705
|
+
return writeJson(res, 200, { ok: true, result });
|
|
706
|
+
} catch (error) {
|
|
707
|
+
const status = error instanceof ApiError ? error.status : 500;
|
|
708
|
+
const code = error instanceof ApiError ? error.code : "INTERNAL";
|
|
709
|
+
if (!(error instanceof ApiError)) {
|
|
710
|
+
warn(`dsh-remote: management API failed: ${messageOf(error)}`);
|
|
711
|
+
}
|
|
712
|
+
return writeJson(res, status, { ok: false, error: { code, message: messageOf(error) } });
|
|
713
|
+
}
|
|
714
|
+
};
|
|
715
|
+
}
|