dsh-remote-go 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.js +1344 -2095
- package/dist/src/admission.js +3 -28
- package/dist/src/api.js +37 -99
- package/dist/src/atomic-json.js +32 -66
- package/dist/src/bootstrap.js +17 -27
- package/dist/src/connect/attach.js +3 -25
- package/dist/src/connect/bootstrap.js +2 -8
- package/dist/src/connect/failures.js +3 -18
- package/dist/src/connect/guards.js +13 -8
- package/dist/src/connect/launch.js +11 -21
- package/dist/src/connect/links.js +11 -27
- package/dist/src/connect/ownership.js +33 -114
- package/dist/src/connect/pipeline.js +61 -158
- package/dist/src/connect/reattach.js +20 -44
- package/dist/src/connect/registry.js +0 -1
- package/dist/src/connect/repair.js +8 -37
- package/dist/src/connect/restart.js +36 -97
- package/dist/src/connect/stop.js +16 -50
- package/dist/src/connect/transport.js +10 -18
- package/dist/src/connect/verify.js +3 -12
- package/dist/src/connect/watchdog.js +6 -38
- package/dist/src/connect-log.js +16 -41
- package/dist/src/connect-progress.js +13 -45
- package/dist/src/constants.js +2 -40
- package/dist/src/context.js +10 -31
- package/dist/src/diagnostics.js +56 -25
- package/dist/src/download-jobs.js +11 -20
- package/dist/src/errors.js +175 -190
- package/dist/src/events.js +20 -84
- package/dist/src/host-lifecycle.js +39 -175
- package/dist/src/host-registry.js +27 -78
- package/dist/src/host-runtime.js +0 -9
- package/dist/src/host-view.js +6 -29
- package/dist/src/index.js +15 -35
- package/dist/src/kernel-adapter.js +34 -80
- package/dist/src/key-files.js +10 -23
- package/dist/src/known-hosts.js +13 -34
- package/dist/src/layout.js +3 -20
- package/dist/src/local-download.js +94 -163
- package/dist/src/local-ssh.js +12 -19
- package/dist/src/local-version.js +35 -49
- package/dist/src/node/download.js +1 -4
- package/dist/src/node-runtime.js +19 -38
- package/dist/src/probe.js +6 -7
- package/dist/src/prompts.js +56 -128
- package/dist/src/proxy/cookies.js +26 -60
- package/dist/src/proxy/headers.js +30 -125
- package/dist/src/proxy/http.js +33 -41
- package/dist/src/proxy/index.js +20 -34
- package/dist/src/proxy/limits.js +4 -6
- package/dist/src/proxy/routes.js +10 -17
- package/dist/src/proxy/upgrade.js +27 -42
- package/dist/src/redact.js +14 -33
- package/dist/src/remote-files.js +9 -21
- package/dist/src/remote-path.js +21 -62
- package/dist/src/remote-proc.js +35 -103
- package/dist/src/remote-web/registry.js +10 -50
- package/dist/src/remote-web/resolve.js +23 -104
- package/dist/src/remote-web/start.js +27 -64
- package/dist/src/remote-web/stop.js +6 -25
- package/dist/src/request-trust.js +15 -32
- package/dist/src/runtime/dispatch.js +33 -143
- package/dist/src/runtime/effects.js +7 -17
- package/dist/src/runtime/events.js +1 -1
- package/dist/src/runtime/fsm.js +11 -61
- package/dist/src/runtime/rules.js +113 -198
- package/dist/src/secrets.js +15 -38
- package/dist/src/service.js +22 -128
- package/dist/src/settings.js +41 -42
- package/dist/src/ssh-config.js +22 -41
- package/dist/src/ssh-failures.js +23 -74
- package/dist/src/ssh-sftp.js +47 -86
- package/dist/src/ssh.js +95 -177
- package/dist/src/store.js +31 -48
- package/dist/src/tool-shared.js +17 -52
- package/dist/src/tools-exec-policy.js +33 -79
- package/dist/src/tools-exec.js +87 -151
- package/dist/src/tools-report.js +100 -167
- package/dist/src/tools.js +59 -133
- package/dist/src/tunnel.js +9 -27
- package/dist/src/util.js +19 -56
- package/dist/src/version.js +6 -12
- package/dist/src/watchdog-bus.js +0 -8
- package/dist/src/watchdog.js +7 -47
- package/package.json +1 -1
package/dist/src/tool-shared.js
CHANGED
|
@@ -1,38 +1,18 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* The tools are separate modules (`tools.ts` owns the list and the reveal entry, `tools-report.ts`
|
|
6
|
-
* the diagnosis report, `tools-exec.ts` the remote command) but they must agree about two things:
|
|
7
|
-
* nothing leaves through a projection that skipped redaction, and a failure is always a structured
|
|
8
|
-
* result the model can report instead of a throw. Owning those here is what keeps a third tool from
|
|
9
|
-
* growing a second, quietly weaker copy.
|
|
10
|
-
*
|
|
11
|
-
* Everything in this module is pure: no transport, no timers, no disk.
|
|
12
|
-
*/
|
|
1
|
+
/** The building blocks every model-facing tool shares: the one redaction path a result crosses, the projection helpers
|
|
2
|
+
* and the result/error vocabulary the kernel renders. Keeping them here stops a third tool from growing a quietly
|
|
3
|
+
* weaker copy of either invariant (everything is redacted; a failure is a structured answer, never a throw). Pure. */
|
|
13
4
|
import { isRemoteGoError, toErrorView } from './errors.js';
|
|
14
5
|
import { redactText } from './redact.js';
|
|
15
6
|
import { messageOf } from './util.js';
|
|
16
7
|
/** Shape limits: one free-text field never carries more than this many characters. */
|
|
17
|
-
export const TEXT_LIMIT = 400;
|
|
18
|
-
export const ADDRESS_LIMIT = 200;
|
|
19
|
-
export const NAME_LIMIT = 120;
|
|
20
|
-
export const ID_LIMIT = 120;
|
|
8
|
+
export const TEXT_LIMIT = 400, ADDRESS_LIMIT = 200, NAME_LIMIT = 120, ID_LIMIT = 120;
|
|
21
9
|
/** A model-facing id or phase code is shorter than a sentence. */
|
|
22
10
|
export const CODE_LIMIT = 60;
|
|
23
11
|
export const ANSI_RE = /\u001B\[[0-9;]*[A-Za-z]/g;
|
|
24
12
|
export const CONTROL_RE = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g;
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
* carries them verbatim: `prompts.js` builds the first-use fingerprint prompt (120s timeout,
|
|
29
|
-
* `first-use` is the default policy) and `ssh.js` builds the host-key-changed one, while `auth`
|
|
30
|
-
* failures quote the configured key file.
|
|
31
|
-
*
|
|
32
|
-
* The fingerprint pattern is a flat quantifier, and key paths are found by scanning whitespace-
|
|
33
|
-
* separated tokens (see `isKeyPath`): a nested `(?:[^\s]*[\\/])?` path pattern backtracks
|
|
34
|
-
* quadratically on a long separator-free token, and `address` has no length limit upstream.
|
|
35
|
-
*/
|
|
13
|
+
// `redactText` covers tokens and key blocks but not host fingerprints or key-file paths, and a
|
|
14
|
+
// connect failure quotes both. The patterns stay flat on purpose: a nested path pattern backtracks
|
|
15
|
+
// quadratically on a long separator-free token, and `address` has no length limit upstream.
|
|
36
16
|
const FINGERPRINT_RE = /\bSHA256:[A-Za-z0-9+/=]+/gi;
|
|
37
17
|
const TOKEN_RE = /[^\s"'`]+/g;
|
|
38
18
|
const PATH_SEPARATOR_RE = /[\\/]+/;
|
|
@@ -60,14 +40,11 @@ export function truncate(text, limit) {
|
|
|
60
40
|
return text;
|
|
61
41
|
return `${points.slice(0, Math.max(0, limit - 1)).join('')}…`;
|
|
62
42
|
}
|
|
63
|
-
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
* `id_*` key counts too, because those are the key files a failed connect quotes.
|
|
67
|
-
*/
|
|
43
|
+
/** Whether one token names a private-key location. `.ssh` must be a whole path segment, so a host name like
|
|
44
|
+
* `box.ssh.example.com` stays readable; the key-file suffixes and OpenSSH `id_*` / host-key names count because those
|
|
45
|
+
* are what a failed connect quotes. */
|
|
68
46
|
function isKeyPath(token) {
|
|
69
|
-
// The trailing punctuation belongs to the sentence, not to the path
|
|
70
|
-
// like `could not read D:\keys\prod.ppk: ENOENT` would keep its key path.
|
|
47
|
+
// The trailing punctuation belongs to the sentence, not to the path.
|
|
71
48
|
const lowered = token.replace(TRAILING_PUNCTUATION_RE, '').toLowerCase();
|
|
72
49
|
const segments = lowered.split(PATH_SEPARATOR_RE);
|
|
73
50
|
if (segments.includes('.ssh'))
|
|
@@ -83,14 +60,10 @@ export function redactHostSecrets(text) {
|
|
|
83
60
|
.replace(FINGERPRINT_RE, '<fingerprint redacted>')
|
|
84
61
|
.replace(TOKEN_RE, (token) => (isKeyPath(token) ? '<private-key path>' : token));
|
|
85
62
|
}
|
|
86
|
-
/**
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
* The input is cut before any regular expression runs: a host field is caller- or remote-controlled
|
|
91
|
-
* (an address in hosts.json, a remote error line) and this projection is synchronous, so its cost
|
|
92
|
-
* must not scale with a field nobody will even see past the first few hundred characters.
|
|
93
|
-
*/
|
|
63
|
+
/** Redact and shorten one free-text value; a non-string or blank value is dropped, so a projected field is either a
|
|
64
|
+
* bounded redacted string or absent. The input is cut before any regular expression runs — it is caller- or
|
|
65
|
+
* remote-controlled and this projection is synchronous, so its cost must not scale with a field nobody reads past the
|
|
66
|
+
* first few hundred characters. */
|
|
94
67
|
export function safeText(value, limit = TEXT_LIMIT) {
|
|
95
68
|
if (typeof value !== 'string')
|
|
96
69
|
return null;
|
|
@@ -122,11 +95,7 @@ export function toolError(code, message, options = {}) {
|
|
|
122
95
|
out.hint = hint;
|
|
123
96
|
return out;
|
|
124
97
|
}
|
|
125
|
-
/**
|
|
126
|
-
* Turn anything the service throws into a structured result, so a broken store or an unknown host
|
|
127
|
-
* id is an answer the model can report instead of a throw. Only a defect this module cannot
|
|
128
|
-
* describe would throw.
|
|
129
|
-
*/
|
|
98
|
+
/** Turn anything the service throws into a result the model can report, so only an indescribable defect throws. */
|
|
130
99
|
export function serviceError(error) {
|
|
131
100
|
if (isRemoteGoError(error)) {
|
|
132
101
|
const view = toErrorView(error);
|
|
@@ -141,7 +110,6 @@ export function serviceError(error) {
|
|
|
141
110
|
hint: '重试一次;若仍失败请查看 DSH 日志。 / Retry once; if it keeps failing, check the DSH log.',
|
|
142
111
|
});
|
|
143
112
|
}
|
|
144
|
-
/** One failure line: the code plus the bilingual reason, redacted and bounded. */
|
|
145
113
|
export function describeViewError(error) {
|
|
146
114
|
if (!error || typeof error !== 'object')
|
|
147
115
|
return null;
|
|
@@ -161,10 +129,7 @@ export function renderFailure(value) {
|
|
|
161
129
|
const text = `${error.code ?? 'error'}: ${error.message ?? ''}`.trim();
|
|
162
130
|
return error.hint ? `${text} — ${error.hint}` : text;
|
|
163
131
|
}
|
|
164
|
-
/**
|
|
165
|
-
* The live view of one host, or `null` when the composition cannot answer. A snapshot that throws
|
|
166
|
-
* is the same "no answer" case: a projection must never take the tool down with it.
|
|
167
|
-
*/
|
|
132
|
+
/** The live view of one host; a snapshot that throws is the same "no answer" a projection must survive. */
|
|
168
133
|
export function hostViewOf(service, id) {
|
|
169
134
|
try {
|
|
170
135
|
const state = service?.snapshot?.();
|
|
@@ -1,31 +1,8 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
|
|
5
|
-
*
|
|
6
|
-
* than plumbing, so it is reviewed, tested and reasoned about on its own. It depends on nothing —
|
|
7
|
-
* a command string in, the offending token (or `null`) out — which also means the tool module stays
|
|
8
|
-
* a projection layer.
|
|
9
|
-
*
|
|
10
|
-
* Why it is a best effort: a POSIX shell is Turing-complete (quoting, builtins, globbing, `$(…)`,
|
|
11
|
-
* aliases, wrapper scripts on the remote PATH), so no word list can prove a command is read-only.
|
|
12
|
-
* This stops accidents and the obvious prompt-injection shapes; it is not a sandbox. The real
|
|
13
|
-
* boundary is that commands only run on a host the human already connected, plus the write switch in
|
|
14
|
-
* the plugin config.
|
|
15
|
-
*
|
|
16
|
-
* Two rules keep the list honest as programs gain flags:
|
|
17
|
-
* - a program that can mutate through an ordinary operand is not allowlisted at all (`date`,
|
|
18
|
-
* `hostname`), because no token list tells the read form from the write form;
|
|
19
|
-
* - the programs that mutate through an option are narrowed per token, and the long options are
|
|
20
|
-
* matched by **prefix**, because glibc's `getopt_long` accepts any unambiguous abbreviation
|
|
21
|
-
* (`file --comp` reaches `--compile`, `journalctl --rot` reaches `--rotate`).
|
|
22
|
-
*/
|
|
23
|
-
/**
|
|
24
|
-
* The programs read mode may run. Every entry is an inspection tool that does not normally write;
|
|
25
|
-
* `systemctl`, `journalctl`, `file`, `ss`, `df` and `ps` are additionally narrowed by the guards
|
|
26
|
-
* below. `date` and `hostname` are deliberately absent: both are settable through an ordinary
|
|
27
|
-
* operand (`date 010100002020`, `hostname attacker`), and no word list tells the two forms apart.
|
|
28
|
-
*/
|
|
1
|
+
/** The read-mode command policy of `remote_exec`: what may run when the caller did not ask for write mode. Its own
|
|
2
|
+
* module because it is a security decision rather than plumbing, and best effort rather than a sandbox — a POSIX shell
|
|
3
|
+
* is Turing-complete, so it stops accidents and obvious injection shapes. The boundary is the human plus the switch. */
|
|
4
|
+
/** The programs read mode may run: inspection tools that do not normally write, six further narrowed by the guards
|
|
5
|
+
* below. `date`/`hostname` are deliberately absent — an ordinary operand mutates them, and no token list helps. */
|
|
29
6
|
const READ_PROGRAMS = new Set([
|
|
30
7
|
'ls',
|
|
31
8
|
'cat',
|
|
@@ -58,12 +35,9 @@ const READ_PROGRAMS = new Set([
|
|
|
58
35
|
]);
|
|
59
36
|
/** The only `systemctl` verbs read mode allows: each one asks the state, none changes it. */
|
|
60
37
|
const SYSTEMCTL_READ_RE = /^(?:status|is-active|is-enabled|is-failed|show|cat|list-units|list-timers|--version)$/;
|
|
61
|
-
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
* `journalctl --rot` reaches `--rotate` and `ss --dia` reaches `--diag`. A token is refused when its
|
|
65
|
-
* option name is a prefix of one of these (three characters is the shortest unambiguous prefix).
|
|
66
|
-
*/
|
|
38
|
+
/** The long options that turn an allowed program into a mutation, matched by **prefix** because glibc's `getopt_long`
|
|
39
|
+
* accepts any unambiguous abbreviation (`file --comp` reaches `--compile`); three characters is the shortest name that
|
|
40
|
+
* already refuses. */
|
|
67
41
|
const DANGEROUS_LONG_OPTIONS = {
|
|
68
42
|
file: ['compile'],
|
|
69
43
|
ss: ['diag', 'kill'],
|
|
@@ -80,52 +54,22 @@ const DANGEROUS_LONG_OPTIONS = {
|
|
|
80
54
|
'update-catalog',
|
|
81
55
|
],
|
|
82
56
|
};
|
|
83
|
-
/**
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
* what it has is the standalone `e` command modifier, which appends every process's environment —
|
|
87
|
-
* a disclosure this read surface must not offer.
|
|
88
|
-
*/
|
|
57
|
+
/** The short flags with the same effect, checked per token because one can carry its argument glued to it (`-s@0`)
|
|
58
|
+
* while `file -C` takes none; `ps` has no mutating flag, but its standalone `e` modifier appends every process's
|
|
59
|
+
* environment. */
|
|
89
60
|
const DANGEROUS_SHORT_FLAGS = {
|
|
90
61
|
file: /^-[A-Za-z]*C/,
|
|
91
62
|
ss: /^-[A-Za-z]*[KD]/,
|
|
92
63
|
};
|
|
93
|
-
/**
|
|
94
|
-
* The two redirections that only silence a stream and cannot write anything. They are stripped
|
|
95
|
-
* before the redirect check so the everyday `ls /nope 2>/dev/null` stays usable; every other
|
|
96
|
-
* redirect operator is refused.
|
|
97
|
-
*/
|
|
64
|
+
/** The two redirections that only silence a stream, stripped so `ls /nope 2>/dev/null` stays usable. */
|
|
98
65
|
const DEV_NULL_RE = /2?>>?\s*\/dev\/null/g;
|
|
99
66
|
const STDERR_MERGE_RE = /2>&1/g;
|
|
100
67
|
/** The separators a compound line is split on; each resulting piece needs its own allowed program. */
|
|
101
68
|
const SEGMENT_RE = /[;|]+|&&/;
|
|
102
|
-
/** The offending
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
if (token.startsWith('--')) {
|
|
107
|
-
const name = (token.slice(2).split('=')[0] ?? '').toLowerCase();
|
|
108
|
-
if (name.length >= 3 && longs.some((option) => option.startsWith(name)))
|
|
109
|
-
return token;
|
|
110
|
-
continue;
|
|
111
|
-
}
|
|
112
|
-
if (program === 'ps' && token === 'e')
|
|
113
|
-
return token;
|
|
114
|
-
const shortFlags = DANGEROUS_SHORT_FLAGS[program];
|
|
115
|
-
if (shortFlags !== undefined && shortFlags.test(token))
|
|
116
|
-
return token;
|
|
117
|
-
}
|
|
118
|
-
return null;
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* The read-mode policy. It returns the offending program or token, or `null` when the command is
|
|
122
|
-
* one of the shapes the allowlist accepts.
|
|
123
|
-
*
|
|
124
|
-
* The order mirrors the risk: a newline/redirect/substitution can hide a whole program behind a
|
|
125
|
-
* harmless first word, so those are found before any token is trusted. Assignments are not
|
|
126
|
-
* stripped either — `FOO=bar ls` is refused *because* its first token is not a program, which is
|
|
127
|
-
* what makes a leading `PATH=… cmd` (or any wrapper) impossible to smuggle through.
|
|
128
|
-
*/
|
|
69
|
+
/** The read-mode policy: the offending program or token, or `null` when the command is one of the shapes the allowlist
|
|
70
|
+
* accepts. The order mirrors the risk: a newline, redirect or substitution can hide a program behind a harmless first
|
|
71
|
+
* word. Assignments are not stripped either — `FOO=bar ls` is refused *because* its first token is not a program, which
|
|
72
|
+
* blocks a leading `PATH=… cmd`. */
|
|
129
73
|
export function readOnlyViolation(command) {
|
|
130
74
|
if (command.trim() === '')
|
|
131
75
|
return 'empty';
|
|
@@ -134,8 +78,7 @@ export function readOnlyViolation(command) {
|
|
|
134
78
|
const stripped = command.replace(DEV_NULL_RE, '').replace(STDERR_MERGE_RE, '');
|
|
135
79
|
if (stripped.includes('>'))
|
|
136
80
|
return '>';
|
|
137
|
-
// `<` is input redirection
|
|
138
|
-
// socket (`cat </dev/tcp/host/port`), so it is refused with the other redirect operators.
|
|
81
|
+
// `<` is input redirection, and in bash it can open a TCP socket (`cat </dev/tcp/host/port`).
|
|
139
82
|
if (stripped.includes('<'))
|
|
140
83
|
return '<';
|
|
141
84
|
if (stripped.includes('`'))
|
|
@@ -149,8 +92,8 @@ export function readOnlyViolation(command) {
|
|
|
149
92
|
if (segments.length === 0)
|
|
150
93
|
return 'empty';
|
|
151
94
|
for (const segment of segments) {
|
|
152
|
-
// A lone `&` backgrounds the first program and runs whatever follows
|
|
153
|
-
//
|
|
95
|
+
// A lone `&` backgrounds the first program and runs whatever follows, so the segment starts a
|
|
96
|
+
// program its first token does not name (`<(` is already caught by the `<` rule).
|
|
154
97
|
if (segment.includes('&'))
|
|
155
98
|
return '&';
|
|
156
99
|
const tokens = segment.split(/\s+/);
|
|
@@ -159,9 +102,20 @@ export function readOnlyViolation(command) {
|
|
|
159
102
|
return program;
|
|
160
103
|
if (program === 'systemctl' && !SYSTEMCTL_READ_RE.test(tokens[1] ?? ''))
|
|
161
104
|
return tokens[1] ?? 'systemctl';
|
|
162
|
-
const
|
|
163
|
-
|
|
164
|
-
|
|
105
|
+
const longs = DANGEROUS_LONG_OPTIONS[program] ?? [];
|
|
106
|
+
for (const token of tokens.slice(1)) {
|
|
107
|
+
if (token.startsWith('--')) {
|
|
108
|
+
const name = (token.slice(2).split('=')[0] ?? '').toLowerCase();
|
|
109
|
+
if (name.length >= 3 && longs.some((option) => option.startsWith(name)))
|
|
110
|
+
return token;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (program === 'ps' && token === 'e')
|
|
114
|
+
return token;
|
|
115
|
+
const shortFlags = DANGEROUS_SHORT_FLAGS[program];
|
|
116
|
+
if (shortFlags !== undefined && shortFlags.test(token))
|
|
117
|
+
return token;
|
|
118
|
+
}
|
|
165
119
|
}
|
|
166
120
|
return null;
|
|
167
121
|
}
|
package/dist/src/tools-exec.js
CHANGED
|
@@ -1,33 +1,9 @@
|
|
|
1
|
-
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* Why a second module instead of a branch in `tools.ts`: the host list is a read-only surface by
|
|
6
|
-
* design (no approval, no switch), and the one tool that can change a remote machine must not
|
|
7
|
-
* inherit that shape. Keeping it here means the gate below — the read allowlist, the config-level
|
|
8
|
-
* write switch, the per-call confirmation — has exactly one owner and one test file.
|
|
9
|
-
*
|
|
10
|
-
* Why it reuses the live link: this module never dials, never authenticates and never sees a
|
|
11
|
-
* credential. A second connection path would be a second place to get host-key policy and auth
|
|
12
|
-
* wrong, and it would lose the one property that makes the command safe to offer at all: it can
|
|
13
|
-
* only reach a host the human already connected in the host switcher.
|
|
14
|
-
*
|
|
15
|
-
* Why write mode is a plugin-config switch *and* a per-call confirmation: a model that can enable
|
|
16
|
-
* its own execution has already escaped the gate. The switch is the human's decision and nothing
|
|
17
|
-
* in this module can write config; `confirm` only makes a caller restate that decision for one
|
|
18
|
-
* call, so an accidental write shows up as a second, visible argument.
|
|
19
|
-
*
|
|
20
|
-
* Why the read allowlist lives in its own module (`tools-exec-policy.ts`): it is the one part of
|
|
21
|
-
* this tool that is a security decision, it is a best effort rather than a sandbox (a POSIX shell is
|
|
22
|
-
* Turing-complete), and it deserves its own review and tests instead of hiding between projections.
|
|
23
|
-
*
|
|
24
|
-
* Why every stream is re-encoded before it leaves: remote output is untrusted data, and while
|
|
25
|
-
* somebody debugs auth it is exactly the stream that carries fingerprints, key paths and tokens.
|
|
26
|
-
* Both streams therefore cross the same strip/redact/cap path — nothing remote is echoed raw.
|
|
27
|
-
*/
|
|
1
|
+
/** The model-facing remote command (`remote_exec`): one shell command on an already-connected host over the link the
|
|
2
|
+
* host half owns. Its own module because the one tool that can change a remote machine must not inherit the read-only
|
|
3
|
+
* shape of the host list: the gate (read allowlist, config write switch, per-call confirm) has exactly one owner. */
|
|
28
4
|
import { redactText } from './redact.js';
|
|
29
5
|
import { readOnlyViolation } from './tools-exec-policy.js';
|
|
30
|
-
import { ANSI_RE, CONTROL_RE, ERROR_SCHEMA,
|
|
6
|
+
import { ANSI_RE, CONTROL_RE, ERROR_SCHEMA, ID_LIMIT, NAME_LIMIT, hostViewOf, redactHostSecrets, renderFailure, renderText, safeText, serviceError, toolError, } from './tool-shared.js';
|
|
31
7
|
export const EXEC_TOOL_NAME = 'remote_exec';
|
|
32
8
|
/** One command line: the parser, the schema and every message quote this number. */
|
|
33
9
|
const COMMAND_LIMIT = 4000;
|
|
@@ -39,67 +15,51 @@ const TIMEOUT_DEFAULT_MS = 20_000;
|
|
|
39
15
|
const MAX_BYTES_MIN = 1_024;
|
|
40
16
|
const MAX_BYTES_MAX = 65_536;
|
|
41
17
|
const MAX_BYTES_DEFAULT = 32_768;
|
|
42
|
-
/**
|
|
43
|
-
*
|
|
44
|
-
* than the projection cap: the port keeps the command's output bounded, and `maxBytes` below is the
|
|
45
|
-
* (smaller) number of characters a model ever sees.
|
|
46
|
-
*/
|
|
18
|
+
/** The transport's own capture cap (both streams, applied by the port): deliberately larger than the projection cap,
|
|
19
|
+
* because the port bounds the command's output and `maxBytes` is the smaller number of characters the model sees. */
|
|
47
20
|
const SSH_CAPTURE_BYTES = 2 * 1024 * 1024;
|
|
48
|
-
|
|
21
|
+
/** One `string` / `integer` / `boolean` schema member; the kernel reads these descriptions verbatim. */
|
|
22
|
+
const str = (description) => ({ type: 'string', description });
|
|
23
|
+
const int = (description) => ({ type: 'integer', description });
|
|
24
|
+
const bool = (description) => ({ type: 'boolean', description });
|
|
25
|
+
/** One closed object schema: its members, the required ones, no undeclared key. */
|
|
26
|
+
const obj = (properties, required) => ({
|
|
49
27
|
type: 'object',
|
|
50
|
-
properties
|
|
51
|
-
|
|
52
|
-
label: { type: 'string', description: 'Display name of the host, falling back to the id.' },
|
|
53
|
-
},
|
|
54
|
-
required: ['id', 'label'],
|
|
28
|
+
properties,
|
|
29
|
+
required,
|
|
55
30
|
additionalProperties: false,
|
|
56
|
-
};
|
|
31
|
+
});
|
|
32
|
+
const HOST_SCHEMA = obj({
|
|
33
|
+
id: str('Host id the call named.'),
|
|
34
|
+
label: str('Display name of the host, falling back to the id.'),
|
|
35
|
+
}, ['id', 'label']);
|
|
57
36
|
/** The `exec` parameters as the kernel validates them; every bound here is enforced again in code. */
|
|
58
|
-
const PARAMETERS = {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
enum: ['read', 'write'],
|
|
66
|
-
description: 'read (default) is restricted to the allowlist; write needs the config switch and confirm: true.',
|
|
67
|
-
},
|
|
68
|
-
confirm: { type: 'boolean', description: 'Must be true for mode "write"; ignored in read mode.' },
|
|
69
|
-
timeoutMs: {
|
|
70
|
-
type: 'integer',
|
|
71
|
-
description: 'Deadline in ms: 1000–120000, default 20000. Out-of-range values are clamped.',
|
|
72
|
-
},
|
|
73
|
-
maxBytes: {
|
|
74
|
-
type: 'integer',
|
|
75
|
-
description: 'Per-stream output cap in characters: 1024–65536, default 32768. Out-of-range values are clamped.',
|
|
76
|
-
},
|
|
77
|
-
},
|
|
78
|
-
required: ['id', 'command'],
|
|
79
|
-
additionalProperties: false,
|
|
80
|
-
};
|
|
81
|
-
const OUTPUT_SCHEMA = {
|
|
82
|
-
type: 'object',
|
|
83
|
-
properties: {
|
|
84
|
-
ok: { type: 'boolean' },
|
|
85
|
-
host: HOST_SCHEMA,
|
|
86
|
-
command: { type: 'string', description: 'The command as received, redacted and capped at 200 characters.' },
|
|
87
|
-
mode: { type: 'string', description: 'The mode that ran: read or write.' },
|
|
88
|
-
code: { type: 'integer', description: 'Exit status; absent when the command produced none.' },
|
|
89
|
-
signal: { type: 'string', description: 'Signal that ended the command; absent when there was none.' },
|
|
90
|
-
stdout: { type: 'string', description: 'Captured standard output, redacted and capped at maxBytes characters.' },
|
|
91
|
-
stderr: { type: 'string', description: 'Captured standard error, redacted and capped at maxBytes characters.' },
|
|
92
|
-
timedOut: {
|
|
93
|
-
type: 'boolean',
|
|
94
|
-
description: 'True when the deadline force-finished the command; partial output kept.',
|
|
95
|
-
},
|
|
96
|
-
durationMs: { type: 'integer', description: 'How long the command took on this side, in milliseconds.' },
|
|
97
|
-
truncated: { type: 'boolean', description: 'Present only when a stream was cut at maxBytes.' },
|
|
98
|
-
error: ERROR_SCHEMA,
|
|
37
|
+
const PARAMETERS = obj({
|
|
38
|
+
id: str('Host id from remote_hosts_list; the host must be connected.'),
|
|
39
|
+
command: str('One shell command line, at most 4000 characters.'),
|
|
40
|
+
mode: {
|
|
41
|
+
type: 'string',
|
|
42
|
+
enum: ['read', 'write'],
|
|
43
|
+
description: 'read (default) is restricted to the allowlist; write needs the config switch and confirm: true.',
|
|
99
44
|
},
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
45
|
+
confirm: bool('Must be true for mode "write"; ignored in read mode.'),
|
|
46
|
+
timeoutMs: int('Deadline in ms: 1000–120000, default 20000. Out-of-range values are clamped.'),
|
|
47
|
+
maxBytes: int('Per-stream output cap in characters: 1024–65536, default 32768. Out-of-range values are clamped.'),
|
|
48
|
+
}, ['id', 'command']);
|
|
49
|
+
const OUTPUT_SCHEMA = obj({
|
|
50
|
+
ok: { type: 'boolean' },
|
|
51
|
+
host: HOST_SCHEMA,
|
|
52
|
+
command: str('The command as received, redacted and capped at 200 characters.'),
|
|
53
|
+
mode: str('The mode that ran: read or write.'),
|
|
54
|
+
code: int('Exit status; absent when the command produced none.'),
|
|
55
|
+
signal: str('Signal that ended the command; absent when there was none.'),
|
|
56
|
+
stdout: str('Captured standard output, redacted and capped at maxBytes characters.'),
|
|
57
|
+
stderr: str('Captured standard error, redacted and capped at maxBytes characters.'),
|
|
58
|
+
timedOut: bool('True when the deadline force-finished the command; partial output kept.'),
|
|
59
|
+
durationMs: int('How long the command took on this side, in milliseconds.'),
|
|
60
|
+
truncated: bool('Present only when a stream was cut at maxBytes.'),
|
|
61
|
+
error: ERROR_SCHEMA,
|
|
62
|
+
}, ['ok']);
|
|
103
63
|
/** The raised voice of the description: what runs, over which link, and what the model may trust. */
|
|
104
64
|
const EXEC_DESCRIPTION = [
|
|
105
65
|
'Run one shell command on a remote host that is already connected, over the authenticated SSH link dsh-remote-go already owns.',
|
|
@@ -139,73 +99,58 @@ function boundedInt(value, fallback, min, max) {
|
|
|
139
99
|
return fallback;
|
|
140
100
|
return Math.min(max, Math.max(min, value));
|
|
141
101
|
}
|
|
102
|
+
/** One refused call: the structured error, the mode when it is known and the bounded echo when there is one. */
|
|
103
|
+
function refusal(error, mode, echo) {
|
|
104
|
+
const output = { ok: false };
|
|
105
|
+
if (mode !== undefined)
|
|
106
|
+
output.mode = mode;
|
|
107
|
+
if (echo !== undefined)
|
|
108
|
+
output.command = echo;
|
|
109
|
+
output.error = error;
|
|
110
|
+
return output;
|
|
111
|
+
}
|
|
142
112
|
function hostNotFound(id) {
|
|
143
113
|
const named = id.slice(0, ID_LIMIT);
|
|
144
|
-
return
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
? '没有给出主机 id / no host id was given'
|
|
148
|
-
: `找不到主机 “${named}” / host "${named}" is not configured`, { hint: '先用 remote_hosts_list 取得主机 id。 / Call remote_hosts_list to get a host id.' }),
|
|
149
|
-
};
|
|
114
|
+
return refusal(toolError('HOST_NOT_FOUND', named === ''
|
|
115
|
+
? '没有给出主机 id / no host id was given'
|
|
116
|
+
: `找不到主机 “${named}” / host "${named}" is not configured`, { hint: '先用 remote_hosts_list 取得主机 id。 / Call remote_hosts_list to get a host id.' }));
|
|
150
117
|
}
|
|
151
118
|
function hostNotConnected(id, echo, mode) {
|
|
152
119
|
const named = id.slice(0, ID_LIMIT);
|
|
153
|
-
|
|
154
|
-
if (echo !== undefined)
|
|
155
|
-
output.command = echo;
|
|
156
|
-
output.error = toolError('HOST_NOT_CONNECTED', `主机 “${named}” 还没有连接 / host "${named}" is not connected`, {
|
|
120
|
+
return refusal(toolError('HOST_NOT_CONNECTED', `主机 “${named}” 还没有连接 / host "${named}" is not connected`, {
|
|
157
121
|
hint: '先在主机切换器里连接这台主机;本工具不会自行拨号或认证。 / Connect the host in the host switcher first; this tool never dials or authenticates.',
|
|
158
|
-
});
|
|
159
|
-
return output;
|
|
122
|
+
}), mode, echo);
|
|
160
123
|
}
|
|
161
124
|
function commandTooLong() {
|
|
162
|
-
return {
|
|
163
|
-
ok: false,
|
|
164
|
-
error: toolError('INVALID_INPUT', `command 最长 ${COMMAND_LIMIT} 个字符 / command may carry at most ${COMMAND_LIMIT} characters`, { retryable: false, hint: '把命令拆成几次调用。 / Split the command across several calls.' }),
|
|
165
|
-
};
|
|
125
|
+
return refusal(toolError('INVALID_INPUT', `command 最长 ${COMMAND_LIMIT} 个字符 / command may carry at most ${COMMAND_LIMIT} characters`, { retryable: false, hint: '把命令拆成几次调用。 / Split the command across several calls.' }));
|
|
166
126
|
}
|
|
167
127
|
/** Write mode has no allowlist to fall back on, so a blank line is refused as a bad argument here. */
|
|
168
128
|
function commandBlank() {
|
|
169
|
-
return {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
hint: '传一条要执行的完整命令。 / Pass the complete command to run.',
|
|
174
|
-
}),
|
|
175
|
-
};
|
|
129
|
+
return refusal(toolError('INVALID_INPUT', 'command 不能为空 / command must not be blank', {
|
|
130
|
+
retryable: false,
|
|
131
|
+
hint: '传一条要执行的完整命令。 / Pass the complete command to run.',
|
|
132
|
+
}));
|
|
176
133
|
}
|
|
177
134
|
/** The read-mode refusal: one code, the bilingual reason, and the offending token named. */
|
|
178
135
|
function readOnlyRefused(token, echo) {
|
|
179
136
|
const named = token.slice(0, 80);
|
|
180
|
-
|
|
181
|
-
if (echo !== undefined)
|
|
182
|
-
output.command = echo;
|
|
183
|
-
output.error = toolError('READ_ONLY_REFUSED', `只读模式拒绝执行(${named}):这条命令可能改变远端主机 / read mode refused (${named}): the command may change the remote host`, {
|
|
137
|
+
return refusal(toolError('READ_ONLY_REFUSED', `只读模式拒绝执行(${named}):这条命令可能改变远端主机 / read mode refused (${named}): the command may change the remote host`, {
|
|
184
138
|
hint: '改用 mode "write" 并设置 confirm: true,或换一条只读命令。 / Use mode "write" with confirm: true, or run a read-only command.',
|
|
185
|
-
});
|
|
186
|
-
return output;
|
|
139
|
+
}), 'read', echo);
|
|
187
140
|
}
|
|
188
141
|
function writeDisabled(echo) {
|
|
189
|
-
|
|
190
|
-
if (echo !== undefined)
|
|
191
|
-
output.command = echo;
|
|
192
|
-
output.error = toolError('WRITE_DISABLED', '写模式已被插件配置关闭,命令没有执行 / write execution is switched off for this plugin, so the command was not run', {
|
|
142
|
+
return refusal(toolError('WRITE_DISABLED', '写模式已被插件配置关闭,命令没有执行 / write execution is switched off for this plugin, so the command was not run', {
|
|
193
143
|
hint: '需要人工在插件配置里打开 exec.allowWrite。 / The human must enable exec.allowWrite in the plugin config.',
|
|
194
|
-
});
|
|
195
|
-
return output;
|
|
144
|
+
}), 'write', echo);
|
|
196
145
|
}
|
|
197
146
|
function confirmRequired(echo) {
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
output.error = toolError('CONFIRM_REQUIRED', '写模式需要 confirm: true 才会执行 / mode "write" runs only when the call sets confirm: true', { hint: '把这次调用改成 confirm: true 再试一次。 / Repeat the call with confirm: true.' });
|
|
202
|
-
return output;
|
|
147
|
+
return refusal(toolError('CONFIRM_REQUIRED', '写模式需要 confirm: true 才会执行 / mode "write" runs only when the call sets confirm: true', {
|
|
148
|
+
hint: '把这次调用改成 confirm: true 再试一次。 / Repeat the call with confirm: true.',
|
|
149
|
+
}), 'write', echo);
|
|
203
150
|
}
|
|
204
|
-
/**
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
* The split guard keeps a cap from cutting a UTF-16 surrogate pair in half.
|
|
208
|
-
*/
|
|
151
|
+
/** Strip escapes and control bytes, redact, then cap: remote output is where fingerprints, key paths and tokens travel
|
|
152
|
+
* while somebody debugs auth. The cap is applied last so a redaction rule never runs on half a text (a token cut in the
|
|
153
|
+
* middle would leak its prefix); the surrogate guard keeps the cap from splitting a UTF-16 pair. */
|
|
209
154
|
function sanitizeStream(value, limit) {
|
|
210
155
|
const raw = typeof value === 'string' ? value : '';
|
|
211
156
|
const cleaned = redactHostSecrets(redactText(raw.replace(ANSI_RE, '').replace(CONTROL_RE, '')));
|
|
@@ -267,10 +212,8 @@ function renderSuccess(result) {
|
|
|
267
212
|
lines.push('(命令没有输出 / the command produced no output)');
|
|
268
213
|
return renderText(lines);
|
|
269
214
|
}
|
|
270
|
-
/**
|
|
271
|
-
*
|
|
272
|
-
* rides the same live runtime the switcher shows — there is no second connection path here.
|
|
273
|
-
*/
|
|
215
|
+
/** Build the one tool this module offers. `service` is the Host half's own service, so the command rides the same live
|
|
216
|
+
* runtime the switcher shows — there is no second connection path here. */
|
|
274
217
|
export function execTool(options) {
|
|
275
218
|
const service = options.service;
|
|
276
219
|
const logger = options.logger ?? console;
|
|
@@ -297,8 +240,8 @@ export function execTool(options) {
|
|
|
297
240
|
},
|
|
298
241
|
// A command can have side effects, so the kernel must serialize it with every other tool call.
|
|
299
242
|
isConcurrencySafe: () => false,
|
|
300
|
-
// Above the parameter ceiling on purpose: the SSH deadline has to fire first, so the model sees
|
|
301
|
-
//
|
|
243
|
+
// Above the parameter ceiling on purpose: the SSH deadline has to fire first, so the model sees our own
|
|
244
|
+
// `timedOut: true` result with its partial output instead of a killed tool call.
|
|
302
245
|
timeoutMs: 125_000,
|
|
303
246
|
async execute(args, context) {
|
|
304
247
|
try {
|
|
@@ -309,13 +252,10 @@ export function execTool(options) {
|
|
|
309
252
|
const mode = raw.mode === 'write' ? 'write' : 'read';
|
|
310
253
|
const command = typeof raw.command === 'string' ? raw.command : null;
|
|
311
254
|
if (command === null) {
|
|
312
|
-
return {
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
hint: '传一条完整的命令行字符串。 / Pass one complete command-line string.',
|
|
317
|
-
}),
|
|
318
|
-
};
|
|
255
|
+
return refusal(toolError('INVALID_INPUT', 'command 必须是非空字符串 / command must be a non-empty string', {
|
|
256
|
+
retryable: false,
|
|
257
|
+
hint: '传一条完整的命令行字符串。 / Pass one complete command-line string.',
|
|
258
|
+
}));
|
|
319
259
|
}
|
|
320
260
|
if (command.length > COMMAND_LIMIT)
|
|
321
261
|
return commandTooLong();
|
|
@@ -336,8 +276,8 @@ export function execTool(options) {
|
|
|
336
276
|
}
|
|
337
277
|
const timeoutMs = boundedInt(raw.timeoutMs, TIMEOUT_DEFAULT_MS, TIMEOUT_MIN_MS, TIMEOUT_MAX_MS);
|
|
338
278
|
const maxBytes = boundedInt(raw.maxBytes, MAX_BYTES_DEFAULT, MAX_BYTES_MIN, MAX_BYTES_MAX);
|
|
339
|
-
// The runtimes map is populated by `init`, so it must run before the lookup (
|
|
340
|
-
//
|
|
279
|
+
// The runtimes map is populated by `init`, so it must run before the lookup (idempotent: the list tool awaits
|
|
280
|
+
// it on every call for the same reason).
|
|
341
281
|
await service.init?.();
|
|
342
282
|
const link = linkOf(service, id);
|
|
343
283
|
if (link === null)
|
|
@@ -352,17 +292,13 @@ export function execTool(options) {
|
|
|
352
292
|
label: safeText(view?.name, NAME_LIMIT) ?? safeText(id, ID_LIMIT) ?? 'host',
|
|
353
293
|
};
|
|
354
294
|
const started = Date.now();
|
|
355
|
-
const result = await link.ssh.exec(command, {
|
|
356
|
-
timeoutMs,
|
|
357
|
-
maxBytes: SSH_CAPTURE_BYTES,
|
|
358
|
-
signal: context?.signal,
|
|
359
|
-
});
|
|
295
|
+
const result = await link.ssh.exec(command, { timeoutMs, maxBytes: SSH_CAPTURE_BYTES, signal: context?.signal });
|
|
360
296
|
const durationMs = Math.max(0, Math.round(Date.now() - started));
|
|
361
297
|
return project(result, { host, mode, echo: bounded, durationMs, maxBytes });
|
|
362
298
|
}
|
|
363
299
|
catch (error) {
|
|
364
|
-
// A transport failure (or an abort) is a structured answer, not a throw: the model has to be
|
|
365
|
-
//
|
|
300
|
+
// A transport failure (or an abort) is a structured answer, not a throw: the model has to be able to report
|
|
301
|
+
// it, and the list tool already answers the same way.
|
|
366
302
|
logger.error?.('[dsh-remote-go] remote_exec failed:', error);
|
|
367
303
|
return { ok: false, error: serviceError(error) };
|
|
368
304
|
}
|