@aithorized/core 0.1.5 → 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.
package/dist/index.d.ts CHANGED
@@ -11,14 +11,16 @@ export { jwkThumbprint, publicJwkToKeyObject, privateJwkToKeyObject, ed25519Publ
11
11
  export type { EcP256Jwk, Ed25519Jwk, JwkThumbprintJwk } from './crypto/jwk.js';
12
12
  export { DECISION_DOMAIN, ACTION_DOMAIN, HTTP_DOMAIN, WS_DOMAIN, ENROLL_DOMAIN, decisionSigningInput, actionSigningInput, enrollSigningInput, wsSigningInput, refreshSigningInput, httpSigningInput, parseEcdsaDer, encodeEcdsaDer, normalizeEcdsaLowS, signEcdsaP256, verifyEcdsaP256, signEd25519, verifyEd25519 } from './crypto/sign.js';
13
13
  export { RISK_ORDER, MIN_TTL_SECONDS, MAX_TTL_SECONDS, clampTtl, evaluatePolicy } from './policy/evaluate.js';
14
- export { toolMatches, argMatches, ruleMatches, compilePolicyRegex } from './policy/match.js';
14
+ export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './policy/match.js';
15
+ export { analyzeCommand, splitShellSegments, tokenizeSegment } from './policy/command-analyzer.js';
16
+ export type { CommandAnalysis, CommandIntent, CommandPatternSuggestion, DetectedFile, DetectedPath, DetectedTool } from './policy/command-analyzer.js';
15
17
  export { mergePolicies, strictnessOf } from './policy/merge.js';
16
18
  export { activePause, assertPauseLimits, MAX_PAUSE_MS, PAUSE_MODES } from './policy/pause.js';
17
19
  export type { MergeOptions } from './policy/merge.js';
18
20
  export { STALE_AFTER_MS, verifyBundle, pinnedKeyFor, bundleStateFromVerification, assertOk, bundleSigningContent } from './policy/bundle.js';
19
21
  export type { BundleStatus, BundleVerification, PinnedPolicyKey, PinnedPolicyKeys } from './policy/bundle.js';
20
22
  export { loadPolicyYaml, parsePolicyJson, validateRules } from './policy/load.js';
21
- export type { RiskLevel, Effect, UnmatchedDefault, ArgPredicate, RuleMatch, PolicyRule, PolicyDefaults, PolicyDocument, AutoRule, Pause, PauseMode, PolicyBundle, EffectivePolicy, EvalInput, EvalFlags, EvalReason, EvalResult } from './policy/types.js';
23
+ export type { RiskLevel, Effect, UnmatchedDefault, ArgPredicate, CommandMatch, RuleMatch, PolicyRule, PolicyDefaults, PolicyDocument, AutoRule, Pause, PauseMode, PolicyBundle, EffectivePolicy, EvalInput, EvalFlags, EvalReason, EvalResult } from './policy/types.js';
22
24
  export { CLOCK_SKEW_ALLOWANCE_MS, MAX_CREATE_ATTEMPTS, createLocalDeadline, shouldRetryCreate, awaitResolutionBeforeDeadline } from './lifecycle/deadline.js';
23
25
  export type { LocalDeadline } from './lifecycle/deadline.js';
24
26
  export { verifyDecisionBundle, keyClassCanDecide, KEY_CLASSES, DIRECTORY_DOMAIN, directorySigningInput, verifyDirectory } from './lifecycle/verify.js';
package/dist/index.js CHANGED
@@ -10,7 +10,8 @@ export { sha256, base64urlEncode, base64urlDecode, payloadHash, feedbackHash, co
10
10
  export { jwkThumbprint, publicJwkToKeyObject, privateJwkToKeyObject, ed25519PublicKeyToKeyObject, ed25519PrivateKeyToKeyObject, keyObjectToJwk } from './crypto/jwk.js';
11
11
  export { DECISION_DOMAIN, ACTION_DOMAIN, HTTP_DOMAIN, WS_DOMAIN, ENROLL_DOMAIN, decisionSigningInput, actionSigningInput, enrollSigningInput, wsSigningInput, refreshSigningInput, httpSigningInput, parseEcdsaDer, encodeEcdsaDer, normalizeEcdsaLowS, signEcdsaP256, verifyEcdsaP256, signEd25519, verifyEd25519 } from './crypto/sign.js';
12
12
  export { RISK_ORDER, MIN_TTL_SECONDS, MAX_TTL_SECONDS, clampTtl, evaluatePolicy } from './policy/evaluate.js';
13
- export { toolMatches, argMatches, ruleMatches, compilePolicyRegex } from './policy/match.js';
13
+ export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './policy/match.js';
14
+ export { analyzeCommand, splitShellSegments, tokenizeSegment } from './policy/command-analyzer.js';
14
15
  export { mergePolicies, strictnessOf } from './policy/merge.js';
15
16
  export { activePause, assertPauseLimits, MAX_PAUSE_MS, PAUSE_MODES } from './policy/pause.js';
16
17
  export { STALE_AFTER_MS, verifyBundle, pinnedKeyFor, bundleStateFromVerification, assertOk, bundleSigningContent } from './policy/bundle.js';
@@ -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 });
@@ -4,7 +4,9 @@
4
4
  */
5
5
  export { loadPolicyYaml, parsePolicyJson, validateRules } from './load.js';
6
6
  export { evaluatePolicy, clampTtl, MIN_TTL_SECONDS, MAX_TTL_SECONDS, RISK_ORDER } from './evaluate.js';
7
- export { toolMatches, argMatches, ruleMatches } from './match.js';
7
+ export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './match.js';
8
+ export { analyzeCommand, splitShellSegments, tokenizeSegment } from './command-analyzer.js';
8
9
  export { activePause, MAX_PAUSE_MS, PAUSE_MODES } from './pause.js';
9
10
  export { PolicyError } from '../errors.js';
10
- export type { ArgPredicate, AutoRule, Effect, EffectivePolicy, EvalFlags, EvalInput, EvalReason, EvalResult, Pause, PauseMode, PolicyDefaults, PolicyDocument, PolicyRule, RiskLevel, RuleMatch, UnmatchedDefault } from './types.js';
11
+ export type { CommandAnalysis, CommandIntent, CommandPatternSuggestion, DetectedFile, DetectedPath, DetectedTool } from './command-analyzer.js';
12
+ export type { ArgPredicate, AutoRule, CommandMatch, Effect, EffectivePolicy, EvalFlags, EvalInput, EvalReason, EvalResult, Pause, PauseMode, PolicyDefaults, PolicyDocument, PolicyRule, RiskLevel, RuleMatch, UnmatchedDefault } from './types.js';
@@ -4,6 +4,7 @@
4
4
  */
5
5
  export { loadPolicyYaml, parsePolicyJson, validateRules } from './load.js';
6
6
  export { evaluatePolicy, clampTtl, MIN_TTL_SECONDS, MAX_TTL_SECONDS, RISK_ORDER } from './evaluate.js';
7
- export { toolMatches, argMatches, ruleMatches } from './match.js';
7
+ export { toolMatches, argMatches, ruleMatches, commandMatches, resolveArgPath, compilePolicyRegex } from './match.js';
8
+ export { analyzeCommand, splitShellSegments, tokenizeSegment } from './command-analyzer.js';
8
9
  export { activePause, MAX_PAUSE_MS, PAUSE_MODES } from './pause.js';
9
10
  export { PolicyError } from '../errors.js';
@@ -0,0 +1,49 @@
1
+ export type CommandIntent = 'read' | 'write' | 'delete' | 'network' | 'exec';
2
+ export interface DetectedTool {
3
+ name: string;
4
+ subcommand?: string;
5
+ runtime?: string;
6
+ primary: boolean;
7
+ glob: string;
8
+ }
9
+ export interface DetectedPath {
10
+ path: string;
11
+ sensitive: boolean;
12
+ }
13
+ export interface DetectedFile {
14
+ path: string;
15
+ name: string;
16
+ access: 'read' | 'write' | 'delete' | 'exec' | 'unknown';
17
+ sensitive: boolean;
18
+ }
19
+ export interface CommandPatternSuggestion {
20
+ id: string;
21
+ kind: 'tool' | 'path' | 'file' | 'url';
22
+ label: string;
23
+ pattern: string;
24
+ operator: 'glob' | 'regex';
25
+ }
26
+ export interface CommandAnalysis {
27
+ tools: DetectedTool[];
28
+ paths: DetectedPath[];
29
+ files: DetectedFile[];
30
+ urls: string[];
31
+ urlHosts: string[];
32
+ flags: string[];
33
+ intents: CommandIntent[];
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[];
39
+ suggestions: CommandPatternSuggestion[];
40
+ }
41
+ /** Split command string into segments on `&&`, `||`, `;`, `|`, `\n` outside quotes. */
42
+ export declare function splitShellSegments(command: string): {
43
+ segment: string;
44
+ piped: boolean;
45
+ }[];
46
+ /** Tokenize a single shell segment respecting quotes and escapes. */
47
+ export declare function tokenizeSegment(segment: string): string[];
48
+ /** Analyze a shell command string for tools, subcommands, paths, files, URLs, flags, intents, and evasion signals. */
49
+ export declare function analyzeCommand(command: string, depth?: number): CommandAnalysis;
@@ -0,0 +1,672 @@
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', '.']);
6
+ const READ_TOOLS = new Set(['cat', 'head', 'tail', 'less', 'more', 'grep', 'rg', 'find', 'ls', 'stat', 'read', 'get', 'list', 'psql', 'sqlite3']);
7
+ const WRITE_TOOLS = new Set(['cp', 'mv', 'tee', 'mkdir', 'touch', 'chmod', 'chown', 'ln', 'sed', 'awk', 'tar', 'unzip', 'zip']);
8
+ const DELETE_TOOLS = new Set(['rm', 'rmdir', 'unlink', 'shred']);
9
+ const NETWORK_TOOLS = new Set(['curl', 'wget', 'ssh', 'scp', 'rsync', 'nc', 'ncat', 'fetch', 'ping', 'dig']);
10
+ const READ_SUBCOMMANDS = new Set(['read', 'get', 'list', 'show', 'status', 'log', 'diff', 'search', 'inspect', 'view', 'describe']);
11
+ const WRITE_SUBCOMMANDS = new Set(['write', 'create', 'update', 'put', 'post', 'apply', 'push', 'install', 'add', 'set', 'deploy', 'send']);
12
+ const DELETE_SUBCOMMANDS = new Set(['delete', 'remove', 'rm', 'drop', 'destroy', 'purge', 'revoke', 'terminate', 'kill']);
13
+ const FLAGS_WITH_VALUE = new Set([
14
+ '-c', '-f', '-o', '-i', '-d', '-n', '-m', '-p', '-u', '-H', '-X', '-C',
15
+ '--account', '--config', '--dir', '--file', '--output', '--input', '--profile',
16
+ '--region', '--namespace', '--project', '--filter', '--format', '--header', '--data'
17
+ ]);
18
+ const KNOWN_FILE_EXT = /\.(py|sh|bash|zsh|js|mjs|cjs|ts|tsx|jsx|json|ya?ml|toml|ini|conf|cfg|env|sql|log|txt|csv|md|xml|html|css|pem|key|crt|db|sqlite)$/i;
19
+ const KNOWN_DOTFILES = /^\.(env(\..+)?|gitignore|npmrc|bashrc|zshrc|profile)$/i;
20
+ const SENSITIVE_PATTERN = /(^|\/)(\.ssh|\.aws|\.gnupg|\.hermes|\.env(\.|$)|etc\/|id_rsa|id_ed25519|credentials|secrets?|\.pem$|\.key$)/i;
21
+ function unquote(token) {
22
+ if (token.length >= 2) {
23
+ const first = token[0];
24
+ const last = token[token.length - 1];
25
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
26
+ return token.slice(1, -1);
27
+ }
28
+ }
29
+ return token;
30
+ }
31
+ function basenameOf(p) {
32
+ const cleaned = p.replace(/[\\/]+$/, '');
33
+ const parts = cleaned.split(/[\\/]/);
34
+ return parts[parts.length - 1] || cleaned;
35
+ }
36
+ function dirnameOf(p) {
37
+ const idx = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\'));
38
+ if (idx <= 0)
39
+ return idx === 0 ? '/' : null;
40
+ const dir = p.slice(0, idx);
41
+ return dir && dir !== '.' ? dir : null;
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
+ }
71
+ function isSensitive(p) {
72
+ return SENSITIVE_PATTERN.test(normalizePath(p));
73
+ }
74
+ function isUrl(token) {
75
+ return /^(https?|s3|gs):\/\/\S+/i.test(token);
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
+ }
187
+ /** Split command string into segments on `&&`, `||`, `;`, `|`, `\n` outside quotes. */
188
+ export function splitShellSegments(command) {
189
+ const out = [];
190
+ let buf = '';
191
+ let quote = null;
192
+ let piped = false;
193
+ for (let i = 0; i < command.length; i++) {
194
+ const ch = command[i] ?? '';
195
+ const next = command[i + 1] ?? '';
196
+ if (quote) {
197
+ if (ch === '\\' && quote === '"' && i + 1 < command.length) {
198
+ buf += ch + next;
199
+ i++;
200
+ continue;
201
+ }
202
+ if (ch === quote)
203
+ quote = null;
204
+ buf += ch;
205
+ continue;
206
+ }
207
+ if (ch === '"' || ch === "'") {
208
+ quote = ch;
209
+ buf += ch;
210
+ continue;
211
+ }
212
+ if ((ch === '&' && next === '&') || (ch === '|' && next === '|')) {
213
+ if (buf.trim())
214
+ out.push({ segment: buf.trim(), piped });
215
+ buf = '';
216
+ piped = false;
217
+ i++;
218
+ continue;
219
+ }
220
+ if (ch === ';' || ch === '\n') {
221
+ if (buf.trim())
222
+ out.push({ segment: buf.trim(), piped });
223
+ buf = '';
224
+ piped = false;
225
+ continue;
226
+ }
227
+ if (ch === '|') {
228
+ if (buf.trim())
229
+ out.push({ segment: buf.trim(), piped });
230
+ buf = '';
231
+ piped = true;
232
+ continue;
233
+ }
234
+ buf += ch;
235
+ }
236
+ if (buf.trim())
237
+ out.push({ segment: buf.trim(), piped });
238
+ return out;
239
+ }
240
+ /** Tokenize a single shell segment respecting quotes and escapes. */
241
+ export function tokenizeSegment(segment) {
242
+ const tokens = [];
243
+ let buf = '';
244
+ let quote = null;
245
+ for (let i = 0; i < segment.length; i++) {
246
+ const ch = segment[i] ?? '';
247
+ const next = segment[i + 1] ?? '';
248
+ if (quote) {
249
+ if (ch === '\\' && quote === '"' && i + 1 < segment.length) {
250
+ buf += next;
251
+ i++;
252
+ continue;
253
+ }
254
+ if (ch === quote) {
255
+ quote = null;
256
+ }
257
+ else {
258
+ buf += ch;
259
+ }
260
+ continue;
261
+ }
262
+ if (ch === '\\' && i + 1 < segment.length) {
263
+ buf += next;
264
+ i++;
265
+ continue;
266
+ }
267
+ if (ch === '"' || ch === "'") {
268
+ quote = ch;
269
+ continue;
270
+ }
271
+ if (/\s/.test(ch)) {
272
+ if (buf.length > 0) {
273
+ tokens.push(buf);
274
+ buf = '';
275
+ }
276
+ continue;
277
+ }
278
+ buf += ch;
279
+ }
280
+ if (buf.length > 0)
281
+ tokens.push(buf);
282
+ return tokens;
283
+ }
284
+ function classifyFileToken(token) {
285
+ const t = token.replace(/^@/, '');
286
+ if (!t || t === '~' || t === '.' || t === '..' || t === '/dev/null' || isUrl(t))
287
+ return 'none';
288
+ if (/^[0-9]+$/.test(t))
289
+ return 'none';
290
+ const looksLikePath = t.startsWith('/') || t.startsWith('~/') || t.startsWith('./') || t.startsWith('../') || /^[A-Za-z]:[\\/]/.test(t) || t.includes('/');
291
+ const base = basenameOf(t);
292
+ if (t.endsWith('/') || t.endsWith('\\'))
293
+ return 'path';
294
+ if (KNOWN_FILE_EXT.test(base) || KNOWN_DOTFILES.test(base))
295
+ return 'file';
296
+ if (looksLikePath)
297
+ return 'path';
298
+ return 'none';
299
+ }
300
+ /** Analyze a shell command string for tools, subcommands, paths, files, URLs, flags, intents, and evasion signals. */
301
+ export function analyzeCommand(command, depth = 0) {
302
+ const tools = [];
303
+ const pathMap = new Map();
304
+ const fileMap = new Map();
305
+ const urlSet = new Set();
306
+ const flagSet = new Set();
307
+ const intentSet = new Set();
308
+ const evasionSet = new Set();
309
+ const recordPath = (rawPath) => {
310
+ const normalized = normalizePath(rawPath).replace(/[\\/]+$/, '') || '/';
311
+ if (!normalized || normalized === '.' || normalized === '~' || normalized === '/dev' || normalized === '/dev/null')
312
+ return;
313
+ if (!pathMap.has(normalized))
314
+ pathMap.set(normalized, { path: normalized, sensitive: isSensitive(normalized) });
315
+ };
316
+ const recordFile = (rawFile, access) => {
317
+ const cleaned = normalizePath(rawFile.replace(/^@/, ''));
318
+ if (!cleaned || cleaned === '/dev/null')
319
+ return;
320
+ const existing = fileMap.get(cleaned);
321
+ if (!existing) {
322
+ fileMap.set(cleaned, {
323
+ path: cleaned,
324
+ name: basenameOf(cleaned),
325
+ access,
326
+ sensitive: isSensitive(cleaned)
327
+ });
328
+ }
329
+ else if (existing.access === 'unknown' && access !== 'unknown') {
330
+ existing.access = access;
331
+ }
332
+ const dir = dirnameOf(cleaned);
333
+ if (dir)
334
+ recordPath(dir);
335
+ };
336
+ const inspectToken = (raw, defaultAccess) => {
337
+ const t = unquote(raw);
338
+ if (!t || t === '/dev/null')
339
+ return;
340
+ if (hasVarExpansion(t)) {
341
+ evasionSet.add('dynamic_var_expansion');
342
+ }
343
+ if (isUrl(t)) {
344
+ urlSet.add(t);
345
+ intentSet.add('network');
346
+ return;
347
+ }
348
+ const kind = classifyFileToken(t);
349
+ if (kind === 'file')
350
+ recordFile(t, defaultAccess);
351
+ else if (kind === 'path')
352
+ recordPath(t);
353
+ };
354
+ const mergeSubAnalysis = (sub) => {
355
+ for (const tool of sub.tools)
356
+ tools.push(tool);
357
+ for (const p of sub.paths)
358
+ if (!pathMap.has(p.path))
359
+ pathMap.set(p.path, p);
360
+ for (const f of sub.files)
361
+ if (!fileMap.has(f.path))
362
+ fileMap.set(f.path, f);
363
+ for (const u of sub.urls)
364
+ urlSet.add(u);
365
+ for (const fl of sub.flags)
366
+ flagSet.add(fl);
367
+ for (const i of sub.intents)
368
+ intentSet.add(i);
369
+ for (const ev of sub.evasionSignals)
370
+ evasionSet.add(ev);
371
+ };
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');
382
+ }
383
+ }
384
+ for (const { segment, piped } of splitShellSegments(command)) {
385
+ const tokens = tokenizeSegment(segment);
386
+ let idx = 0;
387
+ // Strip VAR=val env prefixes
388
+ while (idx < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[idx] ?? '')) {
389
+ const eqPos = (tokens[idx] ?? '').indexOf('=');
390
+ inspectToken((tokens[idx] ?? '').slice(eqPos + 1), 'unknown');
391
+ idx++;
392
+ }
393
+ // Strip sudo / env / nohup / exec wrappers
394
+ while (idx < tokens.length && SHELL_WRAPPERS.has(basenameOf(tokens[idx] ?? '').toLowerCase())) {
395
+ const wrapperName = basenameOf(tokens[idx] ?? '').toLowerCase();
396
+ if (wrapperName === 'sudo')
397
+ flagSet.add('sudo');
398
+ idx++;
399
+ while (idx < tokens.length && (tokens[idx] ?? '').startsWith('-')) {
400
+ flagSet.add(tokens[idx] ?? '');
401
+ idx++;
402
+ }
403
+ }
404
+ // Parse redirections BEFORE checking SHELL_NOISE so `echo ... >> ~/.ssh/authorized_keys` is never missed (PG-02).
405
+ const cleanTokens = [];
406
+ let hadWriteRedir = false;
407
+ let hadAnyRedir = false;
408
+ for (let i = idx; i < tokens.length; i++) {
409
+ const tok = tokens[i] ?? '';
410
+ const redirMatch = tok.match(/^(?:(?:\d*|&))(>>|>|<)(.*)$/);
411
+ if (redirMatch) {
412
+ const op = redirMatch[1];
413
+ const inlineTarget = redirMatch[2];
414
+ const target = inlineTarget || tokens[i + 1];
415
+ if (!inlineTarget && target)
416
+ i++;
417
+ if (target && target !== '/dev/null' && !target.startsWith('&')) {
418
+ const access = op === '<' ? 'read' : 'write';
419
+ const unquotedTarget = unquote(target);
420
+ if (hasVarExpansion(unquotedTarget))
421
+ evasionSet.add('dynamic_var_expansion');
422
+ recordFile(unquotedTarget, access);
423
+ intentSet.add(access === 'read' ? 'read' : 'write');
424
+ hadAnyRedir = true;
425
+ if (access === 'write')
426
+ hadWriteRedir = true;
427
+ }
428
+ continue;
429
+ }
430
+ cleanTokens.push(tok);
431
+ }
432
+ const cmdToken = cleanTokens[0];
433
+ if (!cmdToken)
434
+ continue;
435
+ if (hasVarExpansion(cmdToken)) {
436
+ evasionSet.add('dynamic_command');
437
+ }
438
+ const cmdName = basenameOf(cmdToken);
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
+ }
509
+ // Handle `bash -c "..."` / `sh -c "..."` inline scripts recursively
510
+ if (cmdLower === 'bash' || cmdLower === 'sh' || cmdLower === 'zsh' || cmdLower === 'dash' || cmdLower === 'ksh') {
511
+ const cIdx = cleanTokens.indexOf('-c');
512
+ const inlineScript = cIdx !== -1 ? cleanTokens[cIdx + 1] : undefined;
513
+ if (inlineScript) {
514
+ intentSet.add('exec');
515
+ if (depth < 3) {
516
+ mergeSubAnalysis(analyzeCommand(inlineScript, depth + 1));
517
+ }
518
+ else {
519
+ evasionSet.add('max_depth_exceeded');
520
+ }
521
+ continue;
522
+ }
523
+ }
524
+ let toolName = cmdName;
525
+ let runtime;
526
+ let argStart = 1;
527
+ // Resolve script target for runtimes (python3 ~/.hermes/bin/mailguard.py ...)
528
+ if (SHELL_RUNTIMES.has(cmdLower)) {
529
+ intentSet.add('exec');
530
+ for (let i = 1; i < cleanTokens.length; i++) {
531
+ const arg = cleanTokens[i] ?? '';
532
+ if (arg.startsWith('-')) {
533
+ flagSet.add(arg);
534
+ if ((arg === '-c' || arg === '-e') && depth < 2) {
535
+ // Inline python/node snippet; keep runtime as tool
536
+ break;
537
+ }
538
+ continue;
539
+ }
540
+ runtime = cmdName;
541
+ toolName = basenameOf(arg);
542
+ recordFile(arg, 'exec');
543
+ argStart = i + 1;
544
+ break;
545
+ }
546
+ }
547
+ // Determine default file access from tool
548
+ let defaultAccess = 'unknown';
549
+ if (DELETE_TOOLS.has(cmdLower)) {
550
+ defaultAccess = 'delete';
551
+ intentSet.add('delete');
552
+ }
553
+ else if (WRITE_TOOLS.has(cmdLower)) {
554
+ defaultAccess = 'write';
555
+ intentSet.add('write');
556
+ }
557
+ else if (NETWORK_TOOLS.has(cmdLower)) {
558
+ defaultAccess = 'read';
559
+ intentSet.add('network');
560
+ }
561
+ else if (READ_TOOLS.has(cmdLower)) {
562
+ defaultAccess = 'read';
563
+ intentSet.add('read');
564
+ }
565
+ // Scan remaining args for subcommand, flags, files, paths, URLs
566
+ let subcommand;
567
+ for (let i = argStart; i < cleanTokens.length; i++) {
568
+ const arg = cleanTokens[i] ?? '';
569
+ if (arg.startsWith('-') && arg.length > 1) {
570
+ const eqIdx = arg.indexOf('=');
571
+ const flagName = eqIdx !== -1 ? arg.slice(0, eqIdx) : arg;
572
+ flagSet.add(flagName);
573
+ if (eqIdx !== -1) {
574
+ inspectToken(arg.slice(eqIdx + 1), defaultAccess);
575
+ }
576
+ else if (FLAGS_WITH_VALUE.has(arg) && i + 1 < cleanTokens.length) {
577
+ const val = cleanTokens[i + 1] ?? '';
578
+ inspectToken(val, defaultAccess);
579
+ i++;
580
+ }
581
+ continue;
582
+ }
583
+ if (hasVarExpansion(arg)) {
584
+ evasionSet.add('dynamic_var_expansion');
585
+ }
586
+ if (isUrl(arg) || classifyFileToken(arg) !== 'none') {
587
+ inspectToken(arg, defaultAccess);
588
+ continue;
589
+ }
590
+ if (!subcommand && /^[a-zA-Z][a-zA-Z0-9_-]{1,24}$/.test(arg)) {
591
+ subcommand = arg;
592
+ const subLower = arg.toLowerCase();
593
+ if (READ_SUBCOMMANDS.has(subLower))
594
+ intentSet.add('read');
595
+ else if (WRITE_SUBCOMMANDS.has(subLower))
596
+ intentSet.add('write');
597
+ else if (DELETE_SUBCOMMANDS.has(subLower))
598
+ intentSet.add('delete');
599
+ }
600
+ }
601
+ const isPipeFilter = piped && PIPE_FILTERS.has(cmdLower) && !runtime;
602
+ const glob = subcommand ? `*${toolName}*${subcommand}*` : `*${toolName}*`;
603
+ tools.push({
604
+ name: toolName,
605
+ ...(subcommand ? { subcommand } : {}),
606
+ ...(runtime ? { runtime } : {}),
607
+ primary: !isPipeFilter,
608
+ glob
609
+ });
610
+ }
611
+ // Deduplicate tools by name+subcommand, prioritizing primary tools
612
+ const dedupTools = [];
613
+ const seenToolKey = new Set();
614
+ for (const t of [...tools.filter((x) => x.primary), ...tools.filter((x) => !x.primary)]) {
615
+ const k = `${t.name}:${t.subcommand ?? ''}`;
616
+ if (!seenToolKey.has(k)) {
617
+ seenToolKey.add(k);
618
+ dedupTools.push(t);
619
+ }
620
+ }
621
+ const paths = [...pathMap.values()];
622
+ const files = [...fileMap.values()];
623
+ const urls = [...urlSet];
624
+ const urlHostSet = new Set();
625
+ for (const u of urls) {
626
+ try {
627
+ const parsed = new URL(u);
628
+ if (parsed.host)
629
+ urlHostSet.add(parsed.host);
630
+ }
631
+ catch {
632
+ // ignore unparseable URLs
633
+ }
634
+ }
635
+ const urlHosts = [...urlHostSet];
636
+ const flags = [...flagSet];
637
+ const intents = [...intentSet];
638
+ const hasSensitiveTarget = paths.some((p) => p.sensitive) || files.some((f) => f.sensitive);
639
+ // Build ranked, deduplicated pattern suggestions
640
+ const suggestions = [];
641
+ const seenPatterns = new Set();
642
+ const pushSuggestion = (s) => {
643
+ if (seenPatterns.has(s.pattern))
644
+ return;
645
+ seenPatterns.add(s.pattern);
646
+ suggestions.push({ id: `sug_${suggestions.length}`, ...s });
647
+ };
648
+ for (const t of dedupTools.filter((x) => x.primary)) {
649
+ pushSuggestion({ kind: 'tool', label: t.name, pattern: `*${t.name}*`, operator: 'glob' });
650
+ if (t.subcommand) {
651
+ pushSuggestion({ kind: 'tool', label: `${t.name} ${t.subcommand}`, pattern: `*${t.name}*${t.subcommand}*`, operator: 'glob' });
652
+ }
653
+ }
654
+ for (const f of files) {
655
+ pushSuggestion({ kind: 'file', label: f.name, pattern: `*${f.path}*`, operator: 'glob' });
656
+ }
657
+ for (const p of paths) {
658
+ pushSuggestion({ kind: 'path', label: p.path, pattern: `*${p.path}/*`, operator: 'glob' });
659
+ }
660
+ for (const u of urls) {
661
+ try {
662
+ const parsed = new URL(u);
663
+ pushSuggestion({ kind: 'url', label: parsed.host, pattern: `*${parsed.host}/*`, operator: 'glob' });
664
+ }
665
+ catch {
666
+ pushSuggestion({ kind: 'url', label: u.slice(0, 28), pattern: `*${u}*`, operator: 'glob' });
667
+ }
668
+ }
669
+ const evasionSignals = [...evasionSet];
670
+ const opaque = evasionSignals.length > 0;
671
+ return { tools: dedupTools, paths, files, urls, urlHosts, flags, intents, hasSensitiveTarget, opaque, evasionSignals, suggestions };
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
  }
@@ -11,7 +11,8 @@ import { compilePolicyRegex } from './match.js';
11
11
  */
12
12
  const RISK_LEVELS = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
13
13
  const EFFECTS = ['ALLOW', 'OBSERVE', 'REQUIRE_APPROVAL', 'DENY'];
14
- const argPredicateSchema = z
14
+ const COMMAND_INTENTS = ['read', 'write', 'delete', 'network', 'exec'];
15
+ const argPredicateSchema = z.lazy(() => z
15
16
  .object({
16
17
  eq: z.unknown().optional(),
17
18
  gt: z.number().optional(),
@@ -19,20 +20,42 @@ const argPredicateSchema = z
19
20
  lt: z.number().optional(),
20
21
  lte: z.number().optional(),
21
22
  regex: z.string().optional(),
23
+ notRegex: z.string().optional(),
22
24
  glob: z.string().optional(),
23
- notGlob: z.string().optional()
25
+ notGlob: z.string().optional(),
26
+ containsAll: z.array(z.string().min(1)).optional(),
27
+ allOf: z.array(argPredicateSchema).optional()
28
+ })
29
+ .strict());
30
+ const commandMatchSchema = z
31
+ .object({
32
+ tools: z.array(z.string().min(1)).optional(),
33
+ subcommands: z.array(z.string().min(1)).optional(),
34
+ intents: z.array(z.enum(COMMAND_INTENTS)).optional(),
35
+ paths: z.array(z.string().min(1)).optional(),
36
+ excludePaths: z.array(z.string().min(1)).optional(),
37
+ urls: z.array(z.string().min(1)).optional(),
38
+ flags: z.array(z.string().min(1)).optional(),
39
+ excludeFlags: z.array(z.string().min(1)).optional(),
40
+ sensitive: z.boolean().optional()
41
+ })
42
+ .strict();
43
+ const ruleMatchSchema = z
44
+ .object({
45
+ tool: z.string().min(1),
46
+ agentIds: z.array(z.string().min(1)).optional(),
47
+ environments: z.array(z.string().min(1)).optional(),
48
+ args: z.record(z.string(), argPredicateSchema).optional(),
49
+ command: commandMatchSchema.optional()
24
50
  })
25
51
  .strict();
26
52
  const ruleSchema = z
27
53
  .object({
28
54
  id: z.string().min(1),
29
55
  name: z.string().trim().min(1).max(120).optional(),
30
- match: z
31
- .object({
32
- tool: z.string().min(1),
33
- args: z.record(z.string(), argPredicateSchema).optional()
34
- })
35
- .strict(),
56
+ description: z.string().trim().min(1).max(500).optional(),
57
+ tags: z.array(z.string().trim().min(1).max(40)).max(20).optional(),
58
+ match: ruleMatchSchema,
36
59
  effect: z.enum(EFFECTS),
37
60
  riskLevel: z.enum(RISK_LEVELS).optional(),
38
61
  approversRequired: z.number().int().min(1).max(10).optional(),
@@ -42,12 +65,7 @@ const ruleSchema = z
42
65
  const autoRuleSchema = z
43
66
  .object({
44
67
  id: z.string().min(1),
45
- match: z
46
- .object({
47
- tool: z.string().min(1),
48
- args: z.record(z.string(), argPredicateSchema).optional()
49
- })
50
- .strict(),
68
+ match: ruleMatchSchema,
51
69
  agentIds: z.array(z.string()).optional(),
52
70
  maxRiskLevel: z.enum(RISK_LEVELS).optional(),
53
71
  expiresAt: z.string(),
@@ -68,6 +86,27 @@ const policyDocumentSchema = z
68
86
  autoRules: z.array(autoRuleSchema).optional()
69
87
  })
70
88
  .strict();
89
+ function checkArgPredicateRegexes(predicate, ruleId, argName, source, depth = 0) {
90
+ if (depth > 8) {
91
+ throw new PolicyError('POLICY_INVALID', `rule ${ruleId} in ${source}: predicate nesting too deep for arg '${argName}'`);
92
+ }
93
+ for (const field of ['regex', 'notRegex']) {
94
+ const pattern = predicate[field];
95
+ if (typeof pattern === 'string') {
96
+ try {
97
+ compilePolicyRegex(pattern);
98
+ }
99
+ catch {
100
+ throw new PolicyError('POLICY_INVALID', `rule ${ruleId} in ${source}: invalid ${field} for arg '${argName}'`);
101
+ }
102
+ }
103
+ }
104
+ if (predicate.allOf) {
105
+ for (const sub of predicate.allOf) {
106
+ checkArgPredicateRegexes(sub, ruleId, argName, source, depth + 1);
107
+ }
108
+ }
109
+ }
71
110
  function semanticChecks(parsed, source) {
72
111
  const seen = new Set();
73
112
  for (const rule of parsed.rules) {
@@ -80,14 +119,7 @@ function semanticChecks(parsed, source) {
80
119
  }
81
120
  const args = rule.match.args ?? {};
82
121
  for (const [name, predicate] of Object.entries(args)) {
83
- if (typeof predicate.regex === 'string') {
84
- try {
85
- compilePolicyRegex(predicate.regex);
86
- }
87
- catch {
88
- throw new PolicyError('POLICY_INVALID', `rule ${rule.id} in ${source}: invalid regex for arg '${name}'`);
89
- }
90
- }
122
+ checkArgPredicateRegexes(predicate, rule.id, name, source);
91
123
  }
92
124
  }
93
125
  const seenAuto = new Set();
@@ -1,4 +1,4 @@
1
- import type { ArgPredicate, RuleMatch, EvalInput } from './types.js';
1
+ import type { ArgPredicate, CommandMatch, RuleMatch, EvalInput } from './types.js';
2
2
  /**
3
3
  * Compile a policy regex predicate. The spec (docs/02 section 3.4)
4
4
  * uses PCRE-style inline flags, e.g. `(?i)\bdrop\b`; JavaScript has no
@@ -18,9 +18,29 @@ export declare function toolMatches(pattern: string, tool: string): boolean;
18
18
  * condition must hold (AND). A non-matching value simply fails the
19
19
  * predicate; invalid configuration (bad regex) throws PolicyError.
20
20
  */
21
- export declare function argMatches(predicate: ArgPredicate, value: unknown): boolean;
21
+ export declare function argMatches(predicate: ArgPredicate, value: unknown, depth?: number): boolean;
22
+ /** Resolve exact key first, then dot-notation nested path (e.g. "headers.host"). */
23
+ export declare function resolveArgPath(args: Record<string, unknown>, key: string): {
24
+ found: boolean;
25
+ value: unknown;
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
+ }
36
+ /** Evaluate structured shell command matching using `analyzeCommand()`. */
37
+ export declare function commandMatches(cmdMatch: CommandMatch, args: Record<string, unknown>, options?: MatchOptions): boolean;
22
38
  /**
23
- * A rule matches when its tool glob matches and every argument predicate
24
- * holds. A predicate referencing an absent argument fails the rule.
39
+ * A rule matches when its tool glob matches, optional agentIds/environments
40
+ * scopes match, every argument predicate holds, and optional structured
41
+ * command matching holds. A predicate referencing an absent argument fails
42
+ * the rule.
25
43
  */
26
- 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;
@@ -1,11 +1,21 @@
1
1
  import { PolicyError } from '../errors.js';
2
2
  import { jcs } from '../crypto/jcs.js';
3
+ import { analyzeCommand } from './command-analyzer.js';
3
4
  /**
4
5
  * Deterministic matching (docs/02 section 3.4, FR-3.1).
5
6
  * Pure functions, no side effects, no randomness.
6
7
  */
8
+ const MAX_CACHE_ENTRIES = 2048;
7
9
  const globCache = new Map();
8
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
+ }
9
19
  function escapeRegExp(ch) {
10
20
  return /[.*+?^${}()|[\]\\]/.test(ch) ? '\\' + ch : ch;
11
21
  }
@@ -39,7 +49,7 @@ export function compilePolicyRegex(pattern) {
39
49
  }
40
50
  }
41
51
  const re = new RegExp(body, flags);
42
- regexCache.set(pattern, re);
52
+ cacheSet(regexCache, pattern, re);
43
53
  return re;
44
54
  }
45
55
  /**
@@ -59,7 +69,7 @@ export function toolMatches(pattern, tool) {
59
69
  body += escapeRegExp(ch);
60
70
  }
61
71
  re = new RegExp(`^${body}$`);
62
- globCache.set(pattern, re);
72
+ cacheSet(globCache, pattern, re);
63
73
  }
64
74
  return re.test(tool);
65
75
  }
@@ -78,7 +88,9 @@ function deepEqual(a, b) {
78
88
  * condition must hold (AND). A non-matching value simply fails the
79
89
  * predicate; invalid configuration (bad regex) throws PolicyError.
80
90
  */
81
- export function argMatches(predicate, value) {
91
+ export function argMatches(predicate, value, depth = 0) {
92
+ if (depth > 8)
93
+ return false;
82
94
  if (predicate.eq !== undefined && !deepEqual(value, predicate.eq))
83
95
  return false;
84
96
  if (typeof predicate.gt === 'number') {
@@ -110,6 +122,17 @@ export function argMatches(predicate, value) {
110
122
  if (!re.test(value))
111
123
  return false;
112
124
  }
125
+ if (typeof predicate.notRegex === 'string') {
126
+ let re;
127
+ try {
128
+ re = compilePolicyRegex(predicate.notRegex);
129
+ }
130
+ catch {
131
+ throw new PolicyError('POLICY_INVALID', `invalid notRegex in predicate: ${predicate.notRegex}`);
132
+ }
133
+ if (typeof value === 'string' && re.test(value))
134
+ return false;
135
+ }
113
136
  if (typeof predicate.glob === 'string') {
114
137
  if (typeof value !== 'string' || !toolMatches(predicate.glob, value))
115
138
  return false;
@@ -119,23 +142,175 @@ export function argMatches(predicate, value) {
119
142
  if (typeof value === 'string' && toolMatches(predicate.notGlob, value))
120
143
  return false;
121
144
  }
145
+ if (predicate.containsAll && predicate.containsAll.length > 0) {
146
+ if (typeof value !== 'string')
147
+ return false;
148
+ for (const needle of predicate.containsAll) {
149
+ if (needle.includes('*') || needle.includes('?')) {
150
+ if (!toolMatches(needle, value))
151
+ return false;
152
+ }
153
+ else if (!value.includes(needle)) {
154
+ return false;
155
+ }
156
+ }
157
+ }
158
+ if (predicate.allOf && predicate.allOf.length > 0) {
159
+ for (const sub of predicate.allOf) {
160
+ if (!argMatches(sub, value, depth + 1))
161
+ return false;
162
+ }
163
+ }
164
+ return true;
165
+ }
166
+ /** Resolve exact key first, then dot-notation nested path (e.g. "headers.host"). */
167
+ export function resolveArgPath(args, key) {
168
+ if (key in args)
169
+ return { found: true, value: args[key] };
170
+ if (!key.includes('.'))
171
+ return { found: false, value: undefined };
172
+ const parts = key.split('.');
173
+ let cur = args;
174
+ for (const part of parts) {
175
+ if (!part || cur === null || typeof cur !== 'object' || Array.isArray(cur)) {
176
+ return { found: false, value: undefined };
177
+ }
178
+ const record = cur;
179
+ if (!(part in record))
180
+ return { found: false, value: undefined };
181
+ cur = record[part];
182
+ }
183
+ return { found: true, value: cur };
184
+ }
185
+ function extractCommandText(args) {
186
+ for (const key of ['command', 'cmd', 'script']) {
187
+ const v = args[key];
188
+ if (typeof v === 'string' && v.trim().length > 0)
189
+ return v;
190
+ }
191
+ for (const [k, v] of Object.entries(args)) {
192
+ const lk = k.toLowerCase();
193
+ if ((lk === 'command' || lk === 'cmd' || lk === 'script') && typeof v === 'string' && v.trim().length > 0) {
194
+ return v;
195
+ }
196
+ }
197
+ return null;
198
+ }
199
+ function anyGlobMatches(patterns, candidates) {
200
+ for (const cand of candidates) {
201
+ for (const pat of patterns) {
202
+ if (toolMatches(pat, cand))
203
+ return true;
204
+ }
205
+ }
206
+ return false;
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
+ }
213
+ /** Evaluate structured shell command matching using `analyzeCommand()`. */
214
+ export function commandMatches(cmdMatch, args, options = {}) {
215
+ const cmdText = extractCommandText(args);
216
+ if (!cmdText)
217
+ return false;
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;
224
+ if (cmdMatch.tools && cmdMatch.tools.length > 0) {
225
+ const names = analysis.tools.map((t) => t.name);
226
+ if (!listMatch(cmdMatch.tools, names))
227
+ return false;
228
+ }
229
+ if (cmdMatch.subcommands && cmdMatch.subcommands.length > 0) {
230
+ const subs = analysis.tools.map((t) => t.subcommand).filter((s) => typeof s === 'string');
231
+ if (!listMatch(cmdMatch.subcommands, subs))
232
+ return false;
233
+ }
234
+ if (cmdMatch.intents && cmdMatch.intents.length > 0) {
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))) {
240
+ return false;
241
+ }
242
+ }
243
+ const allPaths = [...analysis.paths.map((p) => p.path), ...analysis.files.map((f) => f.path)];
244
+ if (cmdMatch.paths && cmdMatch.paths.length > 0) {
245
+ if (!listMatch(cmdMatch.paths, allPaths))
246
+ return false;
247
+ }
248
+ if (cmdMatch.excludePaths && cmdMatch.excludePaths.length > 0) {
249
+ if (anyGlobMatches(cmdMatch.excludePaths, allPaths))
250
+ return false;
251
+ }
252
+ if (cmdMatch.urls && cmdMatch.urls.length > 0) {
253
+ const urlTargets = [...analysis.urls, ...analysis.urlHosts];
254
+ if (!listMatch(cmdMatch.urls, urlTargets))
255
+ return false;
256
+ }
257
+ if (cmdMatch.flags && cmdMatch.flags.length > 0) {
258
+ if (!anyGlobMatches(cmdMatch.flags, analysis.flags))
259
+ return false;
260
+ }
261
+ if (cmdMatch.excludeFlags && cmdMatch.excludeFlags.length > 0) {
262
+ if (anyGlobMatches(cmdMatch.excludeFlags, analysis.flags))
263
+ return false;
264
+ }
265
+ if (cmdMatch.sensitive !== undefined) {
266
+ if (analysis.hasSensitiveTarget !== cmdMatch.sensitive)
267
+ return false;
268
+ }
122
269
  return true;
123
270
  }
124
271
  /**
125
- * A rule matches when its tool glob matches and every argument predicate
126
- * holds. A predicate referencing an absent argument fails the rule.
272
+ * A rule matches when its tool glob matches, optional agentIds/environments
273
+ * scopes match, every argument predicate holds, and optional structured
274
+ * command matching holds. A predicate referencing an absent argument fails
275
+ * the rule.
127
276
  */
128
- export function ruleMatches(match, input) {
277
+ export function ruleMatches(match, input, options = {}) {
129
278
  if (!toolMatches(match.tool, input.tool))
130
279
  return false;
280
+ if (match.agentIds && match.agentIds.length > 0) {
281
+ if (!input.agentId || !anyGlobMatches(match.agentIds, [input.agentId]))
282
+ return false;
283
+ }
284
+ if (match.environments && match.environments.length > 0) {
285
+ if (!input.environment)
286
+ return false;
287
+ const envLower = input.environment.toLowerCase();
288
+ const matchedEnv = match.environments.some((e) => toolMatches(e.toLowerCase(), envLower));
289
+ if (!matchedEnv)
290
+ return false;
291
+ }
292
+ const args = input.args ?? {};
131
293
  if (match.args) {
132
- const args = input.args ?? {};
133
294
  for (const [name, predicate] of Object.entries(match.args)) {
134
- if (!(name in args))
295
+ const resolved = resolveArgPath(args, name);
296
+ if (!resolved.found)
135
297
  return false;
136
- if (!argMatches(predicate, args[name]))
298
+ if (!argMatches(predicate, resolved.value))
137
299
  return false;
138
300
  }
139
301
  }
302
+ if (match.command) {
303
+ if (!commandMatches(match.command, args, options))
304
+ return false;
305
+ }
140
306
  return true;
141
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
+ }
@@ -4,6 +4,7 @@
4
4
  * Policies are evaluated deterministically and locally. The backend
5
5
  * re-evaluates the same bundle and can only escalate risk, never lower it.
6
6
  */
7
+ import type { CommandIntent } from './command-analyzer.js';
7
8
  export type RiskLevel = 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
8
9
  export type Effect = 'ALLOW' | 'OBSERVE' | 'REQUIRE_APPROVAL' | 'DENY';
9
10
  export type UnmatchedDefault = 'ALLOW' | 'OBSERVE' | 'REQUIRE_APPROVAL';
@@ -15,19 +16,55 @@ export interface ArgPredicate {
15
16
  lt?: number;
16
17
  lte?: number;
17
18
  regex?: string;
19
+ notRegex?: string;
18
20
  glob?: string;
19
21
  notGlob?: string;
22
+ /** Every substring or glob in the array must match (string values). */
23
+ containsAll?: string[];
24
+ /** Combine multiple predicates on the same argument (AND). */
25
+ allOf?: ArgPredicate[];
26
+ }
27
+ /** Structured shell command matching derived from `analyzeCommand()`. */
28
+ export interface CommandMatch {
29
+ /** Match any detected tool name (glob, e.g. "git", "python*"). */
30
+ tools?: string[];
31
+ /** Match any detected subcommand (glob, e.g. "push", "delete*"). */
32
+ subcommands?: string[];
33
+ /** Match if any detected intent is in this list. */
34
+ intents?: CommandIntent[];
35
+ /** Match if any detected path or file path matches any glob here. */
36
+ paths?: string[];
37
+ /** Exclude if any detected path or file path matches any glob here. */
38
+ excludePaths?: string[];
39
+ /** Match if any detected URL or host matches any glob here. */
40
+ urls?: string[];
41
+ /** Match if any detected flag is present (glob, e.g. "--force", "-rf"). */
42
+ flags?: string[];
43
+ /** Exclude if any detected flag is present (glob). */
44
+ excludeFlags?: string[];
45
+ /** Require (true) or exclude (false) commands touching sensitive paths. */
46
+ sensitive?: boolean;
20
47
  }
21
48
  export interface RuleMatch {
22
49
  /** Tool-name glob (e.g. "sql.*", "stripe.refund"). */
23
50
  tool: string;
24
- /** Predicates keyed by first-level payload argument name. */
51
+ /** Optional agent IDs or globs this rule applies to (empty or absent means all). */
52
+ agentIds?: string[];
53
+ /** Optional environments this rule applies to (e.g. ["prod", "staging"]). */
54
+ environments?: string[];
55
+ /** Predicates keyed by payload argument name (supports dot-notation e.g. "headers.host"). */
25
56
  args?: Record<string, ArgPredicate>;
57
+ /** Structured shell command matching using analyzeCommand(). */
58
+ command?: CommandMatch;
26
59
  }
27
60
  export interface PolicyRule {
28
61
  id: string;
29
62
  /** Human-readable name for the rule (displayed in app & dashboard). */
30
63
  name?: string;
64
+ /** Optional longer explanation of what the rule guards and why. */
65
+ description?: string;
66
+ /** Optional categorization tags for filtering in web & mobile. */
67
+ tags?: string[];
31
68
  match: RuleMatch;
32
69
  effect: Effect;
33
70
  /** Required for effect REQUIRE_APPROVAL. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aithorized/core",
3
- "version": "0.1.5",
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",