@aithorized/core 0.2.0 → 0.3.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.
@@ -28,6 +28,8 @@ export interface RedactionResult {
28
28
  redactedPaths: string[];
29
29
  }
30
30
  export declare const DEFAULT_KEY_GLOBS: string[];
31
+ /** High-confidence secret value patterns redacted by default in previews (PG-06). */
32
+ export declare const DEFAULT_VALUE_REGEXES: string[];
31
33
  /**
32
34
  * Build a redacted preview of a payload. The returned fields are for
33
35
  * display only; hashing must use the original payload.
@@ -12,9 +12,21 @@ export const DEFAULT_KEY_GLOBS = [
12
12
  '*secret*',
13
13
  '*token*',
14
14
  '*credential*',
15
- '*apiKey*',
15
+ '*apikey*',
16
16
  '*api_key*',
17
- '*privateKey*'
17
+ '*privatekey*',
18
+ '*private_key*',
19
+ '*authorization*',
20
+ '*cookie*'
21
+ ];
22
+ /** High-confidence secret value patterns redacted by default in previews (PG-06). */
23
+ export const DEFAULT_VALUE_REGEXES = [
24
+ '\\bAKIA[0-9A-Z]{16}\\b',
25
+ '\\bgh[pousr]_[A-Za-z0-9]{20,}\\b',
26
+ '\\bsk-(?:proj-|ant-)?[A-Za-z0-9_-]{20,}\\b',
27
+ '\\bsk_(?:live|test)_[A-Za-z0-9]{16,}\\b',
28
+ '-----BEGIN [A-Z ]*PRIVATE KEY-----',
29
+ '\\bBearer\\s+[A-Za-z0-9._-]{20,}\\b'
18
30
  ];
19
31
  function escapePointer(segment) {
20
32
  return segment.replace(/~/g, '~0').replace(/\//g, '~1');
@@ -41,7 +53,8 @@ function stringPreview(value, maxLength) {
41
53
  return text;
42
54
  }
43
55
  function isSecretKey(segment, keyGlobs) {
44
- return keyGlobs.some((glob) => toolMatches(glob, segment));
56
+ const lower = segment.toLowerCase();
57
+ return keyGlobs.some((glob) => toolMatches(glob.toLowerCase(), lower));
45
58
  }
46
59
  /**
47
60
  * Walk the payload producing preview fields. A redacted node is emitted
@@ -83,7 +96,8 @@ function walk(value, pointer, segment, ctx) {
83
96
  export function redactForPreview(payload, config = {}) {
84
97
  let valueRegexes;
85
98
  try {
86
- valueRegexes = (config.valueRegexes ?? []).map((pattern) => new RegExp(pattern));
99
+ const patterns = [...DEFAULT_VALUE_REGEXES, ...(config.valueRegexes ?? [])];
100
+ valueRegexes = patterns.map((pattern) => new RegExp(pattern));
87
101
  }
88
102
  catch (err) {
89
103
  throw new Error(`invalid valueRegex: ${err.message}`, { cause: err });
@@ -32,6 +32,10 @@ export interface CommandAnalysis {
32
32
  flags: string[];
33
33
  intents: CommandIntent[];
34
34
  hasSensitiveTarget: boolean;
35
+ /** True when the command uses dynamic/obfuscated constructs (eval, unexpanded vars, pipe-to-shell, max depth, etc.). */
36
+ opaque: boolean;
37
+ /** Specific evasion/obfuscation signals detected during analysis. */
38
+ evasionSignals: string[];
35
39
  suggestions: CommandPatternSuggestion[];
36
40
  }
37
41
  /** Split command string into segments on `&&`, `||`, `;`, `|`, `\n` outside quotes. */
@@ -41,5 +45,5 @@ export declare function splitShellSegments(command: string): {
41
45
  }[];
42
46
  /** Tokenize a single shell segment respecting quotes and escapes. */
43
47
  export declare function tokenizeSegment(segment: string): string[];
44
- /** Analyze a shell command string for tools, subcommands, paths, files, URLs, flags, and intents. */
48
+ /** Analyze a shell command string for tools, subcommands, paths, files, URLs, flags, intents, and evasion signals. */
45
49
  export declare function analyzeCommand(command: string, depth?: number): CommandAnalysis;
@@ -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', 'xargs']);
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.replace(/\\/g, '/'));
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 intents. */
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 p = rawPath.replace(/[\\/]+$/, '') || '/';
166
- if (!p || p === '.' || p === '~' || p === '/dev' || p === '/dev/null')
310
+ const normalized = normalizePath(rawPath).replace(/[\\/]+$/, '') || '/';
311
+ if (!normalized || normalized === '.' || normalized === '~' || normalized === '/dev' || normalized === '/dev/null')
167
312
  return;
168
- if (!pathMap.has(p))
169
- pathMap.set(p, { path: p, sensitive: isSensitive(p) });
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 $(...) subshells recursively (bounded depth)
223
- if (depth < 2) {
224
- const subshellRe = /\$\(([^()]+)\)/g;
225
- let m;
226
- while ((m = subshellRe.exec(command)) !== null) {
227
- if (m[1])
228
- mergeSubAnalysis(analyzeCommand(m[1], depth + 1));
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
- const headRaw = tokens[idx];
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
- inspectToken(target, access);
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 ((cmdLower === 'bash' || cmdLower === 'sh' || cmdLower === 'zsh') && depth < 2) {
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
- mergeSubAnalysis(analyzeCommand(inlineScript, depth + 1));
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
- return { tools: dedupTools, paths, files, urls, urlHosts, flags, intents, hasSensitiveTarget, suggestions };
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
  }
@@ -1,4 +1,4 @@
1
- import { ruleMatches } from './match.js';
1
+ import { isOpaqueCommandInput, ruleMatches } from './match.js';
2
2
  import { PolicyError } from '../errors.js';
3
3
  /**
4
4
  * Deterministic policy evaluation (docs/02 section 3.4).
@@ -37,7 +37,9 @@ function ruleRisk(rule) {
37
37
  return rule.riskLevel;
38
38
  }
39
39
  function ruleMatchesAutoRule(autoRule, input) {
40
- if (!ruleMatches(autoRule.match, input))
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))
@@ -115,7 +117,7 @@ export function evaluatePolicy(policy, input, flags = {}) {
115
117
  if (observeRule) {
116
118
  return { effect: 'OBSERVE', reason: 'OBSERVE_RULE', ruleId: observeRule.id, degraded };
117
119
  }
118
- const allowRule = firstMatchingRule(rules, (r) => r.effect === 'ALLOW' && ruleMatches(r.match, input));
120
+ const allowRule = firstMatchingRule(rules, (r) => r.effect === 'ALLOW' && ruleMatches(r.match, input, { strictAllow: true }));
119
121
  if (allowRule) {
120
122
  return { effect: 'ALLOW', reason: 'ALLOW_RULE', ruleId: allowRule.id, degraded };
121
123
  }
@@ -24,12 +24,23 @@ export declare function resolveArgPath(args: Record<string, unknown>, key: strin
24
24
  found: boolean;
25
25
  value: unknown;
26
26
  };
27
+ export interface MatchOptions {
28
+ /**
29
+ * Strict allowlist semantics (used for ALLOW and AutoRule evaluation, PG-01):
30
+ * - Opaque/evasive commands (eval, unexpanded vars, pipe-to-shell, max depth, unclosed quotes) NEVER match.
31
+ * - Every detected tool, path, URL, and intent in a chained command must satisfy the rule's allowlist (`ALL`),
32
+ * preventing command-chaining bypasses like `ls /workspace && curl evil.com`.
33
+ */
34
+ strictAllow?: boolean;
35
+ }
27
36
  /** Evaluate structured shell command matching using `analyzeCommand()`. */
28
- export declare function commandMatches(cmdMatch: CommandMatch, args: Record<string, unknown>): boolean;
37
+ export declare function commandMatches(cmdMatch: CommandMatch, args: Record<string, unknown>, options?: MatchOptions): boolean;
29
38
  /**
30
39
  * A rule matches when its tool glob matches, optional agentIds/environments
31
40
  * scopes match, every argument predicate holds, and optional structured
32
41
  * command matching holds. A predicate referencing an absent argument fails
33
42
  * the rule.
34
43
  */
35
- export declare function ruleMatches(match: RuleMatch, input: EvalInput): boolean;
44
+ export declare function ruleMatches(match: RuleMatch, input: EvalInput, options?: MatchOptions): boolean;
45
+ /** True when `args` contains a shell command that `analyzeCommand()` flags as opaque/evasive. */
46
+ export declare function isOpaqueCommandInput(args: Record<string, unknown> | undefined): boolean;
@@ -5,8 +5,17 @@ import { analyzeCommand } from './command-analyzer.js';
5
5
  * Deterministic matching (docs/02 section 3.4, FR-3.1).
6
6
  * Pure functions, no side effects, no randomness.
7
7
  */
8
+ const MAX_CACHE_ENTRIES = 2048;
8
9
  const globCache = new Map();
9
10
  const regexCache = new Map();
11
+ function cacheSet(cache, key, value) {
12
+ if (cache.size >= MAX_CACHE_ENTRIES) {
13
+ const oldest = cache.keys().next().value;
14
+ if (oldest !== undefined)
15
+ cache.delete(oldest);
16
+ }
17
+ cache.set(key, value);
18
+ }
10
19
  function escapeRegExp(ch) {
11
20
  return /[.*+?^${}()|[\]\\]/.test(ch) ? '\\' + ch : ch;
12
21
  }
@@ -40,7 +49,7 @@ export function compilePolicyRegex(pattern) {
40
49
  }
41
50
  }
42
51
  const re = new RegExp(body, flags);
43
- regexCache.set(pattern, re);
52
+ cacheSet(regexCache, pattern, re);
44
53
  return re;
45
54
  }
46
55
  /**
@@ -60,7 +69,7 @@ export function toolMatches(pattern, tool) {
60
69
  body += escapeRegExp(ch);
61
70
  }
62
71
  re = new RegExp(`^${body}$`);
63
- globCache.set(pattern, re);
72
+ cacheSet(globCache, pattern, re);
64
73
  }
65
74
  return re.test(tool);
66
75
  }
@@ -196,29 +205,44 @@ function anyGlobMatches(patterns, candidates) {
196
205
  }
197
206
  return false;
198
207
  }
208
+ function allGlobsMatch(patterns, candidates) {
209
+ if (candidates.length === 0)
210
+ return false;
211
+ return candidates.every((cand) => patterns.some((pat) => toolMatches(pat, cand)));
212
+ }
199
213
  /** Evaluate structured shell command matching using `analyzeCommand()`. */
200
- export function commandMatches(cmdMatch, args) {
214
+ export function commandMatches(cmdMatch, args, options = {}) {
201
215
  const cmdText = extractCommandText(args);
202
216
  if (!cmdText)
203
217
  return false;
204
218
  const analysis = analyzeCommand(cmdText);
219
+ const strict = options.strictAllow === true;
220
+ // An opaque/evasive command can never satisfy an ALLOW or AutoRule (fail-closed, PG-03).
221
+ if (strict && analysis.opaque)
222
+ return false;
223
+ const listMatch = strict ? allGlobsMatch : anyGlobMatches;
205
224
  if (cmdMatch.tools && cmdMatch.tools.length > 0) {
206
225
  const names = analysis.tools.map((t) => t.name);
207
- if (!anyGlobMatches(cmdMatch.tools, names))
226
+ if (!listMatch(cmdMatch.tools, names))
208
227
  return false;
209
228
  }
210
229
  if (cmdMatch.subcommands && cmdMatch.subcommands.length > 0) {
211
230
  const subs = analysis.tools.map((t) => t.subcommand).filter((s) => typeof s === 'string');
212
- if (!anyGlobMatches(cmdMatch.subcommands, subs))
231
+ if (!listMatch(cmdMatch.subcommands, subs))
213
232
  return false;
214
233
  }
215
234
  if (cmdMatch.intents && cmdMatch.intents.length > 0) {
216
- if (!cmdMatch.intents.some((intent) => analysis.intents.includes(intent)))
235
+ if (strict) {
236
+ if (analysis.intents.length === 0 || !analysis.intents.every((intent) => cmdMatch.intents.includes(intent)))
237
+ return false;
238
+ }
239
+ else if (!cmdMatch.intents.some((intent) => analysis.intents.includes(intent))) {
217
240
  return false;
241
+ }
218
242
  }
219
243
  const allPaths = [...analysis.paths.map((p) => p.path), ...analysis.files.map((f) => f.path)];
220
244
  if (cmdMatch.paths && cmdMatch.paths.length > 0) {
221
- if (!anyGlobMatches(cmdMatch.paths, allPaths))
245
+ if (!listMatch(cmdMatch.paths, allPaths))
222
246
  return false;
223
247
  }
224
248
  if (cmdMatch.excludePaths && cmdMatch.excludePaths.length > 0) {
@@ -227,7 +251,7 @@ export function commandMatches(cmdMatch, args) {
227
251
  }
228
252
  if (cmdMatch.urls && cmdMatch.urls.length > 0) {
229
253
  const urlTargets = [...analysis.urls, ...analysis.urlHosts];
230
- if (!anyGlobMatches(cmdMatch.urls, urlTargets))
254
+ if (!listMatch(cmdMatch.urls, urlTargets))
231
255
  return false;
232
256
  }
233
257
  if (cmdMatch.flags && cmdMatch.flags.length > 0) {
@@ -250,7 +274,7 @@ export function commandMatches(cmdMatch, args) {
250
274
  * command matching holds. A predicate referencing an absent argument fails
251
275
  * the rule.
252
276
  */
253
- export function ruleMatches(match, input) {
277
+ export function ruleMatches(match, input, options = {}) {
254
278
  if (!toolMatches(match.tool, input.tool))
255
279
  return false;
256
280
  if (match.agentIds && match.agentIds.length > 0) {
@@ -276,8 +300,17 @@ export function ruleMatches(match, input) {
276
300
  }
277
301
  }
278
302
  if (match.command) {
279
- if (!commandMatches(match.command, args))
303
+ if (!commandMatches(match.command, args, options))
280
304
  return false;
281
305
  }
282
306
  return true;
283
307
  }
308
+ /** True when `args` contains a shell command that `analyzeCommand()` flags as opaque/evasive. */
309
+ export function isOpaqueCommandInput(args) {
310
+ if (!args)
311
+ return false;
312
+ const cmdText = extractCommandText(args);
313
+ if (!cmdText)
314
+ return false;
315
+ return analyzeCommand(cmdText).opaque;
316
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aithorized/core",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Deterministic crypto core and policy engine for aithorized (JCS RFC 8785, payload hashing, domain-separated ECDSA/Ed25519 signatures, fail-closed policy evaluation).",
5
5
  "type": "module",
6
6
  "license": "MIT",