@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
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# dsh-remote-terminal — local bridge launcher for the interactive SSH terminal.
|
|
3
|
+
#
|
|
4
|
+
# The DSH browser client types the line produced by relay.open() into a fresh
|
|
5
|
+
# native terminal:
|
|
6
|
+
#
|
|
7
|
+
# exec '<abs>/bin/dsh-remote-terminal' --host '<name>' --session '<id>' --socket '<path>'
|
|
8
|
+
#
|
|
9
|
+
# This script resolves a node binary and execs the CommonJS bridge next to it,
|
|
10
|
+
# forwarding every argument untouched. It must work from a plain interactive
|
|
11
|
+
# shell with no extra environment, so it tries $DSH_REMOTE_NODE, `node` on PATH,
|
|
12
|
+
# then a few common install locations.
|
|
13
|
+
set -u
|
|
14
|
+
|
|
15
|
+
# --- locate this script (resolve symlinks via the real directory) -----------
|
|
16
|
+
script=$0
|
|
17
|
+
# Follow a symlinked launcher to its target; `readlink` is not POSIX, so guard it.
|
|
18
|
+
if command -v readlink >/dev/null 2>&1; then
|
|
19
|
+
hops=0
|
|
20
|
+
while [ -L "$script" ] && [ "$hops" -lt 40 ]; do
|
|
21
|
+
hops=$((hops + 1))
|
|
22
|
+
target=$(readlink "$script") || break
|
|
23
|
+
case $target in
|
|
24
|
+
/*) script=$target ;;
|
|
25
|
+
*) script=$(dirname "$script")/$target ;;
|
|
26
|
+
esac
|
|
27
|
+
done
|
|
28
|
+
fi
|
|
29
|
+
case $script in
|
|
30
|
+
*/*) ;;
|
|
31
|
+
*)
|
|
32
|
+
script=$(command -v "$script" 2>/dev/null || printf '%s' "$script")
|
|
33
|
+
;;
|
|
34
|
+
esac
|
|
35
|
+
case $script in
|
|
36
|
+
*/*) ;;
|
|
37
|
+
*)
|
|
38
|
+
printf 'dsh-remote-terminal: cannot locate the launcher script (%s)\n' "$0" >&2
|
|
39
|
+
exit 127
|
|
40
|
+
;;
|
|
41
|
+
esac
|
|
42
|
+
script_dir=$(CDPATH= cd -P "$(dirname "$script")" 2>/dev/null && pwd -P) || {
|
|
43
|
+
printf 'dsh-remote-terminal: cannot resolve the launcher directory (%s)\n' "$0" >&2
|
|
44
|
+
exit 127
|
|
45
|
+
}
|
|
46
|
+
bridge=$script_dir/../lib/terminal/bridge.cjs
|
|
47
|
+
|
|
48
|
+
if [ ! -f "$bridge" ]; then
|
|
49
|
+
printf 'dsh-remote-terminal: bridge not found at %s\n' "$bridge" >&2
|
|
50
|
+
exit 127
|
|
51
|
+
fi
|
|
52
|
+
|
|
53
|
+
# --- locate node ------------------------------------------------------------
|
|
54
|
+
node_bin=${DSH_REMOTE_NODE:-}
|
|
55
|
+
if [ -z "$node_bin" ]; then
|
|
56
|
+
node_bin=$(command -v node 2>/dev/null || true)
|
|
57
|
+
fi
|
|
58
|
+
if [ -z "$node_bin" ]; then
|
|
59
|
+
for candidate in \
|
|
60
|
+
/opt/homebrew/bin/node \
|
|
61
|
+
/usr/local/bin/node \
|
|
62
|
+
/usr/bin/node \
|
|
63
|
+
/opt/local/bin/node \
|
|
64
|
+
/snap/bin/node \
|
|
65
|
+
"$HOME/.local/bin/node" \
|
|
66
|
+
"$HOME/.nvm/versions/node"/*/bin/node; do
|
|
67
|
+
if [ -n "$candidate" ] && [ -x "$candidate" ]; then
|
|
68
|
+
node_bin=$candidate
|
|
69
|
+
break
|
|
70
|
+
fi
|
|
71
|
+
done
|
|
72
|
+
fi
|
|
73
|
+
if [ -z "$node_bin" ]; then
|
|
74
|
+
printf 'dsh-remote-terminal: no node binary found (set DSH_REMOTE_NODE)\n' >&2
|
|
75
|
+
exit 127
|
|
76
|
+
fi
|
|
77
|
+
if [ ! -x "$node_bin" ]; then
|
|
78
|
+
printf 'dsh-remote-terminal: node is not executable: %s\n' "$node_bin" >&2
|
|
79
|
+
exit 127
|
|
80
|
+
fi
|
|
81
|
+
|
|
82
|
+
exec "$node_bin" "$bridge" "$@"
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Cluster shortcut action contract
|
|
2
|
+
|
|
3
|
+
Implementation contract for replacing fixed `loginCommand` with `actions`.
|
|
4
|
+
|
|
5
|
+
## Profile
|
|
6
|
+
|
|
7
|
+
A shortcut declares `viaHost` and `actions` (1–32 items). An ordinary direct SSH host cannot declare actions. `viaHost` still resolves a direct entrance only, with existing allowHosts/readonly inheritance and terminal-only restrictions. Do not execute exec/probe/SFTP against the entrance as if it were the cluster.
|
|
8
|
+
|
|
9
|
+
Legacy `viaHost` + canonical `sww -r -u USER CLUSTER` migrates to one command action with `expectCluster: CLUSTER`, preserving root-on-target confirmation. Explicit new actions take precedence and normalized saved records no longer need `loginCommand`; metadata may retain it only for legacy compatibility. Reattaching an existing initialized PTY does not replay actions; every genuinely new channel initializes once, never resends a step after failure.
|
|
10
|
+
|
|
11
|
+
## Action shapes
|
|
12
|
+
|
|
13
|
+
All actions may have optional `label` (1–80 printable characters). Unknown fields and raw credential field names must be rejected.
|
|
14
|
+
|
|
15
|
+
- `{type:'command', value:string, expect?:string, expectCluster?:string, timeoutMs?:number}`: send a nonempty single-line command plus CR, then wait for a real shell prompt by default; `expect` selects a literal output completion condition. Legacy `expectCluster` selects the existing anchored target-cluster root prompt check; it is mutually exclusive with expect and must be a safe cluster name.
|
|
16
|
+
- `{type:'text', value:string, expect?:string, timeoutMs?:number}`: send printable raw text without Enter; optional literal completion condition. Without expect it completes after issuing input, so a following key/wait can complete interaction.
|
|
17
|
+
- `{type:'key', value:'Enter'|'Tab'|'Escape'|'Ctrl-C'|'Ctrl-D'|'ArrowUp'|'ArrowDown'|'ArrowLeft'|'ArrowRight'|'Backspace', expect?:string, timeoutMs?:number}`: send the corresponding bytes once, optional literal completion condition.
|
|
18
|
+
- `{type:'wait', value:string, timeoutMs?:number}`: wait for literal sanitized output (not a regular expression).
|
|
19
|
+
- `{type:'delay', durationMs:number}`: cancellable bounded delay.
|
|
20
|
+
|
|
21
|
+
Command/text values are 1–4096 characters with no C0/DEL controls (no literal newline, CR, ESC, NUL). Literal expects/wait values are 1–2048 characters with no NUL/ESC; no user regex. Step timeout defaults to 30000ms, range 100–120000ms. Delay is 0–120000ms. Entire sequence capped at 20 minutes. Secrets must not be embedded in actions; SSH auth stays in the user-only password dialog or environment references.
|
|
22
|
+
|
|
23
|
+
## Execution
|
|
24
|
+
|
|
25
|
+
Existing exports `authorizeConnectionLogin` and `runConnectionLogin` stay callable. Normalize through the shared validator. Policy-check every command/text/key send with the existing approval/risk gate (including readonly and deny patterns); waiting/delay do not grant authority. No synthesized Agent, no implicit approval when saving a profile. Preserve current denial under always/never or unprovenCommands=ask for automatic send actions. Unsupported high-risk automation fails explicitly instead of silently bypassing policy.
|
|
26
|
+
|
|
27
|
+
The PTY opens only after entrance SSH authentication. Wait for the entrance shell prompt before a normal first send; when the first action is a literal wait, use that configured output as the readiness barrier for menu/custom-prompt entrances instead. A command's default shell-prompt completion does not prove exit code zero or the intended target; configure target-success output or expectCluster for login changes. Capture PTY output before any write and subscribe throughout the sequence so synchronous output is not lost between send/wait steps. Do not satisfy a later command using an earlier prompt/output. A standalone wait following text/key must be able to see the output those sends already emitted. Keep bounded sanitized output; avoid JS regex from user data. Stop immediately on timeout, cancellation or PTY exit and never run remaining actions. Leave native-model mounting/disposal to its owner.
|
|
28
|
+
|
|
29
|
+
`runConnectionLogin(pty, {profile,initialOutput,signal,timeoutMs,onCommand,onProgress})` reports safe progress:
|
|
30
|
+
`{state:'waiting-entry'|'running'|'completed'|'failed'|'cancelled', total:number, index:number, completed:number, type?:string, label?:string}`.
|
|
31
|
+
Index is zero-based during a step; final completion has index=total. Do not put raw output, text/key bytes or credentials in progress. Legacy onCommand remains for command sends only. Relay snapshots publish `actionProgress`, retain loginState compatibility (waiting/sent/confirmed/failed), and report connected only when all actions finish.
|
|
32
|
+
|
|
33
|
+
## UI
|
|
34
|
+
|
|
35
|
+
Host editor: replace fixed sww user/cluster fields with ordered action rows, type dropdown, relevant value/expected-output/timeout/delay fields, add/remove/move up/down. Preserve entrance selector, metadata, direct SSH form and existing password/native-terminal helpers. Include explainers for prompt-default command completion, literal waits, failure-stop behavior and no secrets in actions. Read old loginCommand into a migrated command row. Use `actions` in host create/update payloads. Show bounded step progress from relay `actionProgress`; do not auto-repeat, skip, or claim ready early.
|
|
36
|
+
|
|
37
|
+
## Verification
|
|
38
|
+
|
|
39
|
+
Test validation and deep-copy persistence/host loading; legacy migration and target root confirmation; sequential synchronous-output handling and fresh-output isolation; every action type; timeout/abort/exit fail-stop; policy denial before writes; no replay on reattach; editor payload/reordering/migration and privacy. Run the available complete regression suite, deploy via plugin_manager, verify live registration and be honest about manual real-host verification limits.
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/docs/icon.svg
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" fill="none">
|
|
2
|
+
<rect x="3" y="10" width="42" height="30" rx="5" fill="#0F172A" stroke="#38BDF8" stroke-width="2.5"/>
|
|
3
|
+
<path d="M11 20l7 5-7 5" stroke="#38BDF8" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
|
|
4
|
+
<path d="M22 30h9" stroke="#7DD3FC" stroke-width="3" stroke-linecap="round"/>
|
|
5
|
+
<path d="M41 25c7 0 12 4 12 10v4" stroke="#34D399" stroke-width="3" stroke-linecap="round"/>
|
|
6
|
+
<rect x="46" y="39" width="14" height="9" rx="2.5" fill="#022C22" stroke="#34D399" stroke-width="2.5"/>
|
|
7
|
+
<path d="M49 44h8" stroke="#34D399" stroke-width="2.5" stroke-linecap="round"/>
|
|
8
|
+
<path d="M11 48h20" stroke="#94A3B8" stroke-width="2.5" stroke-linecap="round"/>
|
|
9
|
+
<path d="M15 53h12" stroke="#475569" stroke-width="2.5" stroke-linecap="round"/>
|
|
10
|
+
<circle cx="52" cy="16" r="3.5" fill="#38BDF8"/>
|
|
11
|
+
</svg>
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal helpers for the dsh-remote management API (`lib/api.js`).
|
|
3
|
+
*
|
|
4
|
+
* Split out of `lib/api.js` (v0.5.1) to keep both files under the ~700-line
|
|
5
|
+
* convention: `ApiError` + the documented status table, input validators, the
|
|
6
|
+
* defensive JSON body/reply helpers, and the bounded `terminal.trace`
|
|
7
|
+
* diagnostics append. No route registration lives here.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { dirname } from "node:path";
|
|
12
|
+
|
|
13
|
+
/** Maximum accepted request body. */
|
|
14
|
+
export const MAX_BODY_BYTES = 64 * 1024;
|
|
15
|
+
/** Maximum size of the client trace log before it is trimmed. */
|
|
16
|
+
export const TRACE_LOG_MAX_BYTES = 256 * 1024;
|
|
17
|
+
/** Bytes kept after a trace-log trim (last chunk). */
|
|
18
|
+
export const TRACE_LOG_KEEP_BYTES = 64 * 1024;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Error codes and HTTP statuses documented for the v0.5 host/terminal methods.
|
|
22
|
+
* Registry/relay errors are mapped onto these so the browser sees a stable
|
|
23
|
+
* contract instead of internal module error objects.
|
|
24
|
+
*
|
|
25
|
+
* @type {Record<string, number>}
|
|
26
|
+
*/
|
|
27
|
+
export const ERROR_STATUS = Object.freeze({
|
|
28
|
+
HOST_INVALID: 400,
|
|
29
|
+
HOST_EXISTS: 409,
|
|
30
|
+
HOST_NOT_FOUND: 404,
|
|
31
|
+
HOST_NOT_MANAGED: 400,
|
|
32
|
+
HOST_DISALLOWED: 403,
|
|
33
|
+
TERMINAL_DISABLED: 400,
|
|
34
|
+
TERMINAL_NOT_FOUND: 404,
|
|
35
|
+
TERMINAL_ERROR: 500,
|
|
36
|
+
AUDIT_INVALID: 400,
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
export class ApiError extends Error {
|
|
40
|
+
/**
|
|
41
|
+
* @param {string} code
|
|
42
|
+
* @param {string} message
|
|
43
|
+
* @param {number} [status]
|
|
44
|
+
*/
|
|
45
|
+
constructor(code, message, status = 400) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = "ApiError";
|
|
48
|
+
this.code = code;
|
|
49
|
+
this.status = status;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** @param {string} value */
|
|
54
|
+
export function requireString(value, field) {
|
|
55
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
56
|
+
throw new ApiError("INVALID_ARGUMENT", `${field} must be a non-empty string`);
|
|
57
|
+
}
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {unknown} value @param {string} field */
|
|
62
|
+
export function optionalPositiveInt(value, field) {
|
|
63
|
+
if (value === undefined || value === null) return undefined;
|
|
64
|
+
const numeric = Number(value);
|
|
65
|
+
if (!Number.isSafeInteger(numeric) || numeric < 0) {
|
|
66
|
+
throw new ApiError("INVALID_ARGUMENT", `${field} must be a non-negative integer`);
|
|
67
|
+
}
|
|
68
|
+
return numeric;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @param {unknown} error */
|
|
72
|
+
export function mapManagerError(error) {
|
|
73
|
+
const code = error?.code;
|
|
74
|
+
if (code === "NO_SESSION") return new ApiError("NO_SESSION", messageOf(error), 404);
|
|
75
|
+
return new ApiError("SESSION_ERROR", messageOf(error), 400);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// --- v0.5 host/terminal helpers -------------------------------------------
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Build an ApiError from the documented code table (every code has a status).
|
|
82
|
+
*
|
|
83
|
+
* @param {string} code
|
|
84
|
+
* @param {string} message
|
|
85
|
+
* @returns {ApiError}
|
|
86
|
+
*/
|
|
87
|
+
export function fail(code, message) {
|
|
88
|
+
return new ApiError(code, message, ERROR_STATUS[code] ?? 400);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** @param {any} host */
|
|
92
|
+
export function isManaged(host) {
|
|
93
|
+
return host?.managed === true || host?.source === "managed";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Read a policy flag from the host store without letting a store error blank the
|
|
98
|
+
* whole overview page.
|
|
99
|
+
*
|
|
100
|
+
* @param {() => boolean} read
|
|
101
|
+
* @param {boolean} fallback
|
|
102
|
+
* @returns {boolean}
|
|
103
|
+
*/
|
|
104
|
+
export function safeFlag(read, fallback) {
|
|
105
|
+
try {
|
|
106
|
+
const value = read();
|
|
107
|
+
return typeof value === "boolean" ? value : fallback;
|
|
108
|
+
} catch {
|
|
109
|
+
return fallback;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* A RemoteHost-shaped view of a raw ManagedHost record, for the fallback path
|
|
115
|
+
* where merged discovery failed right after a mutation.
|
|
116
|
+
*
|
|
117
|
+
* @param {any} record
|
|
118
|
+
* @returns {object}
|
|
119
|
+
*/
|
|
120
|
+
export function remoteHostOf(record) {
|
|
121
|
+
const name = String(record?.name ?? "");
|
|
122
|
+
return {
|
|
123
|
+
id: `managed:${name}`,
|
|
124
|
+
name,
|
|
125
|
+
host: String(record?.host ?? ""),
|
|
126
|
+
port: record?.port ?? 22,
|
|
127
|
+
username: record?.username,
|
|
128
|
+
source: "managed",
|
|
129
|
+
managed: true,
|
|
130
|
+
identityFile: record?.identityFile,
|
|
131
|
+
passwordEnv: record?.passwordEnv,
|
|
132
|
+
passphraseEnv: record?.passphraseEnv,
|
|
133
|
+
proxyJump: record?.proxyJump,
|
|
134
|
+
tags: record?.tags,
|
|
135
|
+
description: record?.description,
|
|
136
|
+
viaHost: record?.viaHost,
|
|
137
|
+
...(Array.isArray(record?.actions) ? { actions: record.actions.map((action) => ({ ...action })) } : {}),
|
|
138
|
+
...(record?.loginCommand ? { loginCommand: record.loginCommand } : {}),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* @param {any} body
|
|
144
|
+
* @param {string} method
|
|
145
|
+
* @returns {Record<string, unknown>}
|
|
146
|
+
*/
|
|
147
|
+
export function requireHostInput(body, method) {
|
|
148
|
+
const input = body?.host;
|
|
149
|
+
if (input === null || typeof input !== "object" || Array.isArray(input)) {
|
|
150
|
+
throw fail("HOST_INVALID", `${method} requires a "host" input object`);
|
|
151
|
+
}
|
|
152
|
+
return input;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** @param {unknown} value */
|
|
156
|
+
export function requireHostName(value) {
|
|
157
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
158
|
+
throw fail("HOST_INVALID", "name must be a non-empty string");
|
|
159
|
+
}
|
|
160
|
+
return value.trim();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** @param {unknown} value */
|
|
164
|
+
export function optionalAuditHost(value) {
|
|
165
|
+
if (value === undefined || value === null || value === "") return undefined;
|
|
166
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
167
|
+
throw fail("AUDIT_INVALID", "host must be a non-empty string");
|
|
168
|
+
}
|
|
169
|
+
return value.trim();
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* `audit.list({ full })`: true requests the raw `detailFull` field. Anything
|
|
174
|
+
* other than a boolean is rejected with AUDIT_INVALID.
|
|
175
|
+
*
|
|
176
|
+
* @param {unknown} value
|
|
177
|
+
* @returns {boolean | undefined}
|
|
178
|
+
*/
|
|
179
|
+
export function optionalAuditFull(value) {
|
|
180
|
+
if (value === undefined || value === null) return undefined;
|
|
181
|
+
if (typeof value !== "boolean") {
|
|
182
|
+
throw fail("AUDIT_INVALID", "full must be a boolean");
|
|
183
|
+
}
|
|
184
|
+
return value;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* @param {unknown} value
|
|
189
|
+
* @param {string} field
|
|
190
|
+
* @param {number} min
|
|
191
|
+
* @param {number} max
|
|
192
|
+
* @returns {number | undefined}
|
|
193
|
+
*/
|
|
194
|
+
export function optionalAuditInteger(value, field, min, max) {
|
|
195
|
+
if (value === undefined || value === null) return undefined;
|
|
196
|
+
const numeric = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
|
|
197
|
+
if (typeof numeric !== "number" || !Number.isSafeInteger(numeric) || numeric < min || numeric > max) {
|
|
198
|
+
throw fail("AUDIT_INVALID", `${field} must be an integer between ${min} and ${max}`);
|
|
199
|
+
}
|
|
200
|
+
return numeric;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* @param {unknown} value
|
|
205
|
+
* @param {string} field
|
|
206
|
+
* @returns {string}
|
|
207
|
+
*/
|
|
208
|
+
export function requireTerminalArg(value, field) {
|
|
209
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
210
|
+
throw new ApiError("INVALID_ARGUMENT", `${field} must be a non-empty string`);
|
|
211
|
+
}
|
|
212
|
+
return value;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* @param {unknown} value
|
|
217
|
+
* @returns {string | undefined}
|
|
218
|
+
*/
|
|
219
|
+
export function optionalTerminalSessionId(value) {
|
|
220
|
+
if (value === undefined || value === null || value === "") return undefined;
|
|
221
|
+
return requireTerminalArg(value, "sessionId");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Map relay/host errors onto the documented terminal error codes. Anything
|
|
226
|
+
* unexpected becomes a TERMINAL_ERROR so the browser still gets a structured
|
|
227
|
+
* answer.
|
|
228
|
+
*
|
|
229
|
+
* @param {unknown} error
|
|
230
|
+
* @returns {ApiError}
|
|
231
|
+
*/
|
|
232
|
+
export function mapTerminalError(error) {
|
|
233
|
+
const code = typeof (/** @type {any} */ (error)?.code) === "string" ? /** @type {any} */ (error).code : "";
|
|
234
|
+
if (code === "AUTH" || error?.cause?.code === "AUTH") {
|
|
235
|
+
return fail("AUTH", "SSH authentication failed; enter the host password to continue");
|
|
236
|
+
}
|
|
237
|
+
if (code === "HOST_DISALLOWED") return fail("HOST_DISALLOWED", messageOf(error));
|
|
238
|
+
if (code === "HOST_NOT_FOUND" || code === "UNKNOWN_HOST") return fail("HOST_NOT_FOUND", messageOf(error));
|
|
239
|
+
if (code === "TERMINAL_DISABLED") return fail("TERMINAL_DISABLED", messageOf(error));
|
|
240
|
+
if (code === "TERMINAL_NOT_FOUND") return fail("TERMINAL_NOT_FOUND", messageOf(error));
|
|
241
|
+
return fail("TERMINAL_ERROR", messageOf(error));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** @param {object} host */
|
|
245
|
+
export function formatTarget(host) {
|
|
246
|
+
const user = host.username?.trim();
|
|
247
|
+
const target = `${host.host}${host.port && host.port !== 22 ? `:${host.port}` : ""}`;
|
|
248
|
+
return user ? `${user}@${target}` : target;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** @param {object} host */
|
|
252
|
+
export function authHintFor(host) {
|
|
253
|
+
if (typeof host.passwordEnv === "string" && host.passwordEnv.length > 0) return "password env";
|
|
254
|
+
if (host.pubkeyAuthentication === false) return "password required";
|
|
255
|
+
if (typeof host.identityFile === "string" && host.identityFile.length > 0) return "key file";
|
|
256
|
+
if (typeof process.env.SSH_AUTH_SOCK === "string" && process.env.SSH_AUTH_SOCK.length > 0) return "ssh-agent";
|
|
257
|
+
return "default keys";
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Read a bounded JSON body.
|
|
262
|
+
* @param {import("node:http").IncomingMessage} req
|
|
263
|
+
*/
|
|
264
|
+
export async function readJsonBody(req) {
|
|
265
|
+
const chunks = [];
|
|
266
|
+
let total = 0;
|
|
267
|
+
for await (const chunk of req) {
|
|
268
|
+
total += chunk.length;
|
|
269
|
+
if (total > MAX_BODY_BYTES) throw new ApiError("BODY_TOO_LARGE", "request body is too large", 413);
|
|
270
|
+
chunks.push(chunk);
|
|
271
|
+
}
|
|
272
|
+
if (total === 0) return {};
|
|
273
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
274
|
+
try {
|
|
275
|
+
const parsed = JSON.parse(text);
|
|
276
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
277
|
+
throw new ApiError("INVALID_ARGUMENT", "request body must be a JSON object");
|
|
278
|
+
}
|
|
279
|
+
return parsed;
|
|
280
|
+
} catch (error) {
|
|
281
|
+
if (error instanceof ApiError) throw error;
|
|
282
|
+
throw new ApiError("INVALID_JSON", "request body must be valid JSON");
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** @param {import("node:http").ServerResponse} res @param {number} status @param {object} payload */
|
|
287
|
+
export function writeJson(res, status, payload) {
|
|
288
|
+
const body = JSON.stringify(payload);
|
|
289
|
+
res.statusCode = status;
|
|
290
|
+
res.setHeader("content-type", "application/json; charset=utf-8");
|
|
291
|
+
res.setHeader("cache-control", "no-store");
|
|
292
|
+
res.setHeader("content-length", Buffer.byteLength(body));
|
|
293
|
+
res.end(body);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** @param {unknown} error */
|
|
297
|
+
export function messageOf(error) {
|
|
298
|
+
return error instanceof Error ? error.message : String(error);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Append one newline-delimited trace line, bounded to 256 KiB and trimmed to
|
|
303
|
+
* the last 64 KiB once it overflows (same policy as the bridge log). Every
|
|
304
|
+
* filesystem error is swallowed: client tracing must never affect an action.
|
|
305
|
+
*
|
|
306
|
+
* @param {string} filePath absolute trace log path
|
|
307
|
+
* @param {string} line one JSON line (without the trailing newline)
|
|
308
|
+
* @returns {boolean} true when the line was written
|
|
309
|
+
*/
|
|
310
|
+
export function appendBoundedTraceLine(filePath, line) {
|
|
311
|
+
if (typeof filePath !== "string" || filePath.trim() === "") return false;
|
|
312
|
+
try {
|
|
313
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
314
|
+
appendFileSync(filePath, `${line}\n`, "utf8");
|
|
315
|
+
const stats = statSync(filePath);
|
|
316
|
+
if (!stats.isFile() || stats.size <= TRACE_LOG_MAX_BYTES) return true;
|
|
317
|
+
const raw = readFileSync(filePath);
|
|
318
|
+
let start = Math.max(0, raw.length - TRACE_LOG_KEEP_BYTES);
|
|
319
|
+
const newline = raw.indexOf(10, start);
|
|
320
|
+
writeFileSync(filePath, raw.subarray(newline === -1 ? start : newline + 1));
|
|
321
|
+
return true;
|
|
322
|
+
} catch {
|
|
323
|
+
return false;
|
|
324
|
+
}
|
|
325
|
+
}
|