@aithorized/core 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,12 +24,23 @@ export declare function resolveArgPath(args: Record<string, unknown>, key: strin
24
24
  found: boolean;
25
25
  value: unknown;
26
26
  };
27
+ export interface MatchOptions {
28
+ /**
29
+ * Strict allowlist semantics (used for ALLOW and AutoRule evaluation, PG-01):
30
+ * - Opaque/evasive commands (eval, unexpanded vars, pipe-to-shell, max depth, unclosed quotes) NEVER match.
31
+ * - Every detected tool, path, URL, and intent in a chained command must satisfy the rule's allowlist (`ALL`),
32
+ * preventing command-chaining bypasses like `ls /workspace && curl evil.com`.
33
+ */
34
+ strictAllow?: boolean;
35
+ }
27
36
  /** Evaluate structured shell command matching using `analyzeCommand()`. */
28
- export declare function commandMatches(cmdMatch: CommandMatch, args: Record<string, unknown>): boolean;
37
+ export declare function commandMatches(cmdMatch: CommandMatch, args: Record<string, unknown>, options?: MatchOptions): boolean;
29
38
  /**
30
39
  * A rule matches when its tool glob matches, optional agentIds/environments
31
40
  * scopes match, every argument predicate holds, and optional structured
32
41
  * command matching holds. A predicate referencing an absent argument fails
33
42
  * the rule.
34
43
  */
35
- export declare function ruleMatches(match: RuleMatch, input: EvalInput): boolean;
44
+ export declare function ruleMatches(match: RuleMatch, input: EvalInput, options?: MatchOptions): boolean;
45
+ /** True when `args` contains a shell command that `analyzeCommand()` flags as opaque/evasive. */
46
+ export declare function isOpaqueCommandInput(args: Record<string, unknown> | undefined): boolean;
@@ -5,8 +5,17 @@ import { analyzeCommand } from './command-analyzer.js';
5
5
  * Deterministic matching (docs/02 section 3.4, FR-3.1).
6
6
  * Pure functions, no side effects, no randomness.
7
7
  */
8
+ const MAX_CACHE_ENTRIES = 2048;
8
9
  const globCache = new Map();
9
10
  const regexCache = new Map();
11
+ function cacheSet(cache, key, value) {
12
+ if (cache.size >= MAX_CACHE_ENTRIES) {
13
+ const oldest = cache.keys().next().value;
14
+ if (oldest !== undefined)
15
+ cache.delete(oldest);
16
+ }
17
+ cache.set(key, value);
18
+ }
10
19
  function escapeRegExp(ch) {
11
20
  return /[.*+?^${}()|[\]\\]/.test(ch) ? '\\' + ch : ch;
12
21
  }
@@ -40,7 +49,7 @@ export function compilePolicyRegex(pattern) {
40
49
  }
41
50
  }
42
51
  const re = new RegExp(body, flags);
43
- regexCache.set(pattern, re);
52
+ cacheSet(regexCache, pattern, re);
44
53
  return re;
45
54
  }
46
55
  /**
@@ -60,7 +69,7 @@ export function toolMatches(pattern, tool) {
60
69
  body += escapeRegExp(ch);
61
70
  }
62
71
  re = new RegExp(`^${body}$`);
63
- globCache.set(pattern, re);
72
+ cacheSet(globCache, pattern, re);
64
73
  }
65
74
  return re.test(tool);
66
75
  }
@@ -196,29 +205,44 @@ function anyGlobMatches(patterns, candidates) {
196
205
  }
197
206
  return false;
198
207
  }
208
+ function allGlobsMatch(patterns, candidates) {
209
+ if (candidates.length === 0)
210
+ return false;
211
+ return candidates.every((cand) => patterns.some((pat) => toolMatches(pat, cand)));
212
+ }
199
213
  /** Evaluate structured shell command matching using `analyzeCommand()`. */
200
- export function commandMatches(cmdMatch, args) {
214
+ export function commandMatches(cmdMatch, args, options = {}) {
201
215
  const cmdText = extractCommandText(args);
202
216
  if (!cmdText)
203
217
  return false;
204
218
  const analysis = analyzeCommand(cmdText);
219
+ const strict = options.strictAllow === true;
220
+ // An opaque/evasive command can never satisfy an ALLOW or AutoRule (fail-closed, PG-03).
221
+ if (strict && analysis.opaque)
222
+ return false;
223
+ const listMatch = strict ? allGlobsMatch : anyGlobMatches;
205
224
  if (cmdMatch.tools && cmdMatch.tools.length > 0) {
206
225
  const names = analysis.tools.map((t) => t.name);
207
- if (!anyGlobMatches(cmdMatch.tools, names))
226
+ if (!listMatch(cmdMatch.tools, names))
208
227
  return false;
209
228
  }
210
229
  if (cmdMatch.subcommands && cmdMatch.subcommands.length > 0) {
211
230
  const subs = analysis.tools.map((t) => t.subcommand).filter((s) => typeof s === 'string');
212
- if (!anyGlobMatches(cmdMatch.subcommands, subs))
231
+ if (!listMatch(cmdMatch.subcommands, subs))
213
232
  return false;
214
233
  }
215
234
  if (cmdMatch.intents && cmdMatch.intents.length > 0) {
216
- if (!cmdMatch.intents.some((intent) => analysis.intents.includes(intent)))
235
+ if (strict) {
236
+ if (analysis.intents.length === 0 || !analysis.intents.every((intent) => cmdMatch.intents.includes(intent)))
237
+ return false;
238
+ }
239
+ else if (!cmdMatch.intents.some((intent) => analysis.intents.includes(intent))) {
217
240
  return false;
241
+ }
218
242
  }
219
243
  const allPaths = [...analysis.paths.map((p) => p.path), ...analysis.files.map((f) => f.path)];
220
244
  if (cmdMatch.paths && cmdMatch.paths.length > 0) {
221
- if (!anyGlobMatches(cmdMatch.paths, allPaths))
245
+ if (!listMatch(cmdMatch.paths, allPaths))
222
246
  return false;
223
247
  }
224
248
  if (cmdMatch.excludePaths && cmdMatch.excludePaths.length > 0) {
@@ -227,7 +251,7 @@ export function commandMatches(cmdMatch, args) {
227
251
  }
228
252
  if (cmdMatch.urls && cmdMatch.urls.length > 0) {
229
253
  const urlTargets = [...analysis.urls, ...analysis.urlHosts];
230
- if (!anyGlobMatches(cmdMatch.urls, urlTargets))
254
+ if (!listMatch(cmdMatch.urls, urlTargets))
231
255
  return false;
232
256
  }
233
257
  if (cmdMatch.flags && cmdMatch.flags.length > 0) {
@@ -250,7 +274,7 @@ export function commandMatches(cmdMatch, args) {
250
274
  * command matching holds. A predicate referencing an absent argument fails
251
275
  * the rule.
252
276
  */
253
- export function ruleMatches(match, input) {
277
+ export function ruleMatches(match, input, options = {}) {
254
278
  if (!toolMatches(match.tool, input.tool))
255
279
  return false;
256
280
  if (match.agentIds && match.agentIds.length > 0) {
@@ -276,8 +300,22 @@ export function ruleMatches(match, input) {
276
300
  }
277
301
  }
278
302
  if (match.command) {
279
- if (!commandMatches(match.command, args))
303
+ if (!commandMatches(match.command, args, options))
304
+ return false;
305
+ }
306
+ if (match.sessionTaints && match.sessionTaints.length > 0) {
307
+ const active = input.activeTaints ?? [];
308
+ if (!match.sessionTaints.some((t) => active.includes(t)))
280
309
  return false;
281
310
  }
282
311
  return true;
283
312
  }
313
+ /** True when `args` contains a shell command that `analyzeCommand()` flags as opaque/evasive. */
314
+ export function isOpaqueCommandInput(args) {
315
+ if (!args)
316
+ return false;
317
+ const cmdText = extractCommandText(args);
318
+ if (!cmdText)
319
+ return false;
320
+ return analyzeCommand(cmdText).opaque;
321
+ }
@@ -0,0 +1,23 @@
1
+ import type { PolicyDocument, PolicyRule } from './types.js';
2
+ export type PolicyPackId = 'coding-agent' | 'devops' | 'fintech' | 'database';
3
+ export interface PolicyPack {
4
+ id: PolicyPackId;
5
+ name: string;
6
+ description: string;
7
+ tags: string[];
8
+ rules: PolicyRule[];
9
+ }
10
+ export declare const POLICY_PACKS: readonly PolicyPack[];
11
+ export declare function getPolicyPack(id: string): PolicyPack | undefined;
12
+ /**
13
+ * Merge a curated PolicyPack into an existing PolicyDocument without
14
+ * duplicating rule IDs. In `observe` mode, enforcement rules are
15
+ * downgraded to `OBSERVE` for risk-free Shadow Mode onboarding.
16
+ */
17
+ export declare function applyPolicyPack(policy: PolicyDocument, packId: PolicyPackId, options?: {
18
+ mode?: 'observe' | 'enforce';
19
+ }): {
20
+ policy: PolicyDocument;
21
+ addedRuleIds: string[];
22
+ skippedRuleIds: string[];
23
+ };
@@ -0,0 +1,230 @@
1
+ export const POLICY_PACKS = [
2
+ {
3
+ id: 'coding-agent',
4
+ name: 'Coding Agent Guardrails',
5
+ description: 'Protects against destructive shell deletes, force pushes, remote script piping, and secret file access.',
6
+ tags: ['shell', 'git', 'secrets'],
7
+ rules: [
8
+ {
9
+ id: 'pack-coding-deny-remote-pipe',
10
+ name: 'Block remote script pipe to shell',
11
+ description: 'Denies downloading and piping remote scripts directly into a shell interpreter.',
12
+ tags: ['coding-agent', 'security'],
13
+ match: {
14
+ tool: '*bash*',
15
+ command: { tools: ['curl', 'wget'], intents: ['network', 'exec'] }
16
+ },
17
+ effect: 'DENY'
18
+ },
19
+ {
20
+ id: 'pack-coding-critical-sensitive-paths',
21
+ name: 'Gate access to sensitive credential paths',
22
+ description: 'Requires human approval whenever a shell command touches .env, SSH keys, or credential files.',
23
+ tags: ['coding-agent', 'secrets'],
24
+ match: {
25
+ tool: '*bash*',
26
+ command: { sensitive: true }
27
+ },
28
+ effect: 'REQUIRE_APPROVAL',
29
+ riskLevel: 'CRITICAL',
30
+ ttlSeconds: 300
31
+ },
32
+ {
33
+ id: 'pack-coding-high-git-force',
34
+ name: 'Gate destructive git push',
35
+ description: 'Requires approval for git push with --force or -f.',
36
+ tags: ['coding-agent', 'git'],
37
+ match: {
38
+ tool: '*bash*',
39
+ command: { tools: ['git'], subcommands: ['push'], flags: ['--force', '-f', '--force-with-lease'] }
40
+ },
41
+ effect: 'REQUIRE_APPROVAL',
42
+ riskLevel: 'HIGH',
43
+ ttlSeconds: 300
44
+ },
45
+ {
46
+ id: 'pack-coding-high-fs-delete',
47
+ name: 'Gate recursive shell deletions',
48
+ description: 'Requires approval for destructive delete commands such as rm -rf.',
49
+ tags: ['coding-agent', 'filesystem'],
50
+ match: {
51
+ tool: '*bash*',
52
+ command: { intents: ['delete'], flags: ['-rf', '-fr', '--recursive', '-r'] }
53
+ },
54
+ effect: 'REQUIRE_APPROVAL',
55
+ riskLevel: 'HIGH',
56
+ ttlSeconds: 300
57
+ }
58
+ ]
59
+ },
60
+ {
61
+ id: 'devops',
62
+ name: 'DevOps & Cloud Infra',
63
+ description: 'Gates production Terraform/Kubernetes changes, cluster deletions, and IAM/cloud mutations.',
64
+ tags: ['terraform', 'kubernetes', 'aws', 'prod'],
65
+ rules: [
66
+ {
67
+ id: 'pack-devops-critical-tf-destroy',
68
+ name: 'Gate Terraform destroy',
69
+ description: 'Requires approval before running terraform destroy.',
70
+ tags: ['devops', 'terraform'],
71
+ match: {
72
+ tool: '*bash*',
73
+ command: { tools: ['terraform', 'tofu'], subcommands: ['destroy'] }
74
+ },
75
+ effect: 'REQUIRE_APPROVAL',
76
+ riskLevel: 'CRITICAL',
77
+ ttlSeconds: 600
78
+ },
79
+ {
80
+ id: 'pack-devops-high-k8s-delete',
81
+ name: 'Gate kubectl delete',
82
+ description: 'Requires approval for kubectl delete operations.',
83
+ tags: ['devops', 'kubernetes'],
84
+ match: {
85
+ tool: '*bash*',
86
+ command: { tools: ['kubectl'], subcommands: ['delete'] }
87
+ },
88
+ effect: 'REQUIRE_APPROVAL',
89
+ riskLevel: 'HIGH',
90
+ ttlSeconds: 300
91
+ },
92
+ {
93
+ id: 'pack-devops-critical-prod-deploy',
94
+ name: 'Gate production deployments',
95
+ description: 'Requires approval for deploy tools targeting prod.',
96
+ tags: ['devops', 'prod'],
97
+ match: {
98
+ tool: 'deploy.*',
99
+ environments: ['prod', 'production']
100
+ },
101
+ effect: 'REQUIRE_APPROVAL',
102
+ riskLevel: 'CRITICAL',
103
+ ttlSeconds: 600
104
+ }
105
+ ]
106
+ },
107
+ {
108
+ id: 'fintech',
109
+ name: 'Fintech & Payments',
110
+ description: 'Protects Stripe/payment refunds, payouts, and webhook configuration changes.',
111
+ tags: ['stripe', 'payments', 'refunds'],
112
+ rules: [
113
+ {
114
+ id: 'pack-fintech-high-refund',
115
+ name: 'Gate refunds over 50',
116
+ description: 'Requires approval for refunds with amount greater than 50.',
117
+ tags: ['fintech', 'stripe'],
118
+ match: {
119
+ tool: 'stripe.refund*',
120
+ args: { amount: { gt: 50 } }
121
+ },
122
+ effect: 'REQUIRE_APPROVAL',
123
+ riskLevel: 'HIGH',
124
+ ttlSeconds: 300
125
+ },
126
+ {
127
+ id: 'pack-fintech-critical-payout',
128
+ name: 'Gate payouts and transfers',
129
+ description: 'Requires approval for all payout or transfer tool calls.',
130
+ tags: ['fintech', 'payouts'],
131
+ match: {
132
+ tool: '*.payout*'
133
+ },
134
+ effect: 'REQUIRE_APPROVAL',
135
+ riskLevel: 'CRITICAL',
136
+ ttlSeconds: 600
137
+ },
138
+ {
139
+ id: 'pack-fintech-medium-webhook',
140
+ name: 'Gate payment webhook mutations',
141
+ description: 'Requires approval when modifying payment webhook endpoints.',
142
+ tags: ['fintech', 'webhooks'],
143
+ match: {
144
+ tool: 'stripe.webhook*'
145
+ },
146
+ effect: 'REQUIRE_APPROVAL',
147
+ riskLevel: 'MEDIUM',
148
+ ttlSeconds: 300
149
+ }
150
+ ]
151
+ },
152
+ {
153
+ id: 'database',
154
+ name: 'Database Safety',
155
+ description: 'Prevents accidental DROP/TRUNCATE and gates production SQL writes.',
156
+ tags: ['sql', 'postgres', 'mysql'],
157
+ rules: [
158
+ {
159
+ id: 'pack-db-deny-drop-truncate',
160
+ name: 'Block DROP and TRUNCATE SQL statements',
161
+ description: 'Blocks DROP TABLE/DATABASE and TRUNCATE statements in SQL tools.',
162
+ tags: ['database', 'sql'],
163
+ match: {
164
+ tool: 'sql.*',
165
+ args: { query: { regex: '(?i)\\b(DROP|TRUNCATE)\\b' } }
166
+ },
167
+ effect: 'DENY'
168
+ },
169
+ {
170
+ id: 'pack-db-critical-prod-write',
171
+ name: 'Gate production SQL writes',
172
+ description: 'Requires approval for SQL write/execute calls in production.',
173
+ tags: ['database', 'prod'],
174
+ match: {
175
+ tool: 'sql.*',
176
+ environments: ['prod', 'production']
177
+ },
178
+ effect: 'REQUIRE_APPROVAL',
179
+ riskLevel: 'CRITICAL',
180
+ ttlSeconds: 300
181
+ }
182
+ ]
183
+ }
184
+ ];
185
+ export function getPolicyPack(id) {
186
+ return POLICY_PACKS.find((p) => p.id === id);
187
+ }
188
+ /**
189
+ * Merge a curated PolicyPack into an existing PolicyDocument without
190
+ * duplicating rule IDs. In `observe` mode, enforcement rules are
191
+ * downgraded to `OBSERVE` for risk-free Shadow Mode onboarding.
192
+ */
193
+ export function applyPolicyPack(policy, packId, options = {}) {
194
+ const pack = getPolicyPack(packId);
195
+ if (!pack) {
196
+ throw new Error(`Unknown policy pack: ${packId}`);
197
+ }
198
+ const mode = options.mode ?? 'enforce';
199
+ const existingIds = new Set(policy.rules.map((r) => r.id));
200
+ const addedRuleIds = [];
201
+ const skippedRuleIds = [];
202
+ const newRules = [...policy.rules];
203
+ for (const rule of pack.rules) {
204
+ if (existingIds.has(rule.id)) {
205
+ skippedRuleIds.push(rule.id);
206
+ continue;
207
+ }
208
+ const materialized = mode === 'observe'
209
+ ? {
210
+ id: rule.id,
211
+ ...(rule.name ? { name: rule.name } : {}),
212
+ ...(rule.description ? { description: rule.description } : {}),
213
+ ...(rule.tags ? { tags: rule.tags } : {}),
214
+ match: rule.match,
215
+ effect: 'OBSERVE'
216
+ }
217
+ : { ...rule };
218
+ newRules.push(materialized);
219
+ existingIds.add(rule.id);
220
+ addedRuleIds.push(rule.id);
221
+ }
222
+ return {
223
+ policy: {
224
+ ...policy,
225
+ rules: newRules
226
+ },
227
+ addedRuleIds,
228
+ skippedRuleIds
229
+ };
230
+ }
@@ -56,6 +56,8 @@ export interface RuleMatch {
56
56
  args?: Record<string, ArgPredicate>;
57
57
  /** Structured shell command matching using analyzeCommand(). */
58
58
  command?: CommandMatch;
59
+ /** Match only when any of these session taints are active. */
60
+ sessionTaints?: string[];
59
61
  }
60
62
  export interface PolicyRule {
61
63
  id: string;
@@ -73,6 +75,14 @@ export interface PolicyRule {
73
75
  approversRequired?: number;
74
76
  /** Default from defaults.ttlSeconds, clamped to [30, 3600]. */
75
77
  ttlSeconds?: number;
78
+ /** Session taints attached when this rule matches (e.g. ["touched_secrets"]). */
79
+ addTaints?: string[];
80
+ /** Optional routing group (e.g. "dba", "devops", "leads"). */
81
+ routingGroup?: string;
82
+ /** Optional TTL percentage [10..90] after which escalation triggers. */
83
+ escalationAtPercent?: number;
84
+ /** Allow desktop WebAuthn/Passkey approval for LOW/MEDIUM rules. */
85
+ allowDesktopPasskey?: boolean;
76
86
  }
77
87
  export interface PolicyDefaults {
78
88
  /** What unmatched calls do: ALLOW, OBSERVE (shadow) or REQUIRE_APPROVAL (strict). */
@@ -103,6 +113,12 @@ export interface AutoRule {
103
113
  maxUses?: number;
104
114
  /** Uses consumed so far (supplied by the caller; 0 by default). */
105
115
  uses?: number;
116
+ /** Cumulative numeric budget over a payload argument (e.g. refund amount). */
117
+ budget?: {
118
+ field: string;
119
+ maxTotal: number;
120
+ consumed?: number;
121
+ };
106
122
  }
107
123
  export type PauseMode = 'PASSTHROUGH' | 'AUTO_APPROVE' | 'AUTO_DENY';
108
124
  /**
@@ -154,6 +170,8 @@ export interface EvalInput {
154
170
  environment?: string;
155
171
  /** Current time in ms epoch. */
156
172
  nowMs: number;
173
+ /** Active session taints for sequential rules. */
174
+ activeTaints?: string[];
157
175
  }
158
176
  export interface EvalFlags {
159
177
  /** Tenant (or scope) Kill Switch is active. */
@@ -172,4 +190,8 @@ export interface EvalResult {
172
190
  ttlSeconds?: number;
173
191
  /** True when a degraded (stale/missing/invalid) policy was in force. */
174
192
  degraded?: boolean;
193
+ /** Taints added by the matched rule. */
194
+ addedTaints?: string[];
195
+ /** Routing group from the matched rule. */
196
+ routingGroup?: string;
175
197
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aithorized/core",
3
- "version": "0.2.0",
3
+ "version": "0.4.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",