@aithorized/core 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/lifecycle/batch.d.ts +18 -0
- package/dist/lifecycle/batch.js +20 -0
- package/dist/lifecycle/preview.d.ts +41 -0
- package/dist/lifecycle/preview.js +60 -0
- package/dist/lifecycle/redact.d.ts +2 -0
- package/dist/lifecycle/redact.js +18 -4
- package/dist/policy/browser.d.ts +4 -0
- package/dist/policy/browser.js +2 -0
- package/dist/policy/command-analyzer.d.ts +5 -1
- package/dist/policy/command-analyzer.js +268 -38
- package/dist/policy/evaluate.js +38 -7
- package/dist/policy/explain.d.ts +50 -0
- package/dist/policy/explain.js +124 -0
- package/dist/policy/match.d.ts +13 -2
- package/dist/policy/match.js +48 -10
- package/dist/policy/packs.d.ts +23 -0
- package/dist/policy/packs.js +230 -0
- package/dist/policy/types.d.ts +22 -0
- package/package.json +1 -1
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
const SHELL_NOISE = new Set(['cd', 'echo', 'printf', 'export', 'set', 'unset', 'true', 'false', 'exit', 'return', 'test', '[']);
|
|
2
|
-
const SHELL_WRAPPERS = new Set(['sudo', 'env', 'nohup', 'time', 'command', 'nice', 'ionice']);
|
|
3
|
-
const SHELL_RUNTIMES = new Set(['python', 'python3', 'node', 'bash', 'sh', 'zsh', 'npx', 'tsx', 'uv', 'ruby', 'perl', 'php']);
|
|
4
|
-
const PIPE_FILTERS = new Set(['head', 'tail', 'wc', 'sort', 'uniq', 'tr', 'cut', 'tee', 'less', 'more', 'cat'
|
|
1
|
+
const SHELL_NOISE = new Set(['cd', 'echo', 'printf', 'export', 'set', 'unset', 'true', 'false', 'exit', 'return', 'test', '[', ':']);
|
|
2
|
+
const SHELL_WRAPPERS = new Set(['sudo', 'env', 'nohup', 'time', 'command', 'nice', 'ionice', 'exec']);
|
|
3
|
+
const SHELL_RUNTIMES = new Set(['python', 'python3', 'node', 'bash', 'sh', 'zsh', 'dash', 'ksh', 'npx', 'tsx', 'uv', 'ruby', 'perl', 'php']);
|
|
4
|
+
const PIPE_FILTERS = new Set(['head', 'tail', 'wc', 'sort', 'uniq', 'tr', 'cut', 'tee', 'less', 'more', 'cat']);
|
|
5
|
+
const EVAL_BUILTINS = new Set(['eval', 'source', '.']);
|
|
5
6
|
const READ_TOOLS = new Set(['cat', 'head', 'tail', 'less', 'more', 'grep', 'rg', 'find', 'ls', 'stat', 'read', 'get', 'list', 'psql', 'sqlite3']);
|
|
6
7
|
const WRITE_TOOLS = new Set(['cp', 'mv', 'tee', 'mkdir', 'touch', 'chmod', 'chown', 'ln', 'sed', 'awk', 'tar', 'unzip', 'zip']);
|
|
7
8
|
const DELETE_TOOLS = new Set(['rm', 'rmdir', 'unlink', 'shred']);
|
|
@@ -39,12 +40,150 @@ function dirnameOf(p) {
|
|
|
39
40
|
const dir = p.slice(0, idx);
|
|
40
41
|
return dir && dir !== '.' ? dir : null;
|
|
41
42
|
}
|
|
43
|
+
function normalizePath(raw) {
|
|
44
|
+
const unified = raw.replace(/\\/g, '/');
|
|
45
|
+
if (!unified.includes('/..') && !unified.includes('../') && !unified.includes('/./') && !unified.includes('//')) {
|
|
46
|
+
return unified;
|
|
47
|
+
}
|
|
48
|
+
const hasRoot = unified.startsWith('/');
|
|
49
|
+
const hasHome = unified.startsWith('~/');
|
|
50
|
+
const driveMatch = /^([A-Za-z]:)\//.exec(unified);
|
|
51
|
+
const prefix = hasHome ? '~/' : driveMatch ? `${driveMatch[1]}/` : hasRoot ? '/' : '';
|
|
52
|
+
const body = prefix ? unified.slice(prefix.length) : unified;
|
|
53
|
+
const parts = [];
|
|
54
|
+
for (const part of body.split('/')) {
|
|
55
|
+
if (!part || part === '.')
|
|
56
|
+
continue;
|
|
57
|
+
if (part === '..') {
|
|
58
|
+
if (parts.length > 0 && parts[parts.length - 1] !== '..') {
|
|
59
|
+
parts.pop();
|
|
60
|
+
}
|
|
61
|
+
else if (!hasRoot && !driveMatch) {
|
|
62
|
+
parts.push('..');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
parts.push(part);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return prefix + parts.join('/') || (hasRoot ? '/' : '.');
|
|
70
|
+
}
|
|
42
71
|
function isSensitive(p) {
|
|
43
|
-
return SENSITIVE_PATTERN.test(p
|
|
72
|
+
return SENSITIVE_PATTERN.test(normalizePath(p));
|
|
44
73
|
}
|
|
45
74
|
function isUrl(token) {
|
|
46
75
|
return /^(https?|s3|gs):\/\/\S+/i.test(token);
|
|
47
76
|
}
|
|
77
|
+
/** Extract nested subshell / process-substitution / backtick inner commands outside single quotes. */
|
|
78
|
+
function extractEmbeddedCommands(command) {
|
|
79
|
+
const embedded = [];
|
|
80
|
+
let inSingle = false;
|
|
81
|
+
let inDouble = false;
|
|
82
|
+
let unclosed = false;
|
|
83
|
+
for (let i = 0; i < command.length; i++) {
|
|
84
|
+
const ch = command[i] ?? '';
|
|
85
|
+
const next = command[i + 1] ?? '';
|
|
86
|
+
if (inSingle) {
|
|
87
|
+
if (ch === "'")
|
|
88
|
+
inSingle = false;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (ch === '\\' && i + 1 < command.length) {
|
|
92
|
+
i++;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (ch === "'" && !inDouble) {
|
|
96
|
+
inSingle = true;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (ch === '"') {
|
|
100
|
+
inDouble = !inDouble;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
// Backtick command substitution: `...`
|
|
104
|
+
if (ch === '`') {
|
|
105
|
+
let j = i + 1;
|
|
106
|
+
let inner = '';
|
|
107
|
+
let closed = false;
|
|
108
|
+
while (j < command.length) {
|
|
109
|
+
const c = command[j] ?? '';
|
|
110
|
+
if (c === '\\' && j + 1 < command.length) {
|
|
111
|
+
inner += command[j + 1] ?? '';
|
|
112
|
+
j += 2;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (c === '`') {
|
|
116
|
+
closed = true;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
inner += c;
|
|
120
|
+
j++;
|
|
121
|
+
}
|
|
122
|
+
if (closed) {
|
|
123
|
+
if (inner.trim())
|
|
124
|
+
embedded.push(inner.trim());
|
|
125
|
+
i = j;
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
unclosed = true;
|
|
129
|
+
if (inner.trim())
|
|
130
|
+
embedded.push(inner.trim());
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
// Balanced $(...), <(...), >(...)
|
|
136
|
+
if ((ch === '$' || ch === '<' || ch === '>') && next === '(') {
|
|
137
|
+
let depth = 1;
|
|
138
|
+
let j = i + 2;
|
|
139
|
+
let subSingle = false;
|
|
140
|
+
let subDouble = false;
|
|
141
|
+
while (j < command.length && depth > 0) {
|
|
142
|
+
const c = command[j] ?? '';
|
|
143
|
+
if (subSingle) {
|
|
144
|
+
if (c === "'")
|
|
145
|
+
subSingle = false;
|
|
146
|
+
}
|
|
147
|
+
else if (c === '\\' && j + 1 < command.length) {
|
|
148
|
+
j += 2;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
else if (c === "'" && !subDouble) {
|
|
152
|
+
subSingle = true;
|
|
153
|
+
}
|
|
154
|
+
else if (c === '"') {
|
|
155
|
+
subDouble = !subDouble;
|
|
156
|
+
}
|
|
157
|
+
else if (!subDouble) {
|
|
158
|
+
if (c === '(')
|
|
159
|
+
depth++;
|
|
160
|
+
else if (c === ')')
|
|
161
|
+
depth--;
|
|
162
|
+
}
|
|
163
|
+
j++;
|
|
164
|
+
}
|
|
165
|
+
if (depth === 0) {
|
|
166
|
+
const inner = command.slice(i + 2, j - 1).trim();
|
|
167
|
+
if (inner)
|
|
168
|
+
embedded.push(inner);
|
|
169
|
+
i = j - 1;
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
unclosed = true;
|
|
173
|
+
const inner = command.slice(i + 2).trim();
|
|
174
|
+
if (inner)
|
|
175
|
+
embedded.push(inner);
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (inSingle || inDouble)
|
|
181
|
+
unclosed = true;
|
|
182
|
+
return { embedded, unclosed };
|
|
183
|
+
}
|
|
184
|
+
function hasVarExpansion(token) {
|
|
185
|
+
return /\$(?:[A-Za-z_][A-Za-z0-9_]*|\{[^}]+\})/.test(token);
|
|
186
|
+
}
|
|
48
187
|
/** Split command string into segments on `&&`, `||`, `;`, `|`, `\n` outside quotes. */
|
|
49
188
|
export function splitShellSegments(command) {
|
|
50
189
|
const out = [];
|
|
@@ -120,6 +259,11 @@ export function tokenizeSegment(segment) {
|
|
|
120
259
|
}
|
|
121
260
|
continue;
|
|
122
261
|
}
|
|
262
|
+
if (ch === '\\' && i + 1 < segment.length) {
|
|
263
|
+
buf += next;
|
|
264
|
+
i++;
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
123
267
|
if (ch === '"' || ch === "'") {
|
|
124
268
|
quote = ch;
|
|
125
269
|
continue;
|
|
@@ -153,7 +297,7 @@ function classifyFileToken(token) {
|
|
|
153
297
|
return 'path';
|
|
154
298
|
return 'none';
|
|
155
299
|
}
|
|
156
|
-
/** Analyze a shell command string for tools, subcommands, paths, files, URLs, flags, and
|
|
300
|
+
/** Analyze a shell command string for tools, subcommands, paths, files, URLs, flags, intents, and evasion signals. */
|
|
157
301
|
export function analyzeCommand(command, depth = 0) {
|
|
158
302
|
const tools = [];
|
|
159
303
|
const pathMap = new Map();
|
|
@@ -161,15 +305,16 @@ export function analyzeCommand(command, depth = 0) {
|
|
|
161
305
|
const urlSet = new Set();
|
|
162
306
|
const flagSet = new Set();
|
|
163
307
|
const intentSet = new Set();
|
|
308
|
+
const evasionSet = new Set();
|
|
164
309
|
const recordPath = (rawPath) => {
|
|
165
|
-
const
|
|
166
|
-
if (!
|
|
310
|
+
const normalized = normalizePath(rawPath).replace(/[\\/]+$/, '') || '/';
|
|
311
|
+
if (!normalized || normalized === '.' || normalized === '~' || normalized === '/dev' || normalized === '/dev/null')
|
|
167
312
|
return;
|
|
168
|
-
if (!pathMap.has(
|
|
169
|
-
pathMap.set(
|
|
313
|
+
if (!pathMap.has(normalized))
|
|
314
|
+
pathMap.set(normalized, { path: normalized, sensitive: isSensitive(normalized) });
|
|
170
315
|
};
|
|
171
316
|
const recordFile = (rawFile, access) => {
|
|
172
|
-
const cleaned = rawFile.replace(/^@/, '');
|
|
317
|
+
const cleaned = normalizePath(rawFile.replace(/^@/, ''));
|
|
173
318
|
if (!cleaned || cleaned === '/dev/null')
|
|
174
319
|
return;
|
|
175
320
|
const existing = fileMap.get(cleaned);
|
|
@@ -192,6 +337,9 @@ export function analyzeCommand(command, depth = 0) {
|
|
|
192
337
|
const t = unquote(raw);
|
|
193
338
|
if (!t || t === '/dev/null')
|
|
194
339
|
return;
|
|
340
|
+
if (hasVarExpansion(t)) {
|
|
341
|
+
evasionSet.add('dynamic_var_expansion');
|
|
342
|
+
}
|
|
195
343
|
if (isUrl(t)) {
|
|
196
344
|
urlSet.add(t);
|
|
197
345
|
intentSet.add('network');
|
|
@@ -218,14 +366,19 @@ export function analyzeCommand(command, depth = 0) {
|
|
|
218
366
|
flagSet.add(fl);
|
|
219
367
|
for (const i of sub.intents)
|
|
220
368
|
intentSet.add(i);
|
|
369
|
+
for (const ev of sub.evasionSignals)
|
|
370
|
+
evasionSet.add(ev);
|
|
221
371
|
};
|
|
222
|
-
// Extract $(...)
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
372
|
+
// Extract $(...), `...`, <(...), >(...) embedded commands recursively (bounded depth)
|
|
373
|
+
const { embedded, unclosed } = extractEmbeddedCommands(command);
|
|
374
|
+
if (unclosed)
|
|
375
|
+
evasionSet.add('unclosed_quote');
|
|
376
|
+
for (const subCmd of embedded) {
|
|
377
|
+
if (depth < 3) {
|
|
378
|
+
mergeSubAnalysis(analyzeCommand(subCmd, depth + 1));
|
|
379
|
+
}
|
|
380
|
+
else {
|
|
381
|
+
evasionSet.add('max_depth_exceeded');
|
|
229
382
|
}
|
|
230
383
|
}
|
|
231
384
|
for (const { segment, piped } of splitShellSegments(command)) {
|
|
@@ -237,7 +390,7 @@ export function analyzeCommand(command, depth = 0) {
|
|
|
237
390
|
inspectToken((tokens[idx] ?? '').slice(eqPos + 1), 'unknown');
|
|
238
391
|
idx++;
|
|
239
392
|
}
|
|
240
|
-
// Strip sudo / env / nohup wrappers
|
|
393
|
+
// Strip sudo / env / nohup / exec wrappers
|
|
241
394
|
while (idx < tokens.length && SHELL_WRAPPERS.has(basenameOf(tokens[idx] ?? '').toLowerCase())) {
|
|
242
395
|
const wrapperName = basenameOf(tokens[idx] ?? '').toLowerCase();
|
|
243
396
|
if (wrapperName === 'sudo')
|
|
@@ -248,24 +401,13 @@ export function analyzeCommand(command, depth = 0) {
|
|
|
248
401
|
idx++;
|
|
249
402
|
}
|
|
250
403
|
}
|
|
251
|
-
|
|
252
|
-
if (!headRaw)
|
|
253
|
-
continue;
|
|
254
|
-
const headBase = basenameOf(headRaw).toLowerCase();
|
|
255
|
-
// Handle `cd <dir>` by recording its path, then skip noise
|
|
256
|
-
if (headBase === 'cd') {
|
|
257
|
-
const target = tokens[idx + 1];
|
|
258
|
-
if (target)
|
|
259
|
-
inspectToken(target, 'read');
|
|
260
|
-
continue;
|
|
261
|
-
}
|
|
262
|
-
if (SHELL_NOISE.has(headBase))
|
|
263
|
-
continue;
|
|
264
|
-
// Handle redirections across the segment
|
|
404
|
+
// Parse redirections BEFORE checking SHELL_NOISE so `echo ... >> ~/.ssh/authorized_keys` is never missed (PG-02).
|
|
265
405
|
const cleanTokens = [];
|
|
406
|
+
let hadWriteRedir = false;
|
|
407
|
+
let hadAnyRedir = false;
|
|
266
408
|
for (let i = idx; i < tokens.length; i++) {
|
|
267
409
|
const tok = tokens[i] ?? '';
|
|
268
|
-
const redirMatch = tok.match(/^(?:\d
|
|
410
|
+
const redirMatch = tok.match(/^(?:(?:\d*|&))(>>|>|<)(.*)$/);
|
|
269
411
|
if (redirMatch) {
|
|
270
412
|
const op = redirMatch[1];
|
|
271
413
|
const inlineTarget = redirMatch[2];
|
|
@@ -274,8 +416,14 @@ export function analyzeCommand(command, depth = 0) {
|
|
|
274
416
|
i++;
|
|
275
417
|
if (target && target !== '/dev/null' && !target.startsWith('&')) {
|
|
276
418
|
const access = op === '<' ? 'read' : 'write';
|
|
277
|
-
|
|
419
|
+
const unquotedTarget = unquote(target);
|
|
420
|
+
if (hasVarExpansion(unquotedTarget))
|
|
421
|
+
evasionSet.add('dynamic_var_expansion');
|
|
422
|
+
recordFile(unquotedTarget, access);
|
|
278
423
|
intentSet.add(access === 'read' ? 'read' : 'write');
|
|
424
|
+
hadAnyRedir = true;
|
|
425
|
+
if (access === 'write')
|
|
426
|
+
hadWriteRedir = true;
|
|
279
427
|
}
|
|
280
428
|
continue;
|
|
281
429
|
}
|
|
@@ -284,15 +432,92 @@ export function analyzeCommand(command, depth = 0) {
|
|
|
284
432
|
const cmdToken = cleanTokens[0];
|
|
285
433
|
if (!cmdToken)
|
|
286
434
|
continue;
|
|
435
|
+
if (hasVarExpansion(cmdToken)) {
|
|
436
|
+
evasionSet.add('dynamic_command');
|
|
437
|
+
}
|
|
287
438
|
const cmdName = basenameOf(cmdToken);
|
|
288
439
|
const cmdLower = cmdName.toLowerCase();
|
|
440
|
+
// Handle `cd <dir>` by recording its path, then skip noise unless redirections occurred.
|
|
441
|
+
if (cmdLower === 'cd') {
|
|
442
|
+
const target = cleanTokens[1];
|
|
443
|
+
if (target)
|
|
444
|
+
inspectToken(target, 'read');
|
|
445
|
+
if (!hadAnyRedir)
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
if (SHELL_NOISE.has(cmdLower)) {
|
|
449
|
+
if (hadWriteRedir) {
|
|
450
|
+
tools.push({ name: cmdName, primary: true, glob: `*${cmdName}*` });
|
|
451
|
+
}
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
// Detect `eval` / `source` / `.` dynamic execution (PG-03)
|
|
455
|
+
if (EVAL_BUILTINS.has(cmdLower)) {
|
|
456
|
+
intentSet.add('exec');
|
|
457
|
+
evasionSet.add('eval_or_source');
|
|
458
|
+
const rest = cleanTokens.slice(1).join(' ');
|
|
459
|
+
if (rest && depth < 3) {
|
|
460
|
+
mergeSubAnalysis(analyzeCommand(rest, depth + 1));
|
|
461
|
+
}
|
|
462
|
+
tools.push({ name: cmdName, primary: true, glob: `*${cmdName}*` });
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
// Handle `xargs <cmd ...>` by analyzing the executed target command (PG-03)
|
|
466
|
+
if (cmdLower === 'xargs') {
|
|
467
|
+
intentSet.add('exec');
|
|
468
|
+
let targetIdx = 1;
|
|
469
|
+
while (targetIdx < cleanTokens.length && (cleanTokens[targetIdx] ?? '').startsWith('-')) {
|
|
470
|
+
const fl = cleanTokens[targetIdx] ?? '';
|
|
471
|
+
flagSet.add(fl);
|
|
472
|
+
targetIdx++;
|
|
473
|
+
if (['-I', '-L', '-n', '-P', '-d', '-E', '-s'].includes(fl) && targetIdx < cleanTokens.length) {
|
|
474
|
+
targetIdx++;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
const targetCmd = cleanTokens.slice(targetIdx).join(' ');
|
|
478
|
+
if (targetCmd && depth < 3) {
|
|
479
|
+
mergeSubAnalysis(analyzeCommand(targetCmd, depth + 1));
|
|
480
|
+
}
|
|
481
|
+
else {
|
|
482
|
+
evasionSet.add('xargs_dynamic');
|
|
483
|
+
}
|
|
484
|
+
tools.push({ name: 'xargs', primary: true, glob: '*xargs*' });
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
// Handle `find ... -exec <cmd> ... \;` (PG-03)
|
|
488
|
+
if (cmdLower === 'find') {
|
|
489
|
+
const execIdx = cleanTokens.findIndex((t) => t === '-exec' || t === '-execdir' || t === '-ok');
|
|
490
|
+
if (execIdx !== -1) {
|
|
491
|
+
intentSet.add('exec');
|
|
492
|
+
const execTokens = [];
|
|
493
|
+
for (let j = execIdx + 1; j < cleanTokens.length; j++) {
|
|
494
|
+
const tok = cleanTokens[j] ?? '';
|
|
495
|
+
if (tok === ';' || tok === '+')
|
|
496
|
+
break;
|
|
497
|
+
execTokens.push(tok);
|
|
498
|
+
}
|
|
499
|
+
if (execTokens.length > 0 && depth < 3) {
|
|
500
|
+
mergeSubAnalysis(analyzeCommand(execTokens.join(' '), depth + 1));
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
// Detect piping into a shell/runtime interpreter (e.g. `base64 -d | sh`, `curl ... | bash`)
|
|
505
|
+
if (piped && SHELL_RUNTIMES.has(cmdLower)) {
|
|
506
|
+
evasionSet.add('pipe_to_interpreter');
|
|
507
|
+
intentSet.add('exec');
|
|
508
|
+
}
|
|
289
509
|
// Handle `bash -c "..."` / `sh -c "..."` inline scripts recursively
|
|
290
|
-
if (
|
|
510
|
+
if (cmdLower === 'bash' || cmdLower === 'sh' || cmdLower === 'zsh' || cmdLower === 'dash' || cmdLower === 'ksh') {
|
|
291
511
|
const cIdx = cleanTokens.indexOf('-c');
|
|
292
512
|
const inlineScript = cIdx !== -1 ? cleanTokens[cIdx + 1] : undefined;
|
|
293
513
|
if (inlineScript) {
|
|
294
514
|
intentSet.add('exec');
|
|
295
|
-
|
|
515
|
+
if (depth < 3) {
|
|
516
|
+
mergeSubAnalysis(analyzeCommand(inlineScript, depth + 1));
|
|
517
|
+
}
|
|
518
|
+
else {
|
|
519
|
+
evasionSet.add('max_depth_exceeded');
|
|
520
|
+
}
|
|
296
521
|
continue;
|
|
297
522
|
}
|
|
298
523
|
}
|
|
@@ -355,6 +580,9 @@ export function analyzeCommand(command, depth = 0) {
|
|
|
355
580
|
}
|
|
356
581
|
continue;
|
|
357
582
|
}
|
|
583
|
+
if (hasVarExpansion(arg)) {
|
|
584
|
+
evasionSet.add('dynamic_var_expansion');
|
|
585
|
+
}
|
|
358
586
|
if (isUrl(arg) || classifyFileToken(arg) !== 'none') {
|
|
359
587
|
inspectToken(arg, defaultAccess);
|
|
360
588
|
continue;
|
|
@@ -438,5 +666,7 @@ export function analyzeCommand(command, depth = 0) {
|
|
|
438
666
|
pushSuggestion({ kind: 'url', label: u.slice(0, 28), pattern: `*${u}*`, operator: 'glob' });
|
|
439
667
|
}
|
|
440
668
|
}
|
|
441
|
-
|
|
669
|
+
const evasionSignals = [...evasionSet];
|
|
670
|
+
const opaque = evasionSignals.length > 0;
|
|
671
|
+
return { tools: dedupTools, paths, files, urls, urlHosts, flags, intents, hasSensitiveTarget, opaque, evasionSignals, suggestions };
|
|
442
672
|
}
|
package/dist/policy/evaluate.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ruleMatches } from './match.js';
|
|
1
|
+
import { isOpaqueCommandInput, resolveArgPath, ruleMatches } from './match.js';
|
|
2
2
|
import { PolicyError } from '../errors.js';
|
|
3
3
|
/**
|
|
4
4
|
* Deterministic policy evaluation (docs/02 section 3.4).
|
|
@@ -37,12 +37,23 @@ function ruleRisk(rule) {
|
|
|
37
37
|
return rule.riskLevel;
|
|
38
38
|
}
|
|
39
39
|
function ruleMatchesAutoRule(autoRule, input) {
|
|
40
|
-
if (
|
|
40
|
+
if (isOpaqueCommandInput(input.args))
|
|
41
|
+
return false;
|
|
42
|
+
if (!ruleMatches(autoRule.match, input, { strictAllow: true }))
|
|
41
43
|
return false;
|
|
42
44
|
if (autoRule.agentIds && autoRule.agentIds.length > 0) {
|
|
43
45
|
if (!input.agentId || !autoRule.agentIds.includes(input.agentId))
|
|
44
46
|
return false;
|
|
45
47
|
}
|
|
48
|
+
if (autoRule.budget) {
|
|
49
|
+
const resolved = resolveArgPath(input.args ?? {}, autoRule.budget.field);
|
|
50
|
+
if (!resolved.found || typeof resolved.value !== 'number' || !Number.isFinite(resolved.value) || resolved.value < 0) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
const nextTotal = (autoRule.budget.consumed ?? 0) + resolved.value;
|
|
54
|
+
if (nextTotal > autoRule.budget.maxTotal)
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
46
57
|
// Auto-rules can never cover CRITICAL risk (enforced at the call site).
|
|
47
58
|
return true;
|
|
48
59
|
}
|
|
@@ -79,7 +90,13 @@ export function evaluatePolicy(policy, input, flags = {}) {
|
|
|
79
90
|
// DENY always beats everything below it.
|
|
80
91
|
const denyRule = firstMatchingRule(rules, (r) => r.effect === 'DENY' && ruleMatches(r.match, input));
|
|
81
92
|
if (denyRule) {
|
|
82
|
-
return {
|
|
93
|
+
return {
|
|
94
|
+
effect: 'DENY',
|
|
95
|
+
reason: 'DENY_RULE',
|
|
96
|
+
ruleId: denyRule.id,
|
|
97
|
+
degraded,
|
|
98
|
+
...(denyRule.addTaints ? { addedTaints: denyRule.addTaints } : {})
|
|
99
|
+
};
|
|
83
100
|
}
|
|
84
101
|
const approvalRule = firstMatchingRule(rules, (r) => r.effect === 'REQUIRE_APPROVAL' && ruleMatches(r.match, input));
|
|
85
102
|
if (approvalRule) {
|
|
@@ -108,16 +125,30 @@ export function evaluatePolicy(policy, input, flags = {}) {
|
|
|
108
125
|
riskLevel: risk,
|
|
109
126
|
approversRequired: approvers,
|
|
110
127
|
ttlSeconds: ttl,
|
|
111
|
-
degraded
|
|
128
|
+
degraded,
|
|
129
|
+
...(approvalRule.addTaints ? { addedTaints: approvalRule.addTaints } : {}),
|
|
130
|
+
...(approvalRule.routingGroup ? { routingGroup: approvalRule.routingGroup } : {})
|
|
112
131
|
};
|
|
113
132
|
}
|
|
114
133
|
const observeRule = firstMatchingRule(rules, (r) => r.effect === 'OBSERVE' && ruleMatches(r.match, input));
|
|
115
134
|
if (observeRule) {
|
|
116
|
-
return {
|
|
135
|
+
return {
|
|
136
|
+
effect: 'OBSERVE',
|
|
137
|
+
reason: 'OBSERVE_RULE',
|
|
138
|
+
ruleId: observeRule.id,
|
|
139
|
+
degraded,
|
|
140
|
+
...(observeRule.addTaints ? { addedTaints: observeRule.addTaints } : {})
|
|
141
|
+
};
|
|
117
142
|
}
|
|
118
|
-
const allowRule = firstMatchingRule(rules, (r) => r.effect === 'ALLOW' && ruleMatches(r.match, input));
|
|
143
|
+
const allowRule = firstMatchingRule(rules, (r) => r.effect === 'ALLOW' && ruleMatches(r.match, input, { strictAllow: true }));
|
|
119
144
|
if (allowRule) {
|
|
120
|
-
return {
|
|
145
|
+
return {
|
|
146
|
+
effect: 'ALLOW',
|
|
147
|
+
reason: 'ALLOW_RULE',
|
|
148
|
+
ruleId: allowRule.id,
|
|
149
|
+
degraded,
|
|
150
|
+
...(allowRule.addTaints ? { addedTaints: allowRule.addTaints } : {})
|
|
151
|
+
};
|
|
121
152
|
}
|
|
122
153
|
const unmatched = policy.defaults.unmatched;
|
|
123
154
|
if (unmatched === 'ALLOW') {
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type CommandAnalysis } from './command-analyzer.js';
|
|
2
|
+
import type { EffectivePolicy, Effect, EvalFlags, EvalInput, EvalResult } from './types.js';
|
|
3
|
+
export interface RuleEvaluationTrace {
|
|
4
|
+
ruleId: string;
|
|
5
|
+
name?: string;
|
|
6
|
+
effect: Effect;
|
|
7
|
+
matched: boolean;
|
|
8
|
+
reason: string;
|
|
9
|
+
}
|
|
10
|
+
export interface ExplainResult {
|
|
11
|
+
result: EvalResult;
|
|
12
|
+
commandAnalysis?: CommandAnalysis;
|
|
13
|
+
traces: RuleEvaluationTrace[];
|
|
14
|
+
autoRuleMatched?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface SimulationSample {
|
|
17
|
+
id?: string;
|
|
18
|
+
input: EvalInput;
|
|
19
|
+
flags?: EvalFlags;
|
|
20
|
+
}
|
|
21
|
+
export interface SimulationTransitionSample {
|
|
22
|
+
id?: string;
|
|
23
|
+
tool: string;
|
|
24
|
+
fromRuleId?: string;
|
|
25
|
+
toRuleId?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface SimulationTransition {
|
|
28
|
+
from: Effect;
|
|
29
|
+
to: Effect;
|
|
30
|
+
count: number;
|
|
31
|
+
samples: SimulationTransitionSample[];
|
|
32
|
+
}
|
|
33
|
+
export interface SimulationSummary {
|
|
34
|
+
total: number;
|
|
35
|
+
unchanged: number;
|
|
36
|
+
changed: number;
|
|
37
|
+
transitions: SimulationTransition[];
|
|
38
|
+
byNewEffect: Record<Effect, number>;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Pure policy explanation helper for Policy Playground and CLI `policy test`.
|
|
42
|
+
* Evaluates the policy deterministically and returns a per-rule trace plus
|
|
43
|
+
* structured command analysis when a shell command is present.
|
|
44
|
+
*/
|
|
45
|
+
export declare function explainEvaluation(policy: EffectivePolicy, input: EvalInput, flags?: EvalFlags): ExplainResult;
|
|
46
|
+
/**
|
|
47
|
+
* Compare two policies over a batch of historical or synthetic samples
|
|
48
|
+
* ("What-If Replay"). Pure and side-effect free.
|
|
49
|
+
*/
|
|
50
|
+
export declare function simulatePolicy(currentPolicy: EffectivePolicy, candidatePolicy: EffectivePolicy, samples: SimulationSample[], maxSamplesPerTransition?: number): SimulationSummary;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { analyzeCommand } from './command-analyzer.js';
|
|
2
|
+
import { evaluatePolicy } from './evaluate.js';
|
|
3
|
+
import { isOpaqueCommandInput, ruleMatches, toolMatches } from './match.js';
|
|
4
|
+
function extractCommandText(args) {
|
|
5
|
+
if (!args)
|
|
6
|
+
return undefined;
|
|
7
|
+
for (const key of ['command', 'cmd', 'script']) {
|
|
8
|
+
const val = args[key];
|
|
9
|
+
if (typeof val === 'string' && val.trim().length > 0)
|
|
10
|
+
return val;
|
|
11
|
+
}
|
|
12
|
+
return undefined;
|
|
13
|
+
}
|
|
14
|
+
function diagnoseNoMatch(match, input, strictAllow) {
|
|
15
|
+
if (!toolMatches(match.tool, input.tool)) {
|
|
16
|
+
return `tool "${input.tool}" does not match glob "${match.tool}"`;
|
|
17
|
+
}
|
|
18
|
+
if (match.agentIds && match.agentIds.length > 0) {
|
|
19
|
+
if (!input.agentId || !match.agentIds.some((g) => toolMatches(g, input.agentId))) {
|
|
20
|
+
return `agentId "${input.agentId ?? '(none)'}" not in [${match.agentIds.join(', ')}]`;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (match.environments && match.environments.length > 0) {
|
|
24
|
+
if (!input.environment || !match.environments.includes(input.environment)) {
|
|
25
|
+
return `environment "${input.environment ?? '(none)'}" not in [${match.environments.join(', ')}]`;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (strictAllow && isOpaqueCommandInput(input.args)) {
|
|
29
|
+
return 'opaque command input cannot be auto-allowed by strict ALLOW rule';
|
|
30
|
+
}
|
|
31
|
+
if (match.command) {
|
|
32
|
+
return 'command structure (tools/subcommands/intents/paths/flags) did not match';
|
|
33
|
+
}
|
|
34
|
+
if (match.args) {
|
|
35
|
+
return 'argument predicates did not match';
|
|
36
|
+
}
|
|
37
|
+
return 'rule conditions did not match';
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Pure policy explanation helper for Policy Playground and CLI `policy test`.
|
|
41
|
+
* Evaluates the policy deterministically and returns a per-rule trace plus
|
|
42
|
+
* structured command analysis when a shell command is present.
|
|
43
|
+
*/
|
|
44
|
+
export function explainEvaluation(policy, input, flags = {}) {
|
|
45
|
+
const result = evaluatePolicy(policy, input, flags);
|
|
46
|
+
const cmdText = extractCommandText(input.args);
|
|
47
|
+
const commandAnalysis = cmdText ? analyzeCommand(cmdText) : undefined;
|
|
48
|
+
const traces = [];
|
|
49
|
+
const order = ['DENY', 'REQUIRE_APPROVAL', 'OBSERVE', 'ALLOW'];
|
|
50
|
+
for (const phaseEffect of order) {
|
|
51
|
+
for (const rule of policy.rules) {
|
|
52
|
+
if (rule.effect !== phaseEffect)
|
|
53
|
+
continue;
|
|
54
|
+
const strictAllow = phaseEffect === 'ALLOW';
|
|
55
|
+
const matched = ruleMatches(rule.match, input, strictAllow ? { strictAllow: true } : undefined);
|
|
56
|
+
traces.push({
|
|
57
|
+
ruleId: rule.id,
|
|
58
|
+
...(rule.name ? { name: rule.name } : {}),
|
|
59
|
+
effect: rule.effect,
|
|
60
|
+
matched,
|
|
61
|
+
reason: matched
|
|
62
|
+
? result.ruleId === rule.id
|
|
63
|
+
? `matched and selected (${result.reason})`
|
|
64
|
+
: 'matched, shadowed by higher-precedence rule'
|
|
65
|
+
: diagnoseNoMatch(rule.match, input, strictAllow)
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
result,
|
|
71
|
+
...(commandAnalysis ? { commandAnalysis } : {}),
|
|
72
|
+
traces,
|
|
73
|
+
...(result.autoRuleId ? { autoRuleMatched: result.autoRuleId } : {})
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Compare two policies over a batch of historical or synthetic samples
|
|
78
|
+
* ("What-If Replay"). Pure and side-effect free.
|
|
79
|
+
*/
|
|
80
|
+
export function simulatePolicy(currentPolicy, candidatePolicy, samples, maxSamplesPerTransition = 5) {
|
|
81
|
+
const byNewEffect = {
|
|
82
|
+
ALLOW: 0,
|
|
83
|
+
OBSERVE: 0,
|
|
84
|
+
REQUIRE_APPROVAL: 0,
|
|
85
|
+
DENY: 0
|
|
86
|
+
};
|
|
87
|
+
const transitionMap = new Map();
|
|
88
|
+
let unchanged = 0;
|
|
89
|
+
let changed = 0;
|
|
90
|
+
for (const sample of samples) {
|
|
91
|
+
const prev = evaluatePolicy(currentPolicy, sample.input, sample.flags);
|
|
92
|
+
const next = evaluatePolicy(candidatePolicy, sample.input, sample.flags);
|
|
93
|
+
byNewEffect[next.effect] += 1;
|
|
94
|
+
if (prev.effect === next.effect) {
|
|
95
|
+
unchanged += 1;
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
changed += 1;
|
|
99
|
+
}
|
|
100
|
+
const key = `${prev.effect}->${next.effect}`;
|
|
101
|
+
let entry = transitionMap.get(key);
|
|
102
|
+
if (!entry) {
|
|
103
|
+
entry = { from: prev.effect, to: next.effect, count: 0, samples: [] };
|
|
104
|
+
transitionMap.set(key, entry);
|
|
105
|
+
}
|
|
106
|
+
entry.count += 1;
|
|
107
|
+
if (entry.samples.length < maxSamplesPerTransition) {
|
|
108
|
+
entry.samples.push({
|
|
109
|
+
...(sample.id ? { id: sample.id } : {}),
|
|
110
|
+
tool: sample.input.tool,
|
|
111
|
+
...(prev.ruleId ? { fromRuleId: prev.ruleId } : {}),
|
|
112
|
+
...(next.ruleId ? { toRuleId: next.ruleId } : {})
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const transitions = Array.from(transitionMap.values()).sort((a, b) => b.count - a.count);
|
|
117
|
+
return {
|
|
118
|
+
total: samples.length,
|
|
119
|
+
unchanged,
|
|
120
|
+
changed,
|
|
121
|
+
transitions,
|
|
122
|
+
byNewEffect
|
|
123
|
+
};
|
|
124
|
+
}
|