dsh-cmd-guard 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Lexical helpers. Pure string handling, no IO, no process access.
3
+ *
4
+ * Everything here is deliberately naive about shell grammar. The goal is not
5
+ * to emulate cmd.exe; it is to make sure that anything whose shape we cannot
6
+ * confidently read surfaces as an ask instead of sliding through as a pass.
7
+ */
8
+ /** Split into whitespace-separated tokens, keeping quoted runs intact. */
9
+ export function tokenize(cmd) {
10
+ const out = [];
11
+ let cur = '';
12
+ let quote = null;
13
+ let started = false;
14
+ for (const ch of cmd) {
15
+ if (quote !== null) {
16
+ if (ch === quote) {
17
+ quote = null;
18
+ continue;
19
+ }
20
+ cur += ch;
21
+ continue;
22
+ }
23
+ if (ch === '"' || ch === "'") {
24
+ quote = ch;
25
+ started = true;
26
+ continue;
27
+ }
28
+ // Newlines are separators, not whitespace inside a token. A measured
29
+ // bypass: `echo hi\nrm -rf /` tokenised as ["echo", "hi\nrm", "-rf", "/"],
30
+ // so the head was `echo` and the rules layer never saw the delete. Inside
31
+ // quotes they are kept, because there they are data (see hasUnquotedNewline).
32
+ if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
33
+ if (started || cur.length > 0) {
34
+ out.push(cur);
35
+ cur = '';
36
+ started = false;
37
+ }
38
+ continue;
39
+ }
40
+ cur += ch;
41
+ }
42
+ if (started || cur.length > 0)
43
+ out.push(cur);
44
+ return out;
45
+ }
46
+ /**
47
+ * A newline outside quotes. Both shells treat it as a statement separator, so
48
+ * it chains exactly like `;` - but scanOperators covered only punctuation, and
49
+ * the chain therefore reached the rules layer as one command.
50
+ *
51
+ * Quoted newlines are data: `git commit -m "line one\nline two"` is one
52
+ * command, and treating it as two would be a false positive on every
53
+ * multi-line commit message.
54
+ */
55
+ export function hasUnquotedNewline(cmd) {
56
+ let quote = null;
57
+ for (const ch of cmd) {
58
+ if (quote !== null) {
59
+ if (ch === quote)
60
+ quote = null;
61
+ continue;
62
+ }
63
+ if (ch === '"' || ch === "'") {
64
+ quote = ch;
65
+ continue;
66
+ }
67
+ if (ch === '\n' || ch === '\r')
68
+ return true;
69
+ }
70
+ return false;
71
+ }
72
+ /**
73
+ * Operators found outside quotes. Chaining is what hides a second stage
74
+ * behind a harmless first one, so any operator at all is worth surfacing.
75
+ */
76
+ export function scanOperators(cmd) {
77
+ const found = [];
78
+ let quote = null;
79
+ for (let i = 0; i < cmd.length; i++) {
80
+ const ch = cmd[i];
81
+ if (ch === undefined)
82
+ break;
83
+ if (quote !== null) {
84
+ if (ch === quote)
85
+ quote = null;
86
+ continue;
87
+ }
88
+ if (ch === '"' || ch === "'") {
89
+ quote = ch;
90
+ continue;
91
+ }
92
+ const two = cmd.slice(i, i + 2);
93
+ if (two === '&&' || two === '||' || two === '^|' || two === '^&' || two === '>>') {
94
+ found.push(two);
95
+ i += 1;
96
+ continue;
97
+ }
98
+ if (ch === '|' || ch === '&' || ch === ';' || ch === '>' || ch === '<') {
99
+ found.push(ch);
100
+ }
101
+ }
102
+ return found;
103
+ }
104
+ /**
105
+ * Command substitution: `$(...)` and paired backticks.
106
+ *
107
+ * Measured bypass: `echo $(rm -rf /)` and a backtick-wrapped `rm -rf /` both
108
+ * passed with nothing objecting. Substitution was never in scanOperators, and
109
+ * the rules layer only ever reads tokens[0], so the inner command was invisible
110
+ * to every layer.
111
+ *
112
+ * Single quotes suppress substitution in POSIX shells, so their contents are
113
+ * skipped. Double quotes do not, so they are not.
114
+ *
115
+ * Backticks are ambiguous: in PowerShell a lone backtick is an escape
116
+ * (`"a`tb"` is a tab). A backtick with a closing partner is treated as
117
+ * substitution, a lone one as an escape. That keeps normal PowerShell strings
118
+ * from being flagged while closing the POSIX channel.
119
+ */
120
+ export function hasCommandSubstitution(cmd) {
121
+ let inSingle = false;
122
+ for (let i = 0; i < cmd.length; i++) {
123
+ const ch = cmd[i];
124
+ if (ch === undefined)
125
+ break;
126
+ if (inSingle) {
127
+ if (ch === "'")
128
+ inSingle = false;
129
+ continue;
130
+ }
131
+ if (ch === "'") {
132
+ inSingle = true;
133
+ continue;
134
+ }
135
+ if (ch === '$' && cmd[i + 1] === '(')
136
+ return true;
137
+ if (ch === '`') {
138
+ if (cmd.indexOf('`', i + 1) !== -1)
139
+ return true;
140
+ i += 1; // lone backtick: escape the next character and move on
141
+ }
142
+ }
143
+ return false;
144
+ }
145
+ /**
146
+ * Bodies of every command substitution, so the split layer can run the hard
147
+ * rules against the inner text. Without this, `echo $(rm -rf /)` would only
148
+ * ever be an ask; the delete itself is what should decide the verdict.
149
+ */
150
+ export function substitutionBodies(cmd) {
151
+ const out = [];
152
+ let inSingle = false;
153
+ for (let i = 0; i < cmd.length; i++) {
154
+ const ch = cmd[i];
155
+ if (ch === undefined)
156
+ break;
157
+ if (inSingle) {
158
+ if (ch === "'")
159
+ inSingle = false;
160
+ continue;
161
+ }
162
+ if (ch === "'") {
163
+ inSingle = true;
164
+ continue;
165
+ }
166
+ if (ch === '$' && cmd[i + 1] === '(') {
167
+ let depth = 1;
168
+ let j = i + 2;
169
+ for (; j < cmd.length; j++) {
170
+ const c = cmd[j];
171
+ if (c === '(')
172
+ depth += 1;
173
+ else if (c === ')') {
174
+ depth -= 1;
175
+ if (depth === 0)
176
+ break;
177
+ }
178
+ }
179
+ out.push(cmd.slice(i + 2, j));
180
+ i = j;
181
+ continue;
182
+ }
183
+ if (ch === '`') {
184
+ const close = cmd.indexOf('`', i + 1);
185
+ if (close === -1) {
186
+ i += 1;
187
+ continue;
188
+ }
189
+ out.push(cmd.slice(i + 1, close));
190
+ i = close;
191
+ }
192
+ }
193
+ return out;
194
+ }
195
+ /**
196
+ * Split into the individual statements a chain would run. Used only to escalate
197
+ * a hard deny that sits behind a separator: `git status && rm -rf /` used to be
198
+ * an ask from the split layer, which hid the deny the rules layer would have
199
+ * produced for the second statement. Deny must win.
200
+ *
201
+ * Quotes are honoured, so `echo "a;b"` stays one segment.
202
+ */
203
+ export function splitSegments(cmd) {
204
+ const out = [];
205
+ let cur = '';
206
+ let quote = null;
207
+ for (let i = 0; i < cmd.length; i++) {
208
+ const ch = cmd[i];
209
+ if (ch === undefined)
210
+ break;
211
+ if (quote !== null) {
212
+ cur += ch;
213
+ if (ch === quote)
214
+ quote = null;
215
+ continue;
216
+ }
217
+ if (ch === '"' || ch === "'") {
218
+ quote = ch;
219
+ cur += ch;
220
+ continue;
221
+ }
222
+ if (ch === '\n' ||
223
+ ch === '\r' ||
224
+ ch === ';' ||
225
+ ch === '|' ||
226
+ ch === '&' ||
227
+ ch === '>' ||
228
+ ch === '<') {
229
+ out.push(cur);
230
+ cur = '';
231
+ continue;
232
+ }
233
+ cur += ch;
234
+ }
235
+ out.push(cur);
236
+ return out.map((s) => s.trim()).filter((s) => s.length > 0);
237
+ }
238
+ /**
239
+ * Process substitution. The path handed to the tool is an anonymous pipe that
240
+ * never exists on disk, so no provenance check can apply to it. Checked with
241
+ * quotes ignored on purpose: it is legal inside a quoted shell argument.
242
+ */
243
+ export function hasProcessSubstitution(cmd) {
244
+ return /[<>]\(/.test(cmd);
245
+ }
246
+ /**
247
+ * A caret wedged inside a word (`d^e^l`). Outside the word, `^|` is an
248
+ * escaped operator and belongs to the split layer instead.
249
+ */
250
+ export function hasCaretInsideWord(cmd) {
251
+ return /[A-Za-z0-9_]+\^[A-Za-z0-9_]+/.test(cmd);
252
+ }
253
+ /** Forward slashes, lowercase. Used for every path comparison. */
254
+ export function normalizePath(p) {
255
+ return p.replace(/\\/g, '/').toLowerCase();
256
+ }
257
+ /** Last segment of a Windows or POSIX path, quotes already stripped. */
258
+ export function baseName(p) {
259
+ const parts = p.split(/[\\/]+/);
260
+ return parts[parts.length - 1] ?? p;
261
+ }
262
+ /** True when `p` is `root` itself or sits underneath it. */
263
+ export function isInsideWorkspace(p, root) {
264
+ const target = normalizePath(p);
265
+ const base = normalizePath(root).replace(/\/+$/, '');
266
+ return target === base || target.startsWith(base + '/');
267
+ }
268
+ /** `C:\x`, `C:/x`, `\\server\share`, `/usr/x`. */
269
+ export function isAbsolutePath(p) {
270
+ return /^[a-z]:[\\/]/i.test(p) || /^\\\\/.test(p) || p.startsWith('/');
271
+ }
272
+ /** Any `..` segment, which may climb above the workspace root. */
273
+ export function hasParentEscape(p) {
274
+ return p.split(/[\\/]+/).includes('..');
275
+ }
276
+ /** Roots any process on the machine can write to. Not a provenance claim. */
277
+ export function isVolatilePath(p) {
278
+ return /%temp%|%tmp%/i.test(p) || /appdata[\\/]local[\\/]temp/i.test(p);
279
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The seam between DSH and the parser.
3
+ *
4
+ * Everything here is driven by the shipped type declarations, not by memory:
5
+ *
6
+ * exec.name string the tool name (`bash`, `pwsh`, ...)
7
+ * exec.arguments unknown already-parsed arguments
8
+ * ctx.tools.guard(ToolGuard) (exec) => string | undefined, deny only
9
+ * ctx.on('tools/pre-execute') waterfall (exec, next) => PreToolDecision
10
+ *
11
+ * Two facts shape the design:
12
+ *
13
+ * 1. `guard` has no allow exit. It runs after every pre-execute listener and
14
+ * after approval resolves, so a denial registered there cannot be softened
15
+ * by listener ordering or by an operator saying yes. That is the right home
16
+ * for hard rules and the wrong home for anything a human may override.
17
+ *
18
+ * 2. `pre-execute` is a waterfall returning a discriminated union. A handler
19
+ * that returns the wrong shape is not rejected - the registry simply does
20
+ * not see a decision. Getting this shape wrong means the gate silently
21
+ * does nothing, so the shape is validated in tests, not assumed.
22
+ *
23
+ * `cancel` is deliberately never produced. It means "the operator pressed
24
+ * stop", which is not a statement this plugin is entitled to make.
25
+ */
26
+ import type { GuardResult } from './types.js';
27
+ import type { GuardInput } from './types.js';
28
+ /** The framework's four-state pre-dispatch decision, mirrored structurally. */
29
+ export type PreToolDecision = {
30
+ readonly kind: 'allow';
31
+ } | {
32
+ readonly kind: 'deny';
33
+ readonly reason: string;
34
+ } | {
35
+ readonly kind: 'cancel';
36
+ } | {
37
+ readonly kind: 'ask';
38
+ readonly reason?: string;
39
+ readonly displayReason?: {
40
+ readonly en: string;
41
+ readonly [locale: string]: string;
42
+ };
43
+ };
44
+ /**
45
+ * Runtime shape check. Discriminant plus required field per branch. Nothing
46
+ * else - anything stricter would reject a decision the registry accepts, and
47
+ * anything looser would let a typo through as a no-op gate.
48
+ */
49
+ export declare function isPreToolDecision(value: unknown): value is PreToolDecision;
50
+ /** The subset of ToolExecution this module reads. */
51
+ export interface ExecutionLike {
52
+ readonly name?: unknown;
53
+ readonly arguments?: unknown;
54
+ }
55
+ /** What the mount decided to do with one call. */
56
+ export type Mapping = {
57
+ readonly kind: 'call';
58
+ readonly input: GuardInput;
59
+ } | {
60
+ readonly kind: 'skip';
61
+ readonly reason: string;
62
+ };
63
+ /**
64
+ * Turn one dispatched call into parser input, or explain why it is not one.
65
+ *
66
+ * Key order matters: the known command keys are tried before the unknown-tool
67
+ * scan, so a tool that carries `command` is never judged by a heuristic.
68
+ */
69
+ export declare function toGuardInput(exec: ExecutionLike): Mapping;
70
+ /**
71
+ * Adapter for `ctx.tools.guard`, which can only deny.
72
+ *
73
+ * Returning a reason denies; returning undefined leaves the call untouched.
74
+ * A pass therefore becomes undefined rather than an active allow, because this
75
+ * mount has no way to grant anything - and claiming otherwise is how a guard
76
+ * ends up believing it widened a permission it never held.
77
+ */
78
+ export declare function toHardDeny(result: GuardResult): string | undefined;
79
+ /**
80
+ * Adapter for the `tools/pre-execute` waterfall.
81
+ *
82
+ * `null` means "defer": the handler must return `next()` instead of a decision,
83
+ * otherwise every listener mounted after this one is skipped.
84
+ */
85
+ export declare function toDecision(result: GuardResult): PreToolDecision | null;
@@ -0,0 +1,130 @@
1
+ import { DATA_KEYS, EXEC_TOOLS } from './entry.js';
2
+ import { looksLikeCommandString } from './shape.js';
3
+ /** Argument keys a command has been seen under, most specific first. */
4
+ const COMMAND_KEYS = ['command', 'cmd', 'script', 'commandLine', 'command_line'];
5
+ /** Argument keys a stated intent has been seen under. */
6
+ const INTENT_KEYS = ['description', 'why', 'reason', 'intent', 'purpose'];
7
+ /** Values longer than this are documents; a command line is not 2 KB. */
8
+ // The exclusion itself lives in entry.ts so the library entry point and the
9
+ // mount agree. See the note there; the residual risk is stated in the README.
10
+ const MAX_COMMAND_LENGTH = 2048;
11
+ /**
12
+ * Runtime shape check. Discriminant plus required field per branch. Nothing
13
+ * else - anything stricter would reject a decision the registry accepts, and
14
+ * anything looser would let a typo through as a no-op gate.
15
+ */
16
+ export function isPreToolDecision(value) {
17
+ if (typeof value !== 'object' || value === null)
18
+ return false;
19
+ const v = value;
20
+ switch (v.kind) {
21
+ case 'allow':
22
+ case 'cancel':
23
+ return true;
24
+ case 'deny':
25
+ return typeof v.reason === 'string' && v.reason.length > 0;
26
+ case 'ask':
27
+ return v.reason === undefined || typeof v.reason === 'string';
28
+ default:
29
+ return false;
30
+ }
31
+ }
32
+ function asRecord(value) {
33
+ return typeof value === 'object' && value !== null ? value : {};
34
+ }
35
+ function firstString(args, keys) {
36
+ for (const key of keys) {
37
+ const v = args[key];
38
+ if (typeof v === 'string' && v.trim().length > 0)
39
+ return v;
40
+ }
41
+ return undefined;
42
+ }
43
+ /**
44
+ * Turn one dispatched call into parser input, or explain why it is not one.
45
+ *
46
+ * Key order matters: the known command keys are tried before the unknown-tool
47
+ * scan, so a tool that carries `command` is never judged by a heuristic.
48
+ */
49
+ export function toGuardInput(exec) {
50
+ if (typeof exec.name !== 'string' || exec.name.length === 0) {
51
+ return { kind: 'skip', reason: 'call carries no tool name' };
52
+ }
53
+ const name = exec.name;
54
+ const args = asRecord(exec.arguments);
55
+ const intent = firstString(args, INTENT_KEYS);
56
+ // Every populated command key, not just the one that wins. One call
57
+ // carrying both `command` and `cmd` audits one string and may run the
58
+ // other; the entry layer turns that into an ask.
59
+ const populated = COMMAND_KEYS.filter((k) => {
60
+ const v = args[k];
61
+ return typeof v === 'string' && v.trim().length > 0;
62
+ });
63
+ for (const key of COMMAND_KEYS) {
64
+ const raw = args[key];
65
+ if (typeof raw === 'string' && raw.trim().length > 0) {
66
+ return {
67
+ kind: 'call',
68
+ input: { cmd: raw, why: intent, tool: name, commandSource: key, commandKeys: populated },
69
+ };
70
+ }
71
+ }
72
+ // An empty `command` on a known shell tool is its own problem, but it is not
73
+ // this module's verdict to make: the tool itself will reject it.
74
+ if (EXEC_TOOLS.has(name.toLowerCase())) {
75
+ return { kind: 'skip', reason: `"${name}" carries no command argument` };
76
+ }
77
+ // Unknown tool: scan string arguments that are not payload data for a
78
+ // command shape.
79
+ for (const [key, value] of Object.entries(args)) {
80
+ if (typeof value !== 'string')
81
+ continue;
82
+ if (DATA_KEYS.has(key.toLowerCase()))
83
+ continue;
84
+ if (value.length > MAX_COMMAND_LENGTH)
85
+ continue;
86
+ if (!looksLikeCommandString(value))
87
+ continue;
88
+ return {
89
+ kind: 'call',
90
+ input: { cmd: value, why: intent, tool: name, commandSource: key },
91
+ };
92
+ }
93
+ return { kind: 'skip', reason: `"${name}" carries no command-shaped argument` };
94
+ }
95
+ /**
96
+ * Adapter for `ctx.tools.guard`, which can only deny.
97
+ *
98
+ * Returning a reason denies; returning undefined leaves the call untouched.
99
+ * A pass therefore becomes undefined rather than an active allow, because this
100
+ * mount has no way to grant anything - and claiming otherwise is how a guard
101
+ * ends up believing it widened a permission it never held.
102
+ */
103
+ export function toHardDeny(result) {
104
+ if (result.verdict !== 'deny')
105
+ return undefined;
106
+ return `[${result.code}] ${result.reason}`;
107
+ }
108
+ /**
109
+ * Adapter for the `tools/pre-execute` waterfall.
110
+ *
111
+ * `null` means "defer": the handler must return `next()` instead of a decision,
112
+ * otherwise every listener mounted after this one is skipped.
113
+ */
114
+ export function toDecision(result) {
115
+ switch (result.verdict) {
116
+ case 'pass':
117
+ return null;
118
+ case 'deny':
119
+ return { kind: 'deny', reason: `[${result.code}] ${result.reason}` };
120
+ case 'ask':
121
+ return {
122
+ kind: 'ask',
123
+ reason: `[${result.code}] ${result.reason}`,
124
+ displayReason: {
125
+ en: `Allow this command? ${result.code}: ${result.reason}`,
126
+ zh: `是否允许执行该命令?${result.code}:${result.reason}`,
127
+ },
128
+ };
129
+ }
130
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Fold the spellings a human reads as ASCII back to ASCII.
3
+ *
4
+ * Measured evasions that no layer saw as a verb, because each one contains a
5
+ * character the comparison was not written for:
6
+ *
7
+ * rm -rf / fullwidth latin (NFKC folds it to "rm")
8
+ * rm -rf / zero-width space after the verb
9
+ * r-m -rf / soft hyphen inside the verb
10
+ * rm -rf / junk NUL standing in for a separator
11
+ *
12
+ * None of these is a trick a shell performs; they are characters that render
13
+ * as nothing or as their ASCII twin. Folding is the whole fix, and it has to
14
+ * happen before tokenizing, since a tokenizer that has never met U+200B will
15
+ * happily return a token that only looks like "rm".
16
+ */
17
+ export declare function canonicalCommand(cmd: string | null | undefined): string;
18
+ /** `$IFS` and `${IFS}` are the field separator, i.e. whitespace. */
19
+ export declare function expandIfs(value: string): string;
20
+ /**
21
+ * A token with quoting removed but structure intact.
22
+ *
23
+ * This is what path comparisons read. Quotes are syntax rather than content,
24
+ * so `"C:\Windows"` and `C:\Windows` are the same target; backslashes are not,
25
+ * so they stay.
26
+ */
27
+ export declare function plainToken(token: string): string;
28
+ /**
29
+ * A command word with the ways of spelling it without looking like itself
30
+ * undone: `r\m`, `r""m`, `p^ython`, `rm$IFS-rf`.
31
+ *
32
+ * Applied to the head only. A verb never contains a path separator, so the
33
+ * escape rule cannot damage anything that matters here, and it cannot damage
34
+ * a path because paths are never passed through this function.
35
+ */
36
+ export declare function deobfuscateToken(token: string): string;
37
+ /**
38
+ * Programs that run the rest of the line rather than doing work themselves.
39
+ *
40
+ * `start /b del ...` and `call del ...` on Windows, `sudo`/`nice`/`timeout`
41
+ * onwards on POSIX. Each hides the real head one token further along, and the
42
+ * rules layer never looked past the first.
43
+ */
44
+ export declare const WRAPPERS: ReadonlySet<string>;
45
+ /**
46
+ * The verb a token spells, with the ways of spelling it without looking like
47
+ * itself undone, and with any path stripped.
48
+ *
49
+ * Measured evasions that reached a verb the head comparison never saw:
50
+ * `./rm -rf /`, `/bin/rm -rf /`, `rm.exe -rf C:\`, and the full path form.
51
+ * The verb is the last component; where it lives is not part of its identity.
52
+ */
53
+ export declare function stemVerb(token: string): string;
54
+ /** Is this token one of the words that decides what happens to a path? */
55
+ export declare function isHuntVerb(token: string): boolean;
56
+ export declare function headTokens(tokens: readonly string[]): string[];
57
+ /**
58
+ * Effective tokens: separators expanded, wrappers stripped, and a quoted
59
+ * payload re-tokenized so `eval "rm -rf /"` is judged as `rm -rf /`.
60
+ */
61
+ export declare function effectiveTokens(cmd: string): string[];
62
+ /**
63
+ * Is any redirection target outside the workspace?
64
+ *
65
+ * `echo "const x = 1" > src/x.ts` is one command writing one relative file,
66
+ * and it was being asked as a chain. A redirect into a relative, non-escaping
67
+ * path is not a second stage. One into an absolute path, above the workspace,
68
+ * or into a volatile root is still worth surfacing.
69
+ *
70
+ * Returns true when the command has no readable target at all, so an
71
+ * unparseable redirect fails closed.
72
+ */
73
+ export declare function hasUnsafeRedirectTarget(cmd: string): boolean;