@aithorized/core 0.1.5 → 0.2.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 +4 -2
- package/dist/index.js +2 -1
- package/dist/policy/browser.d.ts +4 -2
- package/dist/policy/browser.js +2 -1
- package/dist/policy/command-analyzer.d.ts +45 -0
- package/dist/policy/command-analyzer.js +442 -0
- package/dist/policy/load.js +54 -22
- package/dist/policy/match.d.ts +13 -4
- package/dist/policy/match.js +148 -6
- package/dist/policy/types.d.ts +38 -1
- package/package.json +1 -1
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';
|
package/dist/policy/browser.d.ts
CHANGED
|
@@ -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 {
|
|
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';
|
package/dist/policy/browser.js
CHANGED
|
@@ -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,45 @@
|
|
|
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
|
+
suggestions: CommandPatternSuggestion[];
|
|
36
|
+
}
|
|
37
|
+
/** Split command string into segments on `&&`, `||`, `;`, `|`, `\n` outside quotes. */
|
|
38
|
+
export declare function splitShellSegments(command: string): {
|
|
39
|
+
segment: string;
|
|
40
|
+
piped: boolean;
|
|
41
|
+
}[];
|
|
42
|
+
/** Tokenize a single shell segment respecting quotes and escapes. */
|
|
43
|
+
export declare function tokenizeSegment(segment: string): string[];
|
|
44
|
+
/** Analyze a shell command string for tools, subcommands, paths, files, URLs, flags, and intents. */
|
|
45
|
+
export declare function analyzeCommand(command: string, depth?: number): CommandAnalysis;
|
|
@@ -0,0 +1,442 @@
|
|
|
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']);
|
|
5
|
+
const READ_TOOLS = new Set(['cat', 'head', 'tail', 'less', 'more', 'grep', 'rg', 'find', 'ls', 'stat', 'read', 'get', 'list', 'psql', 'sqlite3']);
|
|
6
|
+
const WRITE_TOOLS = new Set(['cp', 'mv', 'tee', 'mkdir', 'touch', 'chmod', 'chown', 'ln', 'sed', 'awk', 'tar', 'unzip', 'zip']);
|
|
7
|
+
const DELETE_TOOLS = new Set(['rm', 'rmdir', 'unlink', 'shred']);
|
|
8
|
+
const NETWORK_TOOLS = new Set(['curl', 'wget', 'ssh', 'scp', 'rsync', 'nc', 'ncat', 'fetch', 'ping', 'dig']);
|
|
9
|
+
const READ_SUBCOMMANDS = new Set(['read', 'get', 'list', 'show', 'status', 'log', 'diff', 'search', 'inspect', 'view', 'describe']);
|
|
10
|
+
const WRITE_SUBCOMMANDS = new Set(['write', 'create', 'update', 'put', 'post', 'apply', 'push', 'install', 'add', 'set', 'deploy', 'send']);
|
|
11
|
+
const DELETE_SUBCOMMANDS = new Set(['delete', 'remove', 'rm', 'drop', 'destroy', 'purge', 'revoke', 'terminate', 'kill']);
|
|
12
|
+
const FLAGS_WITH_VALUE = new Set([
|
|
13
|
+
'-c', '-f', '-o', '-i', '-d', '-n', '-m', '-p', '-u', '-H', '-X', '-C',
|
|
14
|
+
'--account', '--config', '--dir', '--file', '--output', '--input', '--profile',
|
|
15
|
+
'--region', '--namespace', '--project', '--filter', '--format', '--header', '--data'
|
|
16
|
+
]);
|
|
17
|
+
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;
|
|
18
|
+
const KNOWN_DOTFILES = /^\.(env(\..+)?|gitignore|npmrc|bashrc|zshrc|profile)$/i;
|
|
19
|
+
const SENSITIVE_PATTERN = /(^|\/)(\.ssh|\.aws|\.gnupg|\.hermes|\.env(\.|$)|etc\/|id_rsa|id_ed25519|credentials|secrets?|\.pem$|\.key$)/i;
|
|
20
|
+
function unquote(token) {
|
|
21
|
+
if (token.length >= 2) {
|
|
22
|
+
const first = token[0];
|
|
23
|
+
const last = token[token.length - 1];
|
|
24
|
+
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
|
|
25
|
+
return token.slice(1, -1);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return token;
|
|
29
|
+
}
|
|
30
|
+
function basenameOf(p) {
|
|
31
|
+
const cleaned = p.replace(/[\\/]+$/, '');
|
|
32
|
+
const parts = cleaned.split(/[\\/]/);
|
|
33
|
+
return parts[parts.length - 1] || cleaned;
|
|
34
|
+
}
|
|
35
|
+
function dirnameOf(p) {
|
|
36
|
+
const idx = Math.max(p.lastIndexOf('/'), p.lastIndexOf('\\'));
|
|
37
|
+
if (idx <= 0)
|
|
38
|
+
return idx === 0 ? '/' : null;
|
|
39
|
+
const dir = p.slice(0, idx);
|
|
40
|
+
return dir && dir !== '.' ? dir : null;
|
|
41
|
+
}
|
|
42
|
+
function isSensitive(p) {
|
|
43
|
+
return SENSITIVE_PATTERN.test(p.replace(/\\/g, '/'));
|
|
44
|
+
}
|
|
45
|
+
function isUrl(token) {
|
|
46
|
+
return /^(https?|s3|gs):\/\/\S+/i.test(token);
|
|
47
|
+
}
|
|
48
|
+
/** Split command string into segments on `&&`, `||`, `;`, `|`, `\n` outside quotes. */
|
|
49
|
+
export function splitShellSegments(command) {
|
|
50
|
+
const out = [];
|
|
51
|
+
let buf = '';
|
|
52
|
+
let quote = null;
|
|
53
|
+
let piped = false;
|
|
54
|
+
for (let i = 0; i < command.length; i++) {
|
|
55
|
+
const ch = command[i] ?? '';
|
|
56
|
+
const next = command[i + 1] ?? '';
|
|
57
|
+
if (quote) {
|
|
58
|
+
if (ch === '\\' && quote === '"' && i + 1 < command.length) {
|
|
59
|
+
buf += ch + next;
|
|
60
|
+
i++;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (ch === quote)
|
|
64
|
+
quote = null;
|
|
65
|
+
buf += ch;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (ch === '"' || ch === "'") {
|
|
69
|
+
quote = ch;
|
|
70
|
+
buf += ch;
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if ((ch === '&' && next === '&') || (ch === '|' && next === '|')) {
|
|
74
|
+
if (buf.trim())
|
|
75
|
+
out.push({ segment: buf.trim(), piped });
|
|
76
|
+
buf = '';
|
|
77
|
+
piped = false;
|
|
78
|
+
i++;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (ch === ';' || ch === '\n') {
|
|
82
|
+
if (buf.trim())
|
|
83
|
+
out.push({ segment: buf.trim(), piped });
|
|
84
|
+
buf = '';
|
|
85
|
+
piped = false;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (ch === '|') {
|
|
89
|
+
if (buf.trim())
|
|
90
|
+
out.push({ segment: buf.trim(), piped });
|
|
91
|
+
buf = '';
|
|
92
|
+
piped = true;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
buf += ch;
|
|
96
|
+
}
|
|
97
|
+
if (buf.trim())
|
|
98
|
+
out.push({ segment: buf.trim(), piped });
|
|
99
|
+
return out;
|
|
100
|
+
}
|
|
101
|
+
/** Tokenize a single shell segment respecting quotes and escapes. */
|
|
102
|
+
export function tokenizeSegment(segment) {
|
|
103
|
+
const tokens = [];
|
|
104
|
+
let buf = '';
|
|
105
|
+
let quote = null;
|
|
106
|
+
for (let i = 0; i < segment.length; i++) {
|
|
107
|
+
const ch = segment[i] ?? '';
|
|
108
|
+
const next = segment[i + 1] ?? '';
|
|
109
|
+
if (quote) {
|
|
110
|
+
if (ch === '\\' && quote === '"' && i + 1 < segment.length) {
|
|
111
|
+
buf += next;
|
|
112
|
+
i++;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (ch === quote) {
|
|
116
|
+
quote = null;
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
buf += ch;
|
|
120
|
+
}
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (ch === '"' || ch === "'") {
|
|
124
|
+
quote = ch;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (/\s/.test(ch)) {
|
|
128
|
+
if (buf.length > 0) {
|
|
129
|
+
tokens.push(buf);
|
|
130
|
+
buf = '';
|
|
131
|
+
}
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
buf += ch;
|
|
135
|
+
}
|
|
136
|
+
if (buf.length > 0)
|
|
137
|
+
tokens.push(buf);
|
|
138
|
+
return tokens;
|
|
139
|
+
}
|
|
140
|
+
function classifyFileToken(token) {
|
|
141
|
+
const t = token.replace(/^@/, '');
|
|
142
|
+
if (!t || t === '~' || t === '.' || t === '..' || t === '/dev/null' || isUrl(t))
|
|
143
|
+
return 'none';
|
|
144
|
+
if (/^[0-9]+$/.test(t))
|
|
145
|
+
return 'none';
|
|
146
|
+
const looksLikePath = t.startsWith('/') || t.startsWith('~/') || t.startsWith('./') || t.startsWith('../') || /^[A-Za-z]:[\\/]/.test(t) || t.includes('/');
|
|
147
|
+
const base = basenameOf(t);
|
|
148
|
+
if (t.endsWith('/') || t.endsWith('\\'))
|
|
149
|
+
return 'path';
|
|
150
|
+
if (KNOWN_FILE_EXT.test(base) || KNOWN_DOTFILES.test(base))
|
|
151
|
+
return 'file';
|
|
152
|
+
if (looksLikePath)
|
|
153
|
+
return 'path';
|
|
154
|
+
return 'none';
|
|
155
|
+
}
|
|
156
|
+
/** Analyze a shell command string for tools, subcommands, paths, files, URLs, flags, and intents. */
|
|
157
|
+
export function analyzeCommand(command, depth = 0) {
|
|
158
|
+
const tools = [];
|
|
159
|
+
const pathMap = new Map();
|
|
160
|
+
const fileMap = new Map();
|
|
161
|
+
const urlSet = new Set();
|
|
162
|
+
const flagSet = new Set();
|
|
163
|
+
const intentSet = new Set();
|
|
164
|
+
const recordPath = (rawPath) => {
|
|
165
|
+
const p = rawPath.replace(/[\\/]+$/, '') || '/';
|
|
166
|
+
if (!p || p === '.' || p === '~' || p === '/dev' || p === '/dev/null')
|
|
167
|
+
return;
|
|
168
|
+
if (!pathMap.has(p))
|
|
169
|
+
pathMap.set(p, { path: p, sensitive: isSensitive(p) });
|
|
170
|
+
};
|
|
171
|
+
const recordFile = (rawFile, access) => {
|
|
172
|
+
const cleaned = rawFile.replace(/^@/, '');
|
|
173
|
+
if (!cleaned || cleaned === '/dev/null')
|
|
174
|
+
return;
|
|
175
|
+
const existing = fileMap.get(cleaned);
|
|
176
|
+
if (!existing) {
|
|
177
|
+
fileMap.set(cleaned, {
|
|
178
|
+
path: cleaned,
|
|
179
|
+
name: basenameOf(cleaned),
|
|
180
|
+
access,
|
|
181
|
+
sensitive: isSensitive(cleaned)
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
else if (existing.access === 'unknown' && access !== 'unknown') {
|
|
185
|
+
existing.access = access;
|
|
186
|
+
}
|
|
187
|
+
const dir = dirnameOf(cleaned);
|
|
188
|
+
if (dir)
|
|
189
|
+
recordPath(dir);
|
|
190
|
+
};
|
|
191
|
+
const inspectToken = (raw, defaultAccess) => {
|
|
192
|
+
const t = unquote(raw);
|
|
193
|
+
if (!t || t === '/dev/null')
|
|
194
|
+
return;
|
|
195
|
+
if (isUrl(t)) {
|
|
196
|
+
urlSet.add(t);
|
|
197
|
+
intentSet.add('network');
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const kind = classifyFileToken(t);
|
|
201
|
+
if (kind === 'file')
|
|
202
|
+
recordFile(t, defaultAccess);
|
|
203
|
+
else if (kind === 'path')
|
|
204
|
+
recordPath(t);
|
|
205
|
+
};
|
|
206
|
+
const mergeSubAnalysis = (sub) => {
|
|
207
|
+
for (const tool of sub.tools)
|
|
208
|
+
tools.push(tool);
|
|
209
|
+
for (const p of sub.paths)
|
|
210
|
+
if (!pathMap.has(p.path))
|
|
211
|
+
pathMap.set(p.path, p);
|
|
212
|
+
for (const f of sub.files)
|
|
213
|
+
if (!fileMap.has(f.path))
|
|
214
|
+
fileMap.set(f.path, f);
|
|
215
|
+
for (const u of sub.urls)
|
|
216
|
+
urlSet.add(u);
|
|
217
|
+
for (const fl of sub.flags)
|
|
218
|
+
flagSet.add(fl);
|
|
219
|
+
for (const i of sub.intents)
|
|
220
|
+
intentSet.add(i);
|
|
221
|
+
};
|
|
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));
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
for (const { segment, piped } of splitShellSegments(command)) {
|
|
232
|
+
const tokens = tokenizeSegment(segment);
|
|
233
|
+
let idx = 0;
|
|
234
|
+
// Strip VAR=val env prefixes
|
|
235
|
+
while (idx < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[idx] ?? '')) {
|
|
236
|
+
const eqPos = (tokens[idx] ?? '').indexOf('=');
|
|
237
|
+
inspectToken((tokens[idx] ?? '').slice(eqPos + 1), 'unknown');
|
|
238
|
+
idx++;
|
|
239
|
+
}
|
|
240
|
+
// Strip sudo / env / nohup wrappers
|
|
241
|
+
while (idx < tokens.length && SHELL_WRAPPERS.has(basenameOf(tokens[idx] ?? '').toLowerCase())) {
|
|
242
|
+
const wrapperName = basenameOf(tokens[idx] ?? '').toLowerCase();
|
|
243
|
+
if (wrapperName === 'sudo')
|
|
244
|
+
flagSet.add('sudo');
|
|
245
|
+
idx++;
|
|
246
|
+
while (idx < tokens.length && (tokens[idx] ?? '').startsWith('-')) {
|
|
247
|
+
flagSet.add(tokens[idx] ?? '');
|
|
248
|
+
idx++;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
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
|
|
265
|
+
const cleanTokens = [];
|
|
266
|
+
for (let i = idx; i < tokens.length; i++) {
|
|
267
|
+
const tok = tokens[i] ?? '';
|
|
268
|
+
const redirMatch = tok.match(/^(?:\d*)(>>|>|<)(.*)$/);
|
|
269
|
+
if (redirMatch) {
|
|
270
|
+
const op = redirMatch[1];
|
|
271
|
+
const inlineTarget = redirMatch[2];
|
|
272
|
+
const target = inlineTarget || tokens[i + 1];
|
|
273
|
+
if (!inlineTarget && target)
|
|
274
|
+
i++;
|
|
275
|
+
if (target && target !== '/dev/null' && !target.startsWith('&')) {
|
|
276
|
+
const access = op === '<' ? 'read' : 'write';
|
|
277
|
+
inspectToken(target, access);
|
|
278
|
+
intentSet.add(access === 'read' ? 'read' : 'write');
|
|
279
|
+
}
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
cleanTokens.push(tok);
|
|
283
|
+
}
|
|
284
|
+
const cmdToken = cleanTokens[0];
|
|
285
|
+
if (!cmdToken)
|
|
286
|
+
continue;
|
|
287
|
+
const cmdName = basenameOf(cmdToken);
|
|
288
|
+
const cmdLower = cmdName.toLowerCase();
|
|
289
|
+
// Handle `bash -c "..."` / `sh -c "..."` inline scripts recursively
|
|
290
|
+
if ((cmdLower === 'bash' || cmdLower === 'sh' || cmdLower === 'zsh') && depth < 2) {
|
|
291
|
+
const cIdx = cleanTokens.indexOf('-c');
|
|
292
|
+
const inlineScript = cIdx !== -1 ? cleanTokens[cIdx + 1] : undefined;
|
|
293
|
+
if (inlineScript) {
|
|
294
|
+
intentSet.add('exec');
|
|
295
|
+
mergeSubAnalysis(analyzeCommand(inlineScript, depth + 1));
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
let toolName = cmdName;
|
|
300
|
+
let runtime;
|
|
301
|
+
let argStart = 1;
|
|
302
|
+
// Resolve script target for runtimes (python3 ~/.hermes/bin/mailguard.py ...)
|
|
303
|
+
if (SHELL_RUNTIMES.has(cmdLower)) {
|
|
304
|
+
intentSet.add('exec');
|
|
305
|
+
for (let i = 1; i < cleanTokens.length; i++) {
|
|
306
|
+
const arg = cleanTokens[i] ?? '';
|
|
307
|
+
if (arg.startsWith('-')) {
|
|
308
|
+
flagSet.add(arg);
|
|
309
|
+
if ((arg === '-c' || arg === '-e') && depth < 2) {
|
|
310
|
+
// Inline python/node snippet; keep runtime as tool
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
runtime = cmdName;
|
|
316
|
+
toolName = basenameOf(arg);
|
|
317
|
+
recordFile(arg, 'exec');
|
|
318
|
+
argStart = i + 1;
|
|
319
|
+
break;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// Determine default file access from tool
|
|
323
|
+
let defaultAccess = 'unknown';
|
|
324
|
+
if (DELETE_TOOLS.has(cmdLower)) {
|
|
325
|
+
defaultAccess = 'delete';
|
|
326
|
+
intentSet.add('delete');
|
|
327
|
+
}
|
|
328
|
+
else if (WRITE_TOOLS.has(cmdLower)) {
|
|
329
|
+
defaultAccess = 'write';
|
|
330
|
+
intentSet.add('write');
|
|
331
|
+
}
|
|
332
|
+
else if (NETWORK_TOOLS.has(cmdLower)) {
|
|
333
|
+
defaultAccess = 'read';
|
|
334
|
+
intentSet.add('network');
|
|
335
|
+
}
|
|
336
|
+
else if (READ_TOOLS.has(cmdLower)) {
|
|
337
|
+
defaultAccess = 'read';
|
|
338
|
+
intentSet.add('read');
|
|
339
|
+
}
|
|
340
|
+
// Scan remaining args for subcommand, flags, files, paths, URLs
|
|
341
|
+
let subcommand;
|
|
342
|
+
for (let i = argStart; i < cleanTokens.length; i++) {
|
|
343
|
+
const arg = cleanTokens[i] ?? '';
|
|
344
|
+
if (arg.startsWith('-') && arg.length > 1) {
|
|
345
|
+
const eqIdx = arg.indexOf('=');
|
|
346
|
+
const flagName = eqIdx !== -1 ? arg.slice(0, eqIdx) : arg;
|
|
347
|
+
flagSet.add(flagName);
|
|
348
|
+
if (eqIdx !== -1) {
|
|
349
|
+
inspectToken(arg.slice(eqIdx + 1), defaultAccess);
|
|
350
|
+
}
|
|
351
|
+
else if (FLAGS_WITH_VALUE.has(arg) && i + 1 < cleanTokens.length) {
|
|
352
|
+
const val = cleanTokens[i + 1] ?? '';
|
|
353
|
+
inspectToken(val, defaultAccess);
|
|
354
|
+
i++;
|
|
355
|
+
}
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (isUrl(arg) || classifyFileToken(arg) !== 'none') {
|
|
359
|
+
inspectToken(arg, defaultAccess);
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
if (!subcommand && /^[a-zA-Z][a-zA-Z0-9_-]{1,24}$/.test(arg)) {
|
|
363
|
+
subcommand = arg;
|
|
364
|
+
const subLower = arg.toLowerCase();
|
|
365
|
+
if (READ_SUBCOMMANDS.has(subLower))
|
|
366
|
+
intentSet.add('read');
|
|
367
|
+
else if (WRITE_SUBCOMMANDS.has(subLower))
|
|
368
|
+
intentSet.add('write');
|
|
369
|
+
else if (DELETE_SUBCOMMANDS.has(subLower))
|
|
370
|
+
intentSet.add('delete');
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
const isPipeFilter = piped && PIPE_FILTERS.has(cmdLower) && !runtime;
|
|
374
|
+
const glob = subcommand ? `*${toolName}*${subcommand}*` : `*${toolName}*`;
|
|
375
|
+
tools.push({
|
|
376
|
+
name: toolName,
|
|
377
|
+
...(subcommand ? { subcommand } : {}),
|
|
378
|
+
...(runtime ? { runtime } : {}),
|
|
379
|
+
primary: !isPipeFilter,
|
|
380
|
+
glob
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
// Deduplicate tools by name+subcommand, prioritizing primary tools
|
|
384
|
+
const dedupTools = [];
|
|
385
|
+
const seenToolKey = new Set();
|
|
386
|
+
for (const t of [...tools.filter((x) => x.primary), ...tools.filter((x) => !x.primary)]) {
|
|
387
|
+
const k = `${t.name}:${t.subcommand ?? ''}`;
|
|
388
|
+
if (!seenToolKey.has(k)) {
|
|
389
|
+
seenToolKey.add(k);
|
|
390
|
+
dedupTools.push(t);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
const paths = [...pathMap.values()];
|
|
394
|
+
const files = [...fileMap.values()];
|
|
395
|
+
const urls = [...urlSet];
|
|
396
|
+
const urlHostSet = new Set();
|
|
397
|
+
for (const u of urls) {
|
|
398
|
+
try {
|
|
399
|
+
const parsed = new URL(u);
|
|
400
|
+
if (parsed.host)
|
|
401
|
+
urlHostSet.add(parsed.host);
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
// ignore unparseable URLs
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const urlHosts = [...urlHostSet];
|
|
408
|
+
const flags = [...flagSet];
|
|
409
|
+
const intents = [...intentSet];
|
|
410
|
+
const hasSensitiveTarget = paths.some((p) => p.sensitive) || files.some((f) => f.sensitive);
|
|
411
|
+
// Build ranked, deduplicated pattern suggestions
|
|
412
|
+
const suggestions = [];
|
|
413
|
+
const seenPatterns = new Set();
|
|
414
|
+
const pushSuggestion = (s) => {
|
|
415
|
+
if (seenPatterns.has(s.pattern))
|
|
416
|
+
return;
|
|
417
|
+
seenPatterns.add(s.pattern);
|
|
418
|
+
suggestions.push({ id: `sug_${suggestions.length}`, ...s });
|
|
419
|
+
};
|
|
420
|
+
for (const t of dedupTools.filter((x) => x.primary)) {
|
|
421
|
+
pushSuggestion({ kind: 'tool', label: t.name, pattern: `*${t.name}*`, operator: 'glob' });
|
|
422
|
+
if (t.subcommand) {
|
|
423
|
+
pushSuggestion({ kind: 'tool', label: `${t.name} ${t.subcommand}`, pattern: `*${t.name}*${t.subcommand}*`, operator: 'glob' });
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
for (const f of files) {
|
|
427
|
+
pushSuggestion({ kind: 'file', label: f.name, pattern: `*${f.path}*`, operator: 'glob' });
|
|
428
|
+
}
|
|
429
|
+
for (const p of paths) {
|
|
430
|
+
pushSuggestion({ kind: 'path', label: p.path, pattern: `*${p.path}/*`, operator: 'glob' });
|
|
431
|
+
}
|
|
432
|
+
for (const u of urls) {
|
|
433
|
+
try {
|
|
434
|
+
const parsed = new URL(u);
|
|
435
|
+
pushSuggestion({ kind: 'url', label: parsed.host, pattern: `*${parsed.host}/*`, operator: 'glob' });
|
|
436
|
+
}
|
|
437
|
+
catch {
|
|
438
|
+
pushSuggestion({ kind: 'url', label: u.slice(0, 28), pattern: `*${u}*`, operator: 'glob' });
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return { tools: dedupTools, paths, files, urls, urlHosts, flags, intents, hasSensitiveTarget, suggestions };
|
|
442
|
+
}
|
package/dist/policy/load.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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:
|
|
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
|
-
|
|
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();
|
package/dist/policy/match.d.ts
CHANGED
|
@@ -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,18 @@ 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
|
+
/** Evaluate structured shell command matching using `analyzeCommand()`. */
|
|
28
|
+
export declare function commandMatches(cmdMatch: CommandMatch, args: Record<string, unknown>): boolean;
|
|
22
29
|
/**
|
|
23
|
-
* A rule matches when its tool glob matches
|
|
24
|
-
*
|
|
30
|
+
* A rule matches when its tool glob matches, optional agentIds/environments
|
|
31
|
+
* scopes match, every argument predicate holds, and optional structured
|
|
32
|
+
* command matching holds. A predicate referencing an absent argument fails
|
|
33
|
+
* the rule.
|
|
25
34
|
*/
|
|
26
35
|
export declare function ruleMatches(match: RuleMatch, input: EvalInput): boolean;
|
package/dist/policy/match.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
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.
|
|
@@ -78,7 +79,9 @@ function deepEqual(a, b) {
|
|
|
78
79
|
* condition must hold (AND). A non-matching value simply fails the
|
|
79
80
|
* predicate; invalid configuration (bad regex) throws PolicyError.
|
|
80
81
|
*/
|
|
81
|
-
export function argMatches(predicate, value) {
|
|
82
|
+
export function argMatches(predicate, value, depth = 0) {
|
|
83
|
+
if (depth > 8)
|
|
84
|
+
return false;
|
|
82
85
|
if (predicate.eq !== undefined && !deepEqual(value, predicate.eq))
|
|
83
86
|
return false;
|
|
84
87
|
if (typeof predicate.gt === 'number') {
|
|
@@ -110,6 +113,17 @@ export function argMatches(predicate, value) {
|
|
|
110
113
|
if (!re.test(value))
|
|
111
114
|
return false;
|
|
112
115
|
}
|
|
116
|
+
if (typeof predicate.notRegex === 'string') {
|
|
117
|
+
let re;
|
|
118
|
+
try {
|
|
119
|
+
re = compilePolicyRegex(predicate.notRegex);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
throw new PolicyError('POLICY_INVALID', `invalid notRegex in predicate: ${predicate.notRegex}`);
|
|
123
|
+
}
|
|
124
|
+
if (typeof value === 'string' && re.test(value))
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
113
127
|
if (typeof predicate.glob === 'string') {
|
|
114
128
|
if (typeof value !== 'string' || !toolMatches(predicate.glob, value))
|
|
115
129
|
return false;
|
|
@@ -119,23 +133,151 @@ export function argMatches(predicate, value) {
|
|
|
119
133
|
if (typeof value === 'string' && toolMatches(predicate.notGlob, value))
|
|
120
134
|
return false;
|
|
121
135
|
}
|
|
136
|
+
if (predicate.containsAll && predicate.containsAll.length > 0) {
|
|
137
|
+
if (typeof value !== 'string')
|
|
138
|
+
return false;
|
|
139
|
+
for (const needle of predicate.containsAll) {
|
|
140
|
+
if (needle.includes('*') || needle.includes('?')) {
|
|
141
|
+
if (!toolMatches(needle, value))
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
else if (!value.includes(needle)) {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (predicate.allOf && predicate.allOf.length > 0) {
|
|
150
|
+
for (const sub of predicate.allOf) {
|
|
151
|
+
if (!argMatches(sub, value, depth + 1))
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
/** Resolve exact key first, then dot-notation nested path (e.g. "headers.host"). */
|
|
158
|
+
export function resolveArgPath(args, key) {
|
|
159
|
+
if (key in args)
|
|
160
|
+
return { found: true, value: args[key] };
|
|
161
|
+
if (!key.includes('.'))
|
|
162
|
+
return { found: false, value: undefined };
|
|
163
|
+
const parts = key.split('.');
|
|
164
|
+
let cur = args;
|
|
165
|
+
for (const part of parts) {
|
|
166
|
+
if (!part || cur === null || typeof cur !== 'object' || Array.isArray(cur)) {
|
|
167
|
+
return { found: false, value: undefined };
|
|
168
|
+
}
|
|
169
|
+
const record = cur;
|
|
170
|
+
if (!(part in record))
|
|
171
|
+
return { found: false, value: undefined };
|
|
172
|
+
cur = record[part];
|
|
173
|
+
}
|
|
174
|
+
return { found: true, value: cur };
|
|
175
|
+
}
|
|
176
|
+
function extractCommandText(args) {
|
|
177
|
+
for (const key of ['command', 'cmd', 'script']) {
|
|
178
|
+
const v = args[key];
|
|
179
|
+
if (typeof v === 'string' && v.trim().length > 0)
|
|
180
|
+
return v;
|
|
181
|
+
}
|
|
182
|
+
for (const [k, v] of Object.entries(args)) {
|
|
183
|
+
const lk = k.toLowerCase();
|
|
184
|
+
if ((lk === 'command' || lk === 'cmd' || lk === 'script') && typeof v === 'string' && v.trim().length > 0) {
|
|
185
|
+
return v;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
function anyGlobMatches(patterns, candidates) {
|
|
191
|
+
for (const cand of candidates) {
|
|
192
|
+
for (const pat of patterns) {
|
|
193
|
+
if (toolMatches(pat, cand))
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
/** Evaluate structured shell command matching using `analyzeCommand()`. */
|
|
200
|
+
export function commandMatches(cmdMatch, args) {
|
|
201
|
+
const cmdText = extractCommandText(args);
|
|
202
|
+
if (!cmdText)
|
|
203
|
+
return false;
|
|
204
|
+
const analysis = analyzeCommand(cmdText);
|
|
205
|
+
if (cmdMatch.tools && cmdMatch.tools.length > 0) {
|
|
206
|
+
const names = analysis.tools.map((t) => t.name);
|
|
207
|
+
if (!anyGlobMatches(cmdMatch.tools, names))
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
if (cmdMatch.subcommands && cmdMatch.subcommands.length > 0) {
|
|
211
|
+
const subs = analysis.tools.map((t) => t.subcommand).filter((s) => typeof s === 'string');
|
|
212
|
+
if (!anyGlobMatches(cmdMatch.subcommands, subs))
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
if (cmdMatch.intents && cmdMatch.intents.length > 0) {
|
|
216
|
+
if (!cmdMatch.intents.some((intent) => analysis.intents.includes(intent)))
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
const allPaths = [...analysis.paths.map((p) => p.path), ...analysis.files.map((f) => f.path)];
|
|
220
|
+
if (cmdMatch.paths && cmdMatch.paths.length > 0) {
|
|
221
|
+
if (!anyGlobMatches(cmdMatch.paths, allPaths))
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
if (cmdMatch.excludePaths && cmdMatch.excludePaths.length > 0) {
|
|
225
|
+
if (anyGlobMatches(cmdMatch.excludePaths, allPaths))
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
if (cmdMatch.urls && cmdMatch.urls.length > 0) {
|
|
229
|
+
const urlTargets = [...analysis.urls, ...analysis.urlHosts];
|
|
230
|
+
if (!anyGlobMatches(cmdMatch.urls, urlTargets))
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
if (cmdMatch.flags && cmdMatch.flags.length > 0) {
|
|
234
|
+
if (!anyGlobMatches(cmdMatch.flags, analysis.flags))
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
if (cmdMatch.excludeFlags && cmdMatch.excludeFlags.length > 0) {
|
|
238
|
+
if (anyGlobMatches(cmdMatch.excludeFlags, analysis.flags))
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
if (cmdMatch.sensitive !== undefined) {
|
|
242
|
+
if (analysis.hasSensitiveTarget !== cmdMatch.sensitive)
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
122
245
|
return true;
|
|
123
246
|
}
|
|
124
247
|
/**
|
|
125
|
-
* A rule matches when its tool glob matches
|
|
126
|
-
*
|
|
248
|
+
* A rule matches when its tool glob matches, optional agentIds/environments
|
|
249
|
+
* scopes match, every argument predicate holds, and optional structured
|
|
250
|
+
* command matching holds. A predicate referencing an absent argument fails
|
|
251
|
+
* the rule.
|
|
127
252
|
*/
|
|
128
253
|
export function ruleMatches(match, input) {
|
|
129
254
|
if (!toolMatches(match.tool, input.tool))
|
|
130
255
|
return false;
|
|
256
|
+
if (match.agentIds && match.agentIds.length > 0) {
|
|
257
|
+
if (!input.agentId || !anyGlobMatches(match.agentIds, [input.agentId]))
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
if (match.environments && match.environments.length > 0) {
|
|
261
|
+
if (!input.environment)
|
|
262
|
+
return false;
|
|
263
|
+
const envLower = input.environment.toLowerCase();
|
|
264
|
+
const matchedEnv = match.environments.some((e) => toolMatches(e.toLowerCase(), envLower));
|
|
265
|
+
if (!matchedEnv)
|
|
266
|
+
return false;
|
|
267
|
+
}
|
|
268
|
+
const args = input.args ?? {};
|
|
131
269
|
if (match.args) {
|
|
132
|
-
const args = input.args ?? {};
|
|
133
270
|
for (const [name, predicate] of Object.entries(match.args)) {
|
|
134
|
-
|
|
271
|
+
const resolved = resolveArgPath(args, name);
|
|
272
|
+
if (!resolved.found)
|
|
135
273
|
return false;
|
|
136
|
-
if (!argMatches(predicate,
|
|
274
|
+
if (!argMatches(predicate, resolved.value))
|
|
137
275
|
return false;
|
|
138
276
|
}
|
|
139
277
|
}
|
|
278
|
+
if (match.command) {
|
|
279
|
+
if (!commandMatches(match.command, args))
|
|
280
|
+
return false;
|
|
281
|
+
}
|
|
140
282
|
return true;
|
|
141
283
|
}
|
package/dist/policy/types.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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.
|
|
3
|
+
"version": "0.2.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",
|