agent-threat-rules 1.0.0 → 1.1.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/README.md +9 -8
- package/dist/action-executor.d.ts +44 -0
- package/dist/action-executor.d.ts.map +1 -0
- package/dist/action-executor.js +130 -0
- package/dist/action-executor.js.map +1 -0
- package/dist/adapters/default-adapter.d.ts +24 -0
- package/dist/adapters/default-adapter.d.ts.map +1 -0
- package/dist/adapters/default-adapter.js +51 -0
- package/dist/adapters/default-adapter.js.map +1 -0
- package/dist/adapters/stdio-adapter.d.ts +30 -0
- package/dist/adapters/stdio-adapter.d.ts.map +1 -0
- package/dist/adapters/stdio-adapter.js +128 -0
- package/dist/adapters/stdio-adapter.js.map +1 -0
- package/dist/badge.d.ts +42 -0
- package/dist/badge.d.ts.map +1 -0
- package/dist/badge.js +163 -0
- package/dist/badge.js.map +1 -0
- package/dist/capability-extractor.d.ts +35 -0
- package/dist/capability-extractor.d.ts.map +1 -0
- package/dist/capability-extractor.js +91 -0
- package/dist/capability-extractor.js.map +1 -0
- package/dist/cli/scan-handler.d.ts +21 -0
- package/dist/cli/scan-handler.d.ts.map +1 -0
- package/dist/cli/scan-handler.js +276 -0
- package/dist/cli/scan-handler.js.map +1 -0
- package/dist/cli/tc-pipeline.d.ts +18 -0
- package/dist/cli/tc-pipeline.d.ts.map +1 -0
- package/dist/cli/tc-pipeline.js +295 -0
- package/dist/cli/tc-pipeline.js.map +1 -0
- package/dist/cli.d.ts +12 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +884 -0
- package/dist/cli.js.map +1 -0
- package/dist/content-hash.d.ts +7 -0
- package/dist/content-hash.d.ts.map +1 -0
- package/dist/content-hash.js +10 -0
- package/dist/content-hash.js.map +1 -0
- package/dist/converters/elastic.d.ts +36 -0
- package/dist/converters/elastic.d.ts.map +1 -0
- package/dist/converters/elastic.js +125 -0
- package/dist/converters/elastic.js.map +1 -0
- package/dist/converters/generic-regex.d.ts +37 -0
- package/dist/converters/generic-regex.d.ts.map +1 -0
- package/dist/converters/generic-regex.js +59 -0
- package/dist/converters/generic-regex.js.map +1 -0
- package/dist/converters/index.d.ts +32 -0
- package/dist/converters/index.d.ts.map +1 -0
- package/dist/converters/index.js +38 -0
- package/dist/converters/index.js.map +1 -0
- package/dist/converters/sarif.d.ts +18 -0
- package/dist/converters/sarif.d.ts.map +1 -0
- package/dist/converters/sarif.js +142 -0
- package/dist/converters/sarif.js.map +1 -0
- package/dist/converters/splunk.d.ts +19 -0
- package/dist/converters/splunk.d.ts.map +1 -0
- package/dist/converters/splunk.js +148 -0
- package/dist/converters/splunk.js.map +1 -0
- package/dist/coverage-analyzer.d.ts +43 -0
- package/dist/coverage-analyzer.d.ts.map +1 -0
- package/dist/coverage-analyzer.js +329 -0
- package/dist/coverage-analyzer.js.map +1 -0
- package/dist/embedding/build-corpus.d.ts +15 -0
- package/dist/embedding/build-corpus.d.ts.map +1 -0
- package/dist/embedding/build-corpus.js +105 -0
- package/dist/embedding/build-corpus.js.map +1 -0
- package/dist/embedding/model-loader.d.ts +41 -0
- package/dist/embedding/model-loader.d.ts.map +1 -0
- package/dist/embedding/model-loader.js +90 -0
- package/dist/embedding/model-loader.js.map +1 -0
- package/dist/embedding/vector-store.d.ts +41 -0
- package/dist/embedding/vector-store.d.ts.map +1 -0
- package/dist/embedding/vector-store.js +70 -0
- package/dist/embedding/vector-store.js.map +1 -0
- package/dist/engine.d.ts +217 -0
- package/dist/engine.d.ts.map +1 -0
- package/dist/engine.js +1117 -0
- package/dist/engine.js.map +1 -0
- package/dist/eval/corpus.d.ts +42 -0
- package/dist/eval/corpus.d.ts.map +1 -0
- package/dist/eval/corpus.js +427 -0
- package/dist/eval/corpus.js.map +1 -0
- package/dist/eval/eval-harness.d.ts +44 -0
- package/dist/eval/eval-harness.d.ts.map +1 -0
- package/dist/eval/eval-harness.js +296 -0
- package/dist/eval/eval-harness.js.map +1 -0
- package/dist/eval/index.d.ts +13 -0
- package/dist/eval/index.d.ts.map +1 -0
- package/dist/eval/index.js +9 -0
- package/dist/eval/index.js.map +1 -0
- package/dist/eval/metrics.d.ts +74 -0
- package/dist/eval/metrics.d.ts.map +1 -0
- package/dist/eval/metrics.js +108 -0
- package/dist/eval/metrics.js.map +1 -0
- package/dist/eval/pint-corpus.d.ts +34 -0
- package/dist/eval/pint-corpus.d.ts.map +1 -0
- package/dist/eval/pint-corpus.js +113 -0
- package/dist/eval/pint-corpus.js.map +1 -0
- package/dist/eval/rule-corpus.d.ts +9 -0
- package/dist/eval/rule-corpus.d.ts.map +1 -0
- package/dist/eval/rule-corpus.js +4780 -0
- package/dist/eval/rule-corpus.js.map +1 -0
- package/dist/eval/rule-metrics.d.ts +34 -0
- package/dist/eval/rule-metrics.d.ts.map +1 -0
- package/dist/eval/rule-metrics.js +92 -0
- package/dist/eval/rule-metrics.js.map +1 -0
- package/dist/eval/run-eval.d.ts +7 -0
- package/dist/eval/run-eval.d.ts.map +1 -0
- package/dist/eval/run-eval.js +11 -0
- package/dist/eval/run-eval.js.map +1 -0
- package/dist/eval/run-pint-benchmark.d.ts +18 -0
- package/dist/eval/run-pint-benchmark.d.ts.map +1 -0
- package/dist/eval/run-pint-benchmark.js +159 -0
- package/dist/eval/run-pint-benchmark.js.map +1 -0
- package/dist/eval/skill-benchmark.d.ts +66 -0
- package/dist/eval/skill-benchmark.d.ts.map +1 -0
- package/dist/eval/skill-benchmark.js +194 -0
- package/dist/eval/skill-benchmark.js.map +1 -0
- package/dist/flywheel.d.ts +54 -0
- package/dist/flywheel.d.ts.map +1 -0
- package/dist/flywheel.js +121 -0
- package/dist/flywheel.js.map +1 -0
- package/dist/hook-handler.d.ts +61 -0
- package/dist/hook-handler.d.ts.map +1 -0
- package/dist/hook-handler.js +178 -0
- package/dist/hook-handler.js.map +1 -0
- package/dist/index.d.ts +66 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +57 -0
- package/dist/index.js.map +1 -0
- package/dist/layer-integration.d.ts +55 -0
- package/dist/layer-integration.d.ts.map +1 -0
- package/dist/layer-integration.js +187 -0
- package/dist/layer-integration.js.map +1 -0
- package/dist/loader.d.ts +18 -0
- package/dist/loader.d.ts.map +1 -0
- package/dist/loader.js +129 -0
- package/dist/loader.js.map +1 -0
- package/dist/mcp-server.d.ts +13 -0
- package/dist/mcp-server.d.ts.map +1 -0
- package/dist/mcp-server.js +246 -0
- package/dist/mcp-server.js.map +1 -0
- package/dist/mcp-tools/coverage-gaps.d.ts +13 -0
- package/dist/mcp-tools/coverage-gaps.d.ts.map +1 -0
- package/dist/mcp-tools/coverage-gaps.js +55 -0
- package/dist/mcp-tools/coverage-gaps.js.map +1 -0
- package/dist/mcp-tools/list-rules.d.ts +17 -0
- package/dist/mcp-tools/list-rules.d.ts.map +1 -0
- package/dist/mcp-tools/list-rules.js +45 -0
- package/dist/mcp-tools/list-rules.js.map +1 -0
- package/dist/mcp-tools/scan-skill.d.ts +17 -0
- package/dist/mcp-tools/scan-skill.d.ts.map +1 -0
- package/dist/mcp-tools/scan-skill.js +65 -0
- package/dist/mcp-tools/scan-skill.js.map +1 -0
- package/dist/mcp-tools/scan.d.ts +24 -0
- package/dist/mcp-tools/scan.d.ts.map +1 -0
- package/dist/mcp-tools/scan.js +94 -0
- package/dist/mcp-tools/scan.js.map +1 -0
- package/dist/mcp-tools/submit-proposal.d.ts +12 -0
- package/dist/mcp-tools/submit-proposal.d.ts.map +1 -0
- package/dist/mcp-tools/submit-proposal.js +103 -0
- package/dist/mcp-tools/submit-proposal.js.map +1 -0
- package/dist/mcp-tools/threat-summary.d.ts +12 -0
- package/dist/mcp-tools/threat-summary.d.ts.map +1 -0
- package/dist/mcp-tools/threat-summary.js +74 -0
- package/dist/mcp-tools/threat-summary.js.map +1 -0
- package/dist/mcp-tools/validate.d.ts +15 -0
- package/dist/mcp-tools/validate.d.ts.map +1 -0
- package/dist/mcp-tools/validate.js +51 -0
- package/dist/mcp-tools/validate.js.map +1 -0
- package/dist/modules/embedding.d.ts +71 -0
- package/dist/modules/embedding.d.ts.map +1 -0
- package/dist/modules/embedding.js +141 -0
- package/dist/modules/embedding.js.map +1 -0
- package/dist/modules/index.d.ts +144 -0
- package/dist/modules/index.d.ts.map +1 -0
- package/dist/modules/index.js +82 -0
- package/dist/modules/index.js.map +1 -0
- package/dist/modules/semantic.d.ts +106 -0
- package/dist/modules/semantic.d.ts.map +1 -0
- package/dist/modules/semantic.js +359 -0
- package/dist/modules/semantic.js.map +1 -0
- package/dist/modules/session.d.ts +70 -0
- package/dist/modules/session.d.ts.map +1 -0
- package/dist/modules/session.js +128 -0
- package/dist/modules/session.js.map +1 -0
- package/dist/rule-scaffolder.d.ts +53 -0
- package/dist/rule-scaffolder.d.ts.map +1 -0
- package/dist/rule-scaffolder.js +301 -0
- package/dist/rule-scaffolder.js.map +1 -0
- package/dist/session-tracker.d.ts +58 -0
- package/dist/session-tracker.d.ts.map +1 -0
- package/dist/session-tracker.js +176 -0
- package/dist/session-tracker.js.map +1 -0
- package/dist/shadow-evaluator.d.ts +48 -0
- package/dist/shadow-evaluator.d.ts.map +1 -0
- package/dist/shadow-evaluator.js +129 -0
- package/dist/shadow-evaluator.js.map +1 -0
- package/dist/skill-fingerprint.d.ts +85 -0
- package/dist/skill-fingerprint.d.ts.map +1 -0
- package/dist/skill-fingerprint.js +284 -0
- package/dist/skill-fingerprint.js.map +1 -0
- package/dist/tc-reporter.d.ts +50 -0
- package/dist/tc-reporter.d.ts.map +1 -0
- package/dist/tc-reporter.js +164 -0
- package/dist/tc-reporter.js.map +1 -0
- package/dist/tier0-invariant.d.ts +49 -0
- package/dist/tier0-invariant.d.ts.map +1 -0
- package/dist/tier0-invariant.js +185 -0
- package/dist/tier0-invariant.js.map +1 -0
- package/dist/tier1-blacklist.d.ts +48 -0
- package/dist/tier1-blacklist.d.ts.map +1 -0
- package/dist/tier1-blacklist.js +92 -0
- package/dist/tier1-blacklist.js.map +1 -0
- package/dist/types.d.ts +212 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/verdict.d.ts +26 -0
- package/dist/verdict.d.ts.map +1 -0
- package/dist/verdict.js +127 -0
- package/dist/verdict.js.map +1 -0
- package/package.json +1 -1
- package/rules/context-exfiltration/ATR-2026-00150-credential-in-tool-response.yaml +90 -0
- package/rules/context-exfiltration/ATR-2026-00152-obfuscated-credential-leak.yaml +81 -0
- package/rules/prompt-injection/ATR-2026-00153-tool-with-embedded-instruction-to-bypass.yaml +43 -0
- package/rules/prompt-injection/ATR-2026-00154-unauthorized-background-task-execution-v.yaml +43 -0
- package/rules/prompt-injection/ATR-2026-00155-hidden-llm-instructions-in-skill-descrip.yaml +43 -0
- package/rules/prompt-injection/ATR-2026-00156-ssh-remote-command-execution-with-creden.yaml +43 -0
- package/rules/skill-compromise/ATR-2026-00149-skill-exfil-compound.yaml +189 -0
- package/rules/skill-compromise/ATR-2026-00151-fork-impersonation-install.yaml +75 -0
package/dist/engine.js
ADDED
|
@@ -0,0 +1,1117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ATR Engine - Evaluates agent events against ATR rules
|
|
3
|
+
*
|
|
4
|
+
* Core detection engine that:
|
|
5
|
+
* 1. Loads ATR YAML rules from disk
|
|
6
|
+
* 2. Evaluates agent events (LLM I/O, tool calls, behaviors) against rules
|
|
7
|
+
* 3. Returns matched rules with confidence scores
|
|
8
|
+
* 4. Supports two condition formats:
|
|
9
|
+
* - Array format: conditions is an array of {field, operator, value} objects
|
|
10
|
+
* - Named format: conditions is an object map of named condition blocks
|
|
11
|
+
*
|
|
12
|
+
* @module agent-threat-rules/engine
|
|
13
|
+
*/
|
|
14
|
+
import { computeContentHash } from './content-hash.js';
|
|
15
|
+
import { loadRulesFromDirectory, loadRuleFile } from './loader.js';
|
|
16
|
+
import { computeVerdict } from './verdict.js';
|
|
17
|
+
import { SemanticModule } from './modules/semantic.js';
|
|
18
|
+
import { resolveSkillId, runFingerprintLayer, shouldRunSemanticLayer, createSemanticModuleFromConfig, runSemanticLayer, } from './layer-integration.js';
|
|
19
|
+
import { buildBlacklistMatch, resolveSkillId as resolveBlacklistSkillId } from './tier1-blacklist.js';
|
|
20
|
+
/**
|
|
21
|
+
* Rules excluded from skill-context scanning due to high false-positive rate.
|
|
22
|
+
* Threshold: >0.5% FP on 466 real-world SKILL.md files (skills-sh corpus).
|
|
23
|
+
* Re-evaluate when adding new rules or updating detection patterns.
|
|
24
|
+
*/
|
|
25
|
+
const SKILL_CONTEXT_DENYLIST = new Set([
|
|
26
|
+
'ATR-2026-00111', // Shell Escape — 95.2% FP on benign skills (matches any shell/exec mention)
|
|
27
|
+
'ATR-2026-00118', // Approval Fatigue — 84.8% FP on benign skills (matches any approval/confirm pattern)
|
|
28
|
+
'ATR-2026-00032', // Goal Hijacking — 3.2% FP (skills naturally contain instructional language)
|
|
29
|
+
'ATR-2026-00115', // Env Var Harvesting — 1.7% FP (skills legitimately reference env vars)
|
|
30
|
+
'ATR-2026-00051', // Resource Exhaustion — 1.6% FP (matches loop/retry patterns in normal skills)
|
|
31
|
+
'ATR-2026-00113', // Credential Theft — 1.5% FP (security skills reference credential files)
|
|
32
|
+
'ATR-2026-00110', // eval() Injection — 1.3% FP (coding skills mention eval/exec patterns)
|
|
33
|
+
'ATR-2026-00112', // Dynamic Import — 0.9% FP (normal skills reference import/require)
|
|
34
|
+
'ATR-2026-00030', // Cross-Agent Attack — 0.8% FP (matches multi-agent communication patterns)
|
|
35
|
+
'ATR-2026-00002', // Indirect Prompt Injection — 0.8% FP (matches content-fetch patterns)
|
|
36
|
+
'ATR-2026-00142', // Piggyback Transition — 0.6% FP (descriptive text triggers false match)
|
|
37
|
+
'ATR-2026-00050', // Runaway Agent Loop — 0.4% FP (matches loop patterns in automation skills)
|
|
38
|
+
'ATR-2026-00117', // Agent Identity Spoofing — 0.4% FP (matches persona/identity patterns)
|
|
39
|
+
'ATR-2026-00116', // A2A Message Injection — 0.4% FP (matches agent communication patterns)
|
|
40
|
+
'ATR-2026-00114', // OAuth Token Interception — 2.57% FP on 53K skills (matches normal auth patterns)
|
|
41
|
+
'ATR-2026-00060', // MCP Skill Impersonation — 0.2% FP (matches normal skill metadata patterns)
|
|
42
|
+
'ATR-2026-00077', // Human-Agent Trust Exploitation — 0.2% FP (SRE/monitoring skills trigger)
|
|
43
|
+
'ATR-2026-00076', // Insecure Inter-Agent Communication — 0.2% FP (SDK skills mention agent comms)
|
|
44
|
+
'ATR-2026-00148', // Multilingual Prompt Injection — 0.2% FP (bilingual skills trigger)
|
|
45
|
+
'ATR-2026-00123', // Over-Privileged Skill — 0.2% FP (legitimate admin skills trigger)
|
|
46
|
+
'ATR-2026-00074', // Cross-Agent Privilege Escalation — 0.2% FP (automation skills trigger)
|
|
47
|
+
'ATR-2026-00098', // Unauthorized Financial Action — 0.2% FP (testing skills mention payments)
|
|
48
|
+
]);
|
|
49
|
+
/**
|
|
50
|
+
* Detect and decode base64-encoded blocks in content.
|
|
51
|
+
* Bounds: max 1 level decode, max 5 blocks, min 32 chars per block,
|
|
52
|
+
* MAX_EVAL_LENGTH per decoded block. Returns decoded text fragments.
|
|
53
|
+
*/
|
|
54
|
+
const BASE64_BLOCK_RE = /(?:[A-Za-z0-9+/]{32,}={0,2})/g;
|
|
55
|
+
const MAX_DECODE_BLOCKS = 5;
|
|
56
|
+
function decodeBase64Blocks(content) {
|
|
57
|
+
const decoded = [];
|
|
58
|
+
let match;
|
|
59
|
+
let count = 0;
|
|
60
|
+
while ((match = BASE64_BLOCK_RE.exec(content)) !== null && count < MAX_DECODE_BLOCKS) {
|
|
61
|
+
try {
|
|
62
|
+
const raw = Buffer.from(match[0], 'base64');
|
|
63
|
+
const text = raw.toString('utf-8');
|
|
64
|
+
// Only keep if decoded content looks like text (not binary garbage)
|
|
65
|
+
// Check: >80% printable ASCII or valid UTF-8 with common chars
|
|
66
|
+
const printable = text.split('').filter(c => c.charCodeAt(0) >= 32 && c.charCodeAt(0) < 127).length;
|
|
67
|
+
if (printable / text.length > 0.7 && text.length >= 10) {
|
|
68
|
+
decoded.push(text.slice(0, 100_000)); // MAX_EVAL_LENGTH bound
|
|
69
|
+
count++;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
// Invalid base64, skip
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return decoded;
|
|
77
|
+
}
|
|
78
|
+
/** Map agent event types to ATR source types */
|
|
79
|
+
const EVENT_TYPE_TO_SOURCE = {
|
|
80
|
+
llm_input: 'llm_io',
|
|
81
|
+
llm_output: 'llm_io',
|
|
82
|
+
tool_call: 'tool_call',
|
|
83
|
+
tool_response: 'mcp_exchange',
|
|
84
|
+
agent_behavior: 'agent_behavior',
|
|
85
|
+
multi_agent_message: 'multi_agent_comm',
|
|
86
|
+
};
|
|
87
|
+
/** Map agent event types to default field names */
|
|
88
|
+
const EVENT_TYPE_TO_FIELD = {
|
|
89
|
+
llm_input: 'user_input',
|
|
90
|
+
llm_output: 'agent_output',
|
|
91
|
+
tool_call: 'tool_name',
|
|
92
|
+
tool_response: 'tool_response',
|
|
93
|
+
agent_behavior: 'metric',
|
|
94
|
+
multi_agent_message: 'agent_message',
|
|
95
|
+
};
|
|
96
|
+
export class ATREngine {
|
|
97
|
+
config;
|
|
98
|
+
rules = [];
|
|
99
|
+
compiledPatterns = new Map();
|
|
100
|
+
semanticModuleInstance;
|
|
101
|
+
constructor(config = {}) {
|
|
102
|
+
this.config = config;
|
|
103
|
+
// Initialize Layer 3 semantic module if config provided
|
|
104
|
+
if (config.semanticModule) {
|
|
105
|
+
const moduleConfig = createSemanticModuleFromConfig(config.semanticModule);
|
|
106
|
+
this.semanticModuleInstance = new SemanticModule(moduleConfig);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
this.semanticModuleInstance = null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Load rules from configured directory and/or pre-loaded rules.
|
|
114
|
+
*/
|
|
115
|
+
async loadRules() {
|
|
116
|
+
this.rules = [];
|
|
117
|
+
this.compiledPatterns.clear();
|
|
118
|
+
if (this.config.rules) {
|
|
119
|
+
this.rules.push(...this.config.rules);
|
|
120
|
+
}
|
|
121
|
+
if (this.config.rulesDir) {
|
|
122
|
+
try {
|
|
123
|
+
const fileRules = loadRulesFromDirectory(this.config.rulesDir);
|
|
124
|
+
this.rules.push(...fileRules);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
// Directory may not exist yet
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// Pre-compile regex patterns for performance
|
|
131
|
+
for (const rule of this.rules) {
|
|
132
|
+
this.compilePatterns(rule);
|
|
133
|
+
}
|
|
134
|
+
return this.rules.length;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Load a single rule file and add it to the engine.
|
|
138
|
+
*/
|
|
139
|
+
addRuleFile(filePath) {
|
|
140
|
+
const rule = loadRuleFile(filePath);
|
|
141
|
+
this.rules.push(rule);
|
|
142
|
+
this.compilePatterns(rule);
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Add a pre-parsed rule to the engine.
|
|
146
|
+
*/
|
|
147
|
+
addRule(rule) {
|
|
148
|
+
this.rules.push(rule);
|
|
149
|
+
this.compilePatterns(rule);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Evaluate an agent event against all loaded ATR rules.
|
|
153
|
+
* Returns all matching rules with details.
|
|
154
|
+
*/
|
|
155
|
+
evaluate(event) {
|
|
156
|
+
const matches = [];
|
|
157
|
+
const eventSourceType = EVENT_TYPE_TO_SOURCE[event.type];
|
|
158
|
+
const allMatchedPatterns = [];
|
|
159
|
+
const sessionId = event.sessionId;
|
|
160
|
+
// Tier 0: Invariant enforcement (hard boundaries, pre-check)
|
|
161
|
+
if (this.config.invariantChecker) {
|
|
162
|
+
const violations = this.config.invariantChecker.check(event);
|
|
163
|
+
if (violations.length > 0) {
|
|
164
|
+
// Record denied event in session tracker for telemetry before returning
|
|
165
|
+
if (this.config.sessionTracker && sessionId) {
|
|
166
|
+
this.config.sessionTracker.recordEvent(sessionId, event, ['tier0-invariant-deny']);
|
|
167
|
+
}
|
|
168
|
+
return violations.map((v) => this.config.invariantChecker.buildDenyMatch(v));
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
// Tier 1: Blacklist lookup (known-bad skills)
|
|
172
|
+
if (this.config.blacklistProvider) {
|
|
173
|
+
const skillId = resolveBlacklistSkillId(event);
|
|
174
|
+
if (skillId) {
|
|
175
|
+
const entry = this.config.blacklistProvider.lookup(skillId);
|
|
176
|
+
if (entry) {
|
|
177
|
+
matches.push(buildBlacklistMatch(entry));
|
|
178
|
+
// Don't short-circuit -- continue for telemetry, but blacklist match
|
|
179
|
+
// has critical severity which guarantees DENY verdict
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// Tier 2: Pattern matching (existing regex rules)
|
|
184
|
+
const isSkillContext = event.scanContext === 'skill';
|
|
185
|
+
for (const rule of this.rules) {
|
|
186
|
+
// Skip deprecated and draft rules
|
|
187
|
+
if (rule.status === 'deprecated' || rule.status === 'draft')
|
|
188
|
+
continue;
|
|
189
|
+
// Skill context denylist: skip rules known to cause high FP on SKILL.md content
|
|
190
|
+
if (isSkillContext && SKILL_CONTEXT_DENYLIST.has(rule.id))
|
|
191
|
+
continue;
|
|
192
|
+
// Source type filtering: skip rules that don't apply to this event type
|
|
193
|
+
// When scanContext is 'skill', skip source-type filtering — all rules fire
|
|
194
|
+
if (!isSkillContext && eventSourceType && rule.agent_source.type !== eventSourceType) {
|
|
195
|
+
// Allow mcp_exchange rules to also match tool_call events
|
|
196
|
+
if (!(rule.agent_source.type === 'mcp_exchange' && eventSourceType === 'tool_call')) {
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const matchResult = this.evaluateRule(rule, event);
|
|
201
|
+
if (matchResult) {
|
|
202
|
+
// Skip MCP-only rules in skill context — they cause FP on security skills
|
|
203
|
+
// that describe attack patterns as examples. Skill context only runs
|
|
204
|
+
// skill-targeted rules + denylist-filtered rules.
|
|
205
|
+
if (isSkillContext && rule.tags.scan_target === 'mcp') {
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
matches.push(matchResult);
|
|
209
|
+
allMatchedPatterns.push(...matchResult.matchedPatterns);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
// Record event in session tracker (always, for cross-event sequence detection)
|
|
213
|
+
if (this.config.sessionTracker && sessionId) {
|
|
214
|
+
this.config.sessionTracker.recordEvent(sessionId, event, allMatchedPatterns);
|
|
215
|
+
}
|
|
216
|
+
// Layer 2: Skill behavioral fingerprinting (optional, no LLM)
|
|
217
|
+
const fingerprintStore = this.config.fingerprintStore;
|
|
218
|
+
if (fingerprintStore) {
|
|
219
|
+
const skillId = resolveSkillId(event);
|
|
220
|
+
if (skillId) {
|
|
221
|
+
const layer2Matches = runFingerprintLayer(fingerprintStore, event, skillId);
|
|
222
|
+
matches.push(...layer2Matches);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
// Sort by severity (critical first) then confidence
|
|
226
|
+
const sorted = matches.sort((a, b) => {
|
|
227
|
+
const severityOrder = { critical: 0, high: 1, medium: 2, low: 3, informational: 4 };
|
|
228
|
+
const aSev = severityOrder[a.rule.severity] ?? 4;
|
|
229
|
+
const bSev = severityOrder[b.rule.severity] ?? 4;
|
|
230
|
+
if (aSev !== bSev)
|
|
231
|
+
return aSev - bSev;
|
|
232
|
+
return b.confidence - a.confidence;
|
|
233
|
+
});
|
|
234
|
+
// Report detections to Threat Cloud (opt-in)
|
|
235
|
+
if (this.config.reporter) {
|
|
236
|
+
const hash = computeContentHash(event.content ?? '');
|
|
237
|
+
const scanTarget = isSkillContext ? 'skill' : (event.type ?? 'unknown');
|
|
238
|
+
const now = new Date().toISOString();
|
|
239
|
+
if (sorted.length > 0) {
|
|
240
|
+
for (const match of sorted) {
|
|
241
|
+
this.config.reporter.onDetection({
|
|
242
|
+
ruleId: match.rule.id,
|
|
243
|
+
severity: match.rule.severity,
|
|
244
|
+
scanTarget,
|
|
245
|
+
category: match.rule.tags?.category ?? 'unknown',
|
|
246
|
+
confidence: match.confidence,
|
|
247
|
+
timestamp: now,
|
|
248
|
+
contentHash: hash,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
else if (this.config.reporter.onClean) {
|
|
253
|
+
this.config.reporter.onClean({
|
|
254
|
+
rulesEvaluated: this.rules.length,
|
|
255
|
+
scanTarget,
|
|
256
|
+
timestamp: now,
|
|
257
|
+
contentHash: hash,
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return sorted;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Evaluate a single rule against an event.
|
|
265
|
+
* Supports both array-format and named-map-format conditions.
|
|
266
|
+
*/
|
|
267
|
+
evaluateRule(rule, event) {
|
|
268
|
+
const { detection } = rule;
|
|
269
|
+
const conditions = detection.conditions;
|
|
270
|
+
const allMatchedPatterns = [];
|
|
271
|
+
// Detect format: array or named map
|
|
272
|
+
if (Array.isArray(conditions)) {
|
|
273
|
+
return this.evaluateArrayConditions(rule, conditions, detection.condition, event, allMatchedPatterns);
|
|
274
|
+
}
|
|
275
|
+
return this.evaluateNamedConditions(rule, conditions, detection.condition, event, allMatchedPatterns);
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Evaluate array-format conditions: [{field, operator, value}, ...]
|
|
279
|
+
* with condition: "any" | "all"
|
|
280
|
+
*/
|
|
281
|
+
evaluateArrayConditions(rule, conditions, conditionExpr, event, allMatchedPatterns) {
|
|
282
|
+
const matchedConditionIndices = [];
|
|
283
|
+
const isAny = conditionExpr === 'any' || conditionExpr === 'or';
|
|
284
|
+
for (let i = 0; i < conditions.length; i++) {
|
|
285
|
+
const cond = conditions[i];
|
|
286
|
+
const result = this.evaluateArrayCondition(cond, event, rule.id, i, allMatchedPatterns);
|
|
287
|
+
if (result) {
|
|
288
|
+
matchedConditionIndices.push(i);
|
|
289
|
+
if (isAny)
|
|
290
|
+
break; // Short-circuit on first match for "any"
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const matched = isAny
|
|
294
|
+
? matchedConditionIndices.length > 0
|
|
295
|
+
: matchedConditionIndices.length === conditions.length;
|
|
296
|
+
if (!matched)
|
|
297
|
+
return null;
|
|
298
|
+
const baseConfidence = rule.tags.confidence === 'high' ? 0.9 : rule.tags.confidence === 'medium' ? 0.7 : 0.5;
|
|
299
|
+
const matchRatio = matchedConditionIndices.length / Math.max(conditions.length, 1);
|
|
300
|
+
const confidence = Math.min(baseConfidence + matchRatio * 0.1, 1.0);
|
|
301
|
+
return {
|
|
302
|
+
rule,
|
|
303
|
+
matchedConditions: matchedConditionIndices.map(String),
|
|
304
|
+
matchedPatterns: allMatchedPatterns,
|
|
305
|
+
confidence,
|
|
306
|
+
timestamp: new Date().toISOString(),
|
|
307
|
+
scan_context: 'native',
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Evaluate a single array-format condition {field, operator, value}.
|
|
312
|
+
*/
|
|
313
|
+
evaluateArrayCondition(cond, event, ruleId, index, matchedPatterns) {
|
|
314
|
+
// Sequence condition (has 'steps' array)
|
|
315
|
+
if (cond['steps'] && Array.isArray(cond['steps'])) {
|
|
316
|
+
return this.evaluateSequenceCondition(cond, event);
|
|
317
|
+
}
|
|
318
|
+
// Behavioral condition
|
|
319
|
+
if (cond['metric'] && cond['operator'] && cond['threshold'] !== undefined) {
|
|
320
|
+
return this.evaluateBehavioralCondition(cond, event);
|
|
321
|
+
}
|
|
322
|
+
const field = cond['field'];
|
|
323
|
+
const operator = cond['operator'];
|
|
324
|
+
const value = cond['value'];
|
|
325
|
+
if (!field || !operator || value === undefined)
|
|
326
|
+
return false;
|
|
327
|
+
const rawFieldValue = this.resolveField(field, event);
|
|
328
|
+
if (!rawFieldValue)
|
|
329
|
+
return false;
|
|
330
|
+
const fieldValue = normalizeUnicode(rawFieldValue);
|
|
331
|
+
switch (operator) {
|
|
332
|
+
case 'regex': {
|
|
333
|
+
// Try pre-compiled pattern first
|
|
334
|
+
const compiled = this.compiledPatterns.get(ruleId)?.get(String(index));
|
|
335
|
+
if (compiled && compiled.length > 0) {
|
|
336
|
+
// Test against both normalized and raw values so that patterns
|
|
337
|
+
// detecting zero-width/bidi characters can match before stripping
|
|
338
|
+
if (safeRegexTest(compiled[0], fieldValue) || safeRegexTest(compiled[0], rawFieldValue)) {
|
|
339
|
+
matchedPatterns.push(value);
|
|
340
|
+
return true;
|
|
341
|
+
}
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
// Fallback: compile on the fly
|
|
345
|
+
try {
|
|
346
|
+
const normalized = normalizeRegex(value);
|
|
347
|
+
const rFlags = normalized.includes('\\u{') || normalized.includes('\\p{') ? 'iu' : 'i';
|
|
348
|
+
const regex = new RegExp(normalized, rFlags);
|
|
349
|
+
if (safeRegexTest(regex, fieldValue) || safeRegexTest(regex, rawFieldValue)) {
|
|
350
|
+
matchedPatterns.push(value);
|
|
351
|
+
return true;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
// Invalid regex
|
|
356
|
+
}
|
|
357
|
+
return false;
|
|
358
|
+
}
|
|
359
|
+
case 'contains': {
|
|
360
|
+
if (fieldValue.toLowerCase().includes(value.toLowerCase())) {
|
|
361
|
+
matchedPatterns.push(value);
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
case 'exact': {
|
|
367
|
+
if (fieldValue === value) {
|
|
368
|
+
matchedPatterns.push(value);
|
|
369
|
+
return true;
|
|
370
|
+
}
|
|
371
|
+
return false;
|
|
372
|
+
}
|
|
373
|
+
case 'starts_with': {
|
|
374
|
+
if (fieldValue.toLowerCase().startsWith(value.toLowerCase())) {
|
|
375
|
+
matchedPatterns.push(value);
|
|
376
|
+
return true;
|
|
377
|
+
}
|
|
378
|
+
return false;
|
|
379
|
+
}
|
|
380
|
+
default:
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Evaluate named-map-format conditions: {name: {field, patterns, match_type}, ...}
|
|
386
|
+
* with condition: "name1 AND name2" | "name1 OR name2" | "name1"
|
|
387
|
+
*/
|
|
388
|
+
evaluateNamedConditions(rule, conditions, conditionExpr, event, allMatchedPatterns) {
|
|
389
|
+
const conditionResults = new Map();
|
|
390
|
+
const matchedConditionNames = [];
|
|
391
|
+
for (const [condName, condDef] of Object.entries(conditions)) {
|
|
392
|
+
const result = this.evaluateNamedCondition(condName, condDef, event, rule, allMatchedPatterns);
|
|
393
|
+
conditionResults.set(condName, result);
|
|
394
|
+
if (result) {
|
|
395
|
+
matchedConditionNames.push(condName);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
// Evaluate the boolean expression
|
|
399
|
+
const finalResult = this.evaluateExpression(conditionExpr, conditionResults);
|
|
400
|
+
if (!finalResult)
|
|
401
|
+
return null;
|
|
402
|
+
const baseConfidence = rule.tags.confidence === 'high' ? 0.9 : rule.tags.confidence === 'medium' ? 0.7 : 0.5;
|
|
403
|
+
const matchRatio = matchedConditionNames.length / Math.max(Object.keys(conditions).length, 1);
|
|
404
|
+
const confidence = Math.min(baseConfidence + matchRatio * 0.1, 1.0);
|
|
405
|
+
return {
|
|
406
|
+
rule,
|
|
407
|
+
matchedConditions: matchedConditionNames,
|
|
408
|
+
matchedPatterns: allMatchedPatterns,
|
|
409
|
+
confidence,
|
|
410
|
+
timestamp: new Date().toISOString(),
|
|
411
|
+
scan_context: 'native',
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Evaluate a single named condition against an event.
|
|
416
|
+
*/
|
|
417
|
+
evaluateNamedCondition(condName, condDef, event, rule, matchedPatterns) {
|
|
418
|
+
const cond = condDef;
|
|
419
|
+
// Pattern matching condition (named format with patterns array)
|
|
420
|
+
if (cond['patterns'] && cond['field']) {
|
|
421
|
+
return this.evaluatePatternCondition(cond, event, rule.id, condName, matchedPatterns);
|
|
422
|
+
}
|
|
423
|
+
// Behavioral condition
|
|
424
|
+
if (cond['metric'] && cond['operator'] && cond['threshold'] !== undefined) {
|
|
425
|
+
return this.evaluateBehavioralCondition(cond, event);
|
|
426
|
+
}
|
|
427
|
+
// Sequence condition
|
|
428
|
+
if (cond['steps'] && Array.isArray(cond['steps'])) {
|
|
429
|
+
return this.evaluateSequenceCondition(cond, event);
|
|
430
|
+
}
|
|
431
|
+
return false;
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* Evaluate a pattern matching condition (named format with patterns array).
|
|
435
|
+
*/
|
|
436
|
+
evaluatePatternCondition(cond, event, ruleId, condName, matchedPatterns) {
|
|
437
|
+
const rawFieldValue = this.resolveField(cond.field, event);
|
|
438
|
+
if (!rawFieldValue)
|
|
439
|
+
return false;
|
|
440
|
+
const fieldValue = normalizeUnicode(rawFieldValue);
|
|
441
|
+
// Code block suppression: for rules that commonly false-positive on
|
|
442
|
+
// documentation content (shell commands, file paths in code examples),
|
|
443
|
+
// check if the match falls inside a markdown code block.
|
|
444
|
+
// Prompt injection rules (ATR-001 through ATR-005, ATR-080+) are NOT suppressed
|
|
445
|
+
// because attackers can hide injections in code blocks too.
|
|
446
|
+
const suppressInCodeBlocks = this.shouldSuppressInCodeBlocks(ruleId);
|
|
447
|
+
const codeRanges = suppressInCodeBlocks ? buildCodeBlockRanges(fieldValue) : [];
|
|
448
|
+
// Get pre-compiled patterns
|
|
449
|
+
const compiled = this.compiledPatterns.get(ruleId)?.get(condName);
|
|
450
|
+
if (compiled) {
|
|
451
|
+
for (let i = 0; i < compiled.length; i++) {
|
|
452
|
+
if (safeRegexTest(compiled[i], fieldValue) || (rawFieldValue && safeRegexTest(compiled[i], rawFieldValue))) {
|
|
453
|
+
// If match is inside a code block and this rule supports suppression, skip it
|
|
454
|
+
if (suppressInCodeBlocks && codeRanges.length > 0 && isInsideCodeBlock(fieldValue, compiled[i], codeRanges)) {
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
matchedPatterns.push(cond.patterns[i] ?? 'unknown');
|
|
458
|
+
return true;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
return false;
|
|
462
|
+
}
|
|
463
|
+
// Fallback: direct string matching
|
|
464
|
+
const checkValue = cond.case_sensitive ? fieldValue : fieldValue.toLowerCase();
|
|
465
|
+
for (const pattern of cond.patterns) {
|
|
466
|
+
const checkPattern = cond.case_sensitive ? pattern : pattern.toLowerCase();
|
|
467
|
+
switch (cond.match_type) {
|
|
468
|
+
case 'contains':
|
|
469
|
+
if (checkValue.includes(checkPattern)) {
|
|
470
|
+
matchedPatterns.push(pattern);
|
|
471
|
+
return true;
|
|
472
|
+
}
|
|
473
|
+
break;
|
|
474
|
+
case 'exact':
|
|
475
|
+
if (checkValue === checkPattern) {
|
|
476
|
+
matchedPatterns.push(pattern);
|
|
477
|
+
return true;
|
|
478
|
+
}
|
|
479
|
+
break;
|
|
480
|
+
case 'starts_with':
|
|
481
|
+
if (checkValue.startsWith(checkPattern)) {
|
|
482
|
+
matchedPatterns.push(pattern);
|
|
483
|
+
return true;
|
|
484
|
+
}
|
|
485
|
+
break;
|
|
486
|
+
case 'regex':
|
|
487
|
+
default: {
|
|
488
|
+
try {
|
|
489
|
+
const flags = cond.case_sensitive ? '' : 'i';
|
|
490
|
+
const regex = new RegExp(pattern, flags);
|
|
491
|
+
if (safeRegexTest(regex, fieldValue)) {
|
|
492
|
+
matchedPatterns.push(pattern);
|
|
493
|
+
return true;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
catch {
|
|
497
|
+
// Invalid regex, skip
|
|
498
|
+
}
|
|
499
|
+
break;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return false;
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Determine if a rule should suppress matches inside markdown code blocks.
|
|
507
|
+
* Rules that commonly false-positive on documentation (shell commands, file paths,
|
|
508
|
+
* code examples) are suppressed. Prompt injection rules are NEVER suppressed
|
|
509
|
+
* because attackers deliberately hide payloads in code blocks.
|
|
510
|
+
*/
|
|
511
|
+
shouldSuppressInCodeBlocks(ruleId) {
|
|
512
|
+
const rule = this.rules.find(r => r.id === ruleId);
|
|
513
|
+
if (!rule)
|
|
514
|
+
return false;
|
|
515
|
+
const category = rule.tags?.category ?? '';
|
|
516
|
+
const subcategory = rule.tags?.subcategory ?? '';
|
|
517
|
+
// Categories that commonly match documentation content
|
|
518
|
+
const suppressCategories = [
|
|
519
|
+
'privilege-escalation', // ATR-111 shell metacharacter
|
|
520
|
+
'context-exfiltration', // ATR-113 credential paths
|
|
521
|
+
'skill-compromise', // supply chain patterns in docs
|
|
522
|
+
];
|
|
523
|
+
// Never suppress skill-content rules (ATR-120+) — code blocks in SKILL.md
|
|
524
|
+
// are executable instructions, not documentation examples
|
|
525
|
+
const neverSuppressSubcategories = [
|
|
526
|
+
'skill-instruction-injection',
|
|
527
|
+
'dangerous-script',
|
|
528
|
+
'weaponized-skill',
|
|
529
|
+
'skill-overreach',
|
|
530
|
+
'skill-squatting',
|
|
531
|
+
];
|
|
532
|
+
if (neverSuppressSubcategories.includes(subcategory))
|
|
533
|
+
return false;
|
|
534
|
+
return suppressCategories.includes(category);
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* Evaluate a behavioral threshold condition.
|
|
538
|
+
* When a session tracker is available and the event has a sessionId,
|
|
539
|
+
* supports session-derived metrics: call_frequency, pattern_frequency, event_count.
|
|
540
|
+
*/
|
|
541
|
+
evaluateBehavioralCondition(cond, event) {
|
|
542
|
+
const metricValue = this.resolveMetricValue(cond, event);
|
|
543
|
+
if (metricValue === undefined)
|
|
544
|
+
return false;
|
|
545
|
+
switch (cond.operator) {
|
|
546
|
+
case 'gt': return metricValue > cond.threshold;
|
|
547
|
+
case 'lt': return metricValue < cond.threshold;
|
|
548
|
+
case 'eq': return metricValue === cond.threshold;
|
|
549
|
+
case 'gte': return metricValue >= cond.threshold;
|
|
550
|
+
case 'lte': return metricValue <= cond.threshold;
|
|
551
|
+
case 'deviation_from_baseline':
|
|
552
|
+
return Math.abs(metricValue) > cond.threshold;
|
|
553
|
+
default:
|
|
554
|
+
return false;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Resolve a metric value from event metrics or session tracker.
|
|
559
|
+
* Session-derived metrics use the format: "call_frequency:toolName" or "pattern_frequency:pattern".
|
|
560
|
+
*/
|
|
561
|
+
resolveMetricValue(cond, event) {
|
|
562
|
+
// Check event-level metrics first
|
|
563
|
+
const directValue = event.metrics?.[cond.metric];
|
|
564
|
+
if (directValue !== undefined)
|
|
565
|
+
return directValue;
|
|
566
|
+
// Try session tracker for session-derived metrics
|
|
567
|
+
const tracker = this.config.sessionTracker;
|
|
568
|
+
const sessionId = event.sessionId;
|
|
569
|
+
if (!tracker || !sessionId)
|
|
570
|
+
return undefined;
|
|
571
|
+
const windowMs = this.parseWindowMs(cond.window);
|
|
572
|
+
if (cond.metric.startsWith('call_frequency:')) {
|
|
573
|
+
const toolName = cond.metric.slice('call_frequency:'.length);
|
|
574
|
+
return tracker.getCallFrequency(sessionId, toolName, windowMs);
|
|
575
|
+
}
|
|
576
|
+
if (cond.metric.startsWith('pattern_frequency:')) {
|
|
577
|
+
const pattern = cond.metric.slice('pattern_frequency:'.length);
|
|
578
|
+
return tracker.getPatternFrequency(sessionId, pattern, windowMs);
|
|
579
|
+
}
|
|
580
|
+
if (cond.metric === 'event_count') {
|
|
581
|
+
return tracker.getEventCount(sessionId, windowMs);
|
|
582
|
+
}
|
|
583
|
+
return undefined;
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* Parse a window string (e.g. "5m", "1h", "30s") to milliseconds.
|
|
587
|
+
* Defaults to 5 minutes if not specified or unparseable.
|
|
588
|
+
*/
|
|
589
|
+
parseWindowMs(window) {
|
|
590
|
+
if (!window)
|
|
591
|
+
return 5 * 60 * 1000;
|
|
592
|
+
const match = window.match(/^(\d+)\s*(s|m|h)$/);
|
|
593
|
+
if (!match)
|
|
594
|
+
return 5 * 60 * 1000;
|
|
595
|
+
const value = parseInt(match[1], 10);
|
|
596
|
+
const unit = match[2];
|
|
597
|
+
switch (unit) {
|
|
598
|
+
case 's': return value * 1000;
|
|
599
|
+
case 'm': return value * 60 * 1000;
|
|
600
|
+
case 'h': return value * 60 * 60 * 1000;
|
|
601
|
+
default: return 5 * 60 * 1000;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* Evaluate a sequence condition against the current event.
|
|
606
|
+
*
|
|
607
|
+
* Two modes:
|
|
608
|
+
* 1. Session-aware (when SessionTracker + sessionId available):
|
|
609
|
+
* Checks patterns across historical events in the session.
|
|
610
|
+
* Respects `ordered` flag and `within` time window.
|
|
611
|
+
* 2. Single-event fallback: checks if patterns co-occur in one event.
|
|
612
|
+
*/
|
|
613
|
+
evaluateSequenceCondition(cond, event) {
|
|
614
|
+
const steps = cond['steps'];
|
|
615
|
+
if (!steps || steps.length === 0)
|
|
616
|
+
return false;
|
|
617
|
+
// Try session-aware detection first
|
|
618
|
+
const tracker = this.config.sessionTracker;
|
|
619
|
+
const sessionId = event.sessionId;
|
|
620
|
+
if (tracker && sessionId) {
|
|
621
|
+
const sessionResult = this.evaluateSequenceAcrossSession(steps, cond, tracker, sessionId, event);
|
|
622
|
+
if (sessionResult)
|
|
623
|
+
return true;
|
|
624
|
+
}
|
|
625
|
+
// Fallback: single-event check
|
|
626
|
+
return this.evaluateSequenceSingleEvent(steps, event);
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Cross-event sequence detection using SessionTracker.
|
|
630
|
+
* Checks if step patterns have been seen across events in order.
|
|
631
|
+
*/
|
|
632
|
+
evaluateSequenceAcrossSession(steps, cond, tracker, sessionId, currentEvent) {
|
|
633
|
+
const ordered = cond['ordered'] !== false; // default: true
|
|
634
|
+
const withinMs = this.parseWindowMs(cond['within']);
|
|
635
|
+
const snapshot = tracker.getSessionSnapshot(sessionId);
|
|
636
|
+
if (!snapshot)
|
|
637
|
+
return false;
|
|
638
|
+
// Collect all events: historical + current
|
|
639
|
+
const allEvents = [...snapshot.events, currentEvent];
|
|
640
|
+
if (allEvents.length < steps.length)
|
|
641
|
+
return false;
|
|
642
|
+
// For each step, find the earliest event that matches
|
|
643
|
+
const stepMatches = [];
|
|
644
|
+
for (let si = 0; si < steps.length; si++) {
|
|
645
|
+
const step = steps[si];
|
|
646
|
+
const patterns = step['patterns'];
|
|
647
|
+
if (!patterns)
|
|
648
|
+
continue;
|
|
649
|
+
for (let ei = 0; ei < allEvents.length; ei++) {
|
|
650
|
+
const ev = allEvents[ei];
|
|
651
|
+
const content = normalizeUnicode(ev.content);
|
|
652
|
+
let matched = false;
|
|
653
|
+
for (const pattern of patterns) {
|
|
654
|
+
try {
|
|
655
|
+
if (safeRegexTest(new RegExp(pattern, 'i'), content)) {
|
|
656
|
+
matched = true;
|
|
657
|
+
break;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
catch {
|
|
661
|
+
// Invalid regex
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
if (matched) {
|
|
665
|
+
stepMatches.push({
|
|
666
|
+
stepIndex: si,
|
|
667
|
+
eventIndex: ei,
|
|
668
|
+
timestamp: new Date(ev.timestamp).getTime(),
|
|
669
|
+
});
|
|
670
|
+
break; // First match per step
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
// Need all steps to match
|
|
675
|
+
if (stepMatches.length < steps.length)
|
|
676
|
+
return false;
|
|
677
|
+
// Check ordering
|
|
678
|
+
if (ordered) {
|
|
679
|
+
for (let i = 1; i < stepMatches.length; i++) {
|
|
680
|
+
if (stepMatches[i].eventIndex <= stepMatches[i - 1].eventIndex) {
|
|
681
|
+
return false; // Out of order
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
// Check time window
|
|
686
|
+
if (withinMs > 0) {
|
|
687
|
+
const firstTs = Math.min(...stepMatches.map((m) => m.timestamp));
|
|
688
|
+
const lastTs = Math.max(...stepMatches.map((m) => m.timestamp));
|
|
689
|
+
if (lastTs - firstTs > withinMs)
|
|
690
|
+
return false;
|
|
691
|
+
}
|
|
692
|
+
return true;
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Single-event fallback: check if step patterns co-occur in one event.
|
|
696
|
+
*/
|
|
697
|
+
evaluateSequenceSingleEvent(steps, event) {
|
|
698
|
+
const content = normalizeUnicode(event.content);
|
|
699
|
+
let matchCount = 0;
|
|
700
|
+
for (const step of steps) {
|
|
701
|
+
const patterns = step['patterns'];
|
|
702
|
+
if (patterns) {
|
|
703
|
+
for (const pattern of patterns) {
|
|
704
|
+
try {
|
|
705
|
+
if (safeRegexTest(new RegExp(pattern, 'i'), content)) {
|
|
706
|
+
matchCount++;
|
|
707
|
+
break;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
catch {
|
|
711
|
+
// Invalid regex
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
return matchCount >= 2;
|
|
717
|
+
}
|
|
718
|
+
// parseWindowMs already defined above (behavioral conditions)
|
|
719
|
+
/**
|
|
720
|
+
* Resolve a field value from an agent event.
|
|
721
|
+
*/
|
|
722
|
+
resolveField(fieldName, event) {
|
|
723
|
+
// Check explicit fields first
|
|
724
|
+
if (event.fields?.[fieldName]) {
|
|
725
|
+
return event.fields[fieldName];
|
|
726
|
+
}
|
|
727
|
+
// Map standard field names to event properties
|
|
728
|
+
const defaultField = EVENT_TYPE_TO_FIELD[event.type];
|
|
729
|
+
if (fieldName === defaultField || fieldName === 'content') {
|
|
730
|
+
return event.content;
|
|
731
|
+
}
|
|
732
|
+
// Common field aliases
|
|
733
|
+
switch (fieldName) {
|
|
734
|
+
case 'user_input':
|
|
735
|
+
return event.type === 'llm_input' ? event.content : event.fields?.['user_input'];
|
|
736
|
+
case 'agent_output':
|
|
737
|
+
return event.type === 'llm_output' ? event.content : event.fields?.['agent_output'];
|
|
738
|
+
case 'tool_response':
|
|
739
|
+
return event.type === 'tool_response' ? event.content : event.fields?.['tool_response'];
|
|
740
|
+
case 'tool_name':
|
|
741
|
+
return event.fields?.['tool_name'] ?? (event.type === 'tool_call' ? event.content : undefined);
|
|
742
|
+
case 'tool_args':
|
|
743
|
+
return event.fields?.['tool_args'] ?? (event.type === 'tool_call' ? event.content : undefined);
|
|
744
|
+
case 'agent_message':
|
|
745
|
+
return event.type === 'multi_agent_message' ? event.content : event.fields?.['agent_message'];
|
|
746
|
+
default:
|
|
747
|
+
// Try metadata
|
|
748
|
+
return event.metadata?.[fieldName];
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Evaluate a boolean expression string against condition results.
|
|
753
|
+
* Supports AND, OR, NOT operators.
|
|
754
|
+
*/
|
|
755
|
+
evaluateExpression(expression, results) {
|
|
756
|
+
const expr = expression.trim();
|
|
757
|
+
// Simple single condition
|
|
758
|
+
if (results.has(expr)) {
|
|
759
|
+
return results.get(expr) ?? false;
|
|
760
|
+
}
|
|
761
|
+
// Handle NOT
|
|
762
|
+
if (expr.startsWith('NOT ') || expr.startsWith('not ')) {
|
|
763
|
+
const inner = expr.slice(4).trim();
|
|
764
|
+
return !this.evaluateExpression(inner, results);
|
|
765
|
+
}
|
|
766
|
+
// Handle OR (lower precedence — split first so AND binds tighter)
|
|
767
|
+
const orParts = this.splitByOperator(expr, 'OR');
|
|
768
|
+
if (orParts.length > 1) {
|
|
769
|
+
return orParts.some((part) => this.evaluateExpression(part, results));
|
|
770
|
+
}
|
|
771
|
+
// Handle AND (higher precedence — evaluated within each OR branch)
|
|
772
|
+
const andParts = this.splitByOperator(expr, 'AND');
|
|
773
|
+
if (andParts.length > 1) {
|
|
774
|
+
return andParts.every((part) => this.evaluateExpression(part, results));
|
|
775
|
+
}
|
|
776
|
+
// Handle parentheses
|
|
777
|
+
if (expr.startsWith('(') && expr.endsWith(')')) {
|
|
778
|
+
return this.evaluateExpression(expr.slice(1, -1), results);
|
|
779
|
+
}
|
|
780
|
+
// Default: treat as condition name
|
|
781
|
+
return results.get(expr) ?? false;
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Split expression by operator, respecting parentheses.
|
|
785
|
+
*/
|
|
786
|
+
splitByOperator(expr, operator) {
|
|
787
|
+
const parts = [];
|
|
788
|
+
let depth = 0;
|
|
789
|
+
let current = '';
|
|
790
|
+
const op = ` ${operator} `;
|
|
791
|
+
const opLower = ` ${operator.toLowerCase()} `;
|
|
792
|
+
for (let i = 0; i < expr.length; i++) {
|
|
793
|
+
const char = expr[i];
|
|
794
|
+
if (char === '(')
|
|
795
|
+
depth++;
|
|
796
|
+
if (char === ')')
|
|
797
|
+
depth--;
|
|
798
|
+
if (depth === 0) {
|
|
799
|
+
const remaining = expr.slice(i);
|
|
800
|
+
if (remaining.startsWith(op) || remaining.startsWith(opLower)) {
|
|
801
|
+
parts.push(current.trim());
|
|
802
|
+
current = '';
|
|
803
|
+
i += op.length - 1;
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
current += char;
|
|
808
|
+
}
|
|
809
|
+
if (current.trim()) {
|
|
810
|
+
parts.push(current.trim());
|
|
811
|
+
}
|
|
812
|
+
return parts;
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Pre-compile regex patterns for a rule (performance optimization).
|
|
816
|
+
* Supports both array-format and named-map-format conditions.
|
|
817
|
+
*/
|
|
818
|
+
compilePatterns(rule) {
|
|
819
|
+
const ruleMap = new Map();
|
|
820
|
+
const conditions = rule.detection.conditions;
|
|
821
|
+
if (Array.isArray(conditions)) {
|
|
822
|
+
// Array format: compile each {operator: regex, value: "pattern"} entry
|
|
823
|
+
for (let i = 0; i < conditions.length; i++) {
|
|
824
|
+
const cond = conditions[i];
|
|
825
|
+
if (cond['operator'] === 'regex' && typeof cond['value'] === 'string') {
|
|
826
|
+
try {
|
|
827
|
+
const pattern = normalizeRegex(cond['value']);
|
|
828
|
+
const flags = pattern.includes('\\u{') || pattern.includes('\\p{') ? 'iu' : 'i';
|
|
829
|
+
ruleMap.set(String(i), [new RegExp(pattern, flags)]);
|
|
830
|
+
}
|
|
831
|
+
catch {
|
|
832
|
+
// Invalid regex, skip
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
else {
|
|
838
|
+
// Named format: compile patterns arrays
|
|
839
|
+
for (const [condName, condDef] of Object.entries(conditions)) {
|
|
840
|
+
const cond = condDef;
|
|
841
|
+
if (cond['patterns'] && Array.isArray(cond['patterns'])) {
|
|
842
|
+
const matchType = cond['match_type'] ?? 'regex';
|
|
843
|
+
const caseSensitive = cond['case_sensitive'] ?? false;
|
|
844
|
+
const flags = caseSensitive ? '' : 'i';
|
|
845
|
+
const compiled = [];
|
|
846
|
+
for (const pattern of cond['patterns']) {
|
|
847
|
+
try {
|
|
848
|
+
if (matchType === 'regex') {
|
|
849
|
+
compiled.push(new RegExp(normalizeRegex(pattern), flags));
|
|
850
|
+
}
|
|
851
|
+
else if (matchType === 'contains') {
|
|
852
|
+
compiled.push(new RegExp(escapeRegex(pattern), flags));
|
|
853
|
+
}
|
|
854
|
+
else if (matchType === 'exact') {
|
|
855
|
+
compiled.push(new RegExp(`^${escapeRegex(pattern)}$`, flags));
|
|
856
|
+
}
|
|
857
|
+
else if (matchType === 'starts_with') {
|
|
858
|
+
compiled.push(new RegExp(`^${escapeRegex(pattern)}`, flags));
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
catch {
|
|
862
|
+
// Invalid regex pattern, skip
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
ruleMap.set(condName, compiled);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
this.compiledPatterns.set(rule.id, ruleMap);
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Evaluate an event and compute a verdict with optional action execution.
|
|
873
|
+
*
|
|
874
|
+
* Combines evaluate() + computeVerdict() + optional ActionExecutor
|
|
875
|
+
* into a single call for convenience.
|
|
876
|
+
*/
|
|
877
|
+
async evaluateWithVerdict(event, executor) {
|
|
878
|
+
const layersUsed = ['layer1-regex'];
|
|
879
|
+
let matches = this.evaluate(event);
|
|
880
|
+
// Tier 0 + Tier 1 run inside evaluate(), track them
|
|
881
|
+
if (this.config.invariantChecker)
|
|
882
|
+
layersUsed.push('tier0-invariant');
|
|
883
|
+
if (this.config.blacklistProvider)
|
|
884
|
+
layersUsed.push('tier1-blacklist');
|
|
885
|
+
// Layer 2 runs synchronously inside evaluate(), but track if it was configured
|
|
886
|
+
if (this.config.fingerprintStore) {
|
|
887
|
+
layersUsed.push('layer2-fingerprint');
|
|
888
|
+
}
|
|
889
|
+
// Tier 2.5: Embedding similarity (async, runs on all events)
|
|
890
|
+
if (this.config.embeddingModule?.isAvailable()) {
|
|
891
|
+
layersUsed.push('tier2.5-embedding');
|
|
892
|
+
try {
|
|
893
|
+
const embResult = await this.config.embeddingModule.evaluate(event, {
|
|
894
|
+
module: 'embedding',
|
|
895
|
+
function: 'similarity_search',
|
|
896
|
+
args: { field: 'content' },
|
|
897
|
+
operator: 'gte',
|
|
898
|
+
threshold: 0.65,
|
|
899
|
+
});
|
|
900
|
+
if (embResult.matched) {
|
|
901
|
+
const severity = embResult.value >= 0.95 ? 'critical'
|
|
902
|
+
: embResult.value >= 0.88 ? 'high'
|
|
903
|
+
: 'medium';
|
|
904
|
+
const syntheticMatch = {
|
|
905
|
+
rule: {
|
|
906
|
+
title: `Embedding Match: ${embResult.description}`,
|
|
907
|
+
id: 'tier2.5-embedding-match',
|
|
908
|
+
status: 'experimental',
|
|
909
|
+
description: embResult.description,
|
|
910
|
+
author: 'atr-engine/tier2.5',
|
|
911
|
+
date: new Date().toISOString().slice(0, 10),
|
|
912
|
+
severity,
|
|
913
|
+
tags: { category: 'prompt-injection', subcategory: 'semantic-similarity', confidence: 'high' },
|
|
914
|
+
agent_source: { type: 'llm_io' },
|
|
915
|
+
detection: { conditions: {}, condition: 'tier2.5-runtime' },
|
|
916
|
+
response: {
|
|
917
|
+
actions: severity === 'critical'
|
|
918
|
+
? ['block_input', 'alert']
|
|
919
|
+
: ['alert'],
|
|
920
|
+
},
|
|
921
|
+
},
|
|
922
|
+
matchedConditions: ['embedding_similarity'],
|
|
923
|
+
matchedPatterns: [`similarity=${embResult.value.toFixed(3)}`],
|
|
924
|
+
confidence: embResult.value,
|
|
925
|
+
timestamp: new Date().toISOString(),
|
|
926
|
+
scan_context: 'native',
|
|
927
|
+
};
|
|
928
|
+
matches = [...matches, syntheticMatch];
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
catch {
|
|
932
|
+
// Embedding failure is non-fatal
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
// Layer 3: Semantic LLM-as-judge (async, conditional)
|
|
936
|
+
if (this.semanticModuleInstance && shouldRunSemanticLayer(matches, event)) {
|
|
937
|
+
layersUsed.push('layer3-semantic');
|
|
938
|
+
const semanticMatches = await runSemanticLayer(this.semanticModuleInstance, event, matches);
|
|
939
|
+
if (semanticMatches.length > 0) {
|
|
940
|
+
// Merge and re-sort immutably
|
|
941
|
+
const merged = [...matches, ...semanticMatches];
|
|
942
|
+
const severityOrder = {
|
|
943
|
+
critical: 0, high: 1, medium: 2, low: 3, informational: 4,
|
|
944
|
+
};
|
|
945
|
+
merged.sort((a, b) => {
|
|
946
|
+
const aSev = severityOrder[a.rule.severity] ?? 4;
|
|
947
|
+
const bSev = severityOrder[b.rule.severity] ?? 4;
|
|
948
|
+
if (aSev !== bSev)
|
|
949
|
+
return aSev - bSev;
|
|
950
|
+
return b.confidence - a.confidence;
|
|
951
|
+
});
|
|
952
|
+
matches = merged;
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
const verdict = computeVerdict(matches);
|
|
956
|
+
let actionResults = Object.freeze([]);
|
|
957
|
+
if (executor && verdict.actions.length > 0) {
|
|
958
|
+
const context = Object.freeze({
|
|
959
|
+
event,
|
|
960
|
+
matches,
|
|
961
|
+
verdict,
|
|
962
|
+
sessionId: event.sessionId,
|
|
963
|
+
metadata: event.metadata ? Object.freeze({ ...event.metadata }) : undefined,
|
|
964
|
+
});
|
|
965
|
+
actionResults = await executor.execute(context);
|
|
966
|
+
}
|
|
967
|
+
return { verdict, actionResults, layersUsed: Object.freeze(layersUsed) };
|
|
968
|
+
}
|
|
969
|
+
/** Get loaded rule count */
|
|
970
|
+
getRuleCount() {
|
|
971
|
+
return this.rules.length;
|
|
972
|
+
}
|
|
973
|
+
/** Get all loaded rules */
|
|
974
|
+
getRules() {
|
|
975
|
+
return this.rules;
|
|
976
|
+
}
|
|
977
|
+
/** Get a rule by ID */
|
|
978
|
+
getRuleById(id) {
|
|
979
|
+
return this.rules.find((r) => r.id === id);
|
|
980
|
+
}
|
|
981
|
+
/** Get rules by category */
|
|
982
|
+
getRulesByCategory(category) {
|
|
983
|
+
return this.rules.filter((r) => r.tags.category === category);
|
|
984
|
+
}
|
|
985
|
+
/**
|
|
986
|
+
* Scan SKILL.md content for threats.
|
|
987
|
+
* All rules fire with scanContext='skill':
|
|
988
|
+
* - skill/both rules: native context, full confidence
|
|
989
|
+
* - MCP-only rules: cross-context, confidence * 0.6
|
|
990
|
+
* Also decodes base64 blocks and scans decoded content.
|
|
991
|
+
* Code-block suppression and FP denylist applied in evaluate().
|
|
992
|
+
*/
|
|
993
|
+
scanSkill(content) {
|
|
994
|
+
const baseEvent = {
|
|
995
|
+
type: 'mcp_exchange',
|
|
996
|
+
timestamp: new Date().toISOString(),
|
|
997
|
+
sessionId: 'skill-scan',
|
|
998
|
+
fields: {},
|
|
999
|
+
scanContext: 'skill',
|
|
1000
|
+
};
|
|
1001
|
+
// Scan original content
|
|
1002
|
+
const matches = this.evaluate({ ...baseEvent, content });
|
|
1003
|
+
// Scan base64-decoded blocks for hidden payloads
|
|
1004
|
+
const decodedBlocks = decodeBase64Blocks(content);
|
|
1005
|
+
for (const block of decodedBlocks) {
|
|
1006
|
+
const blockMatches = this.evaluate({ ...baseEvent, content: block });
|
|
1007
|
+
for (const m of blockMatches) {
|
|
1008
|
+
// Tag decoded matches so consumers know the source
|
|
1009
|
+
matches.push({
|
|
1010
|
+
...m,
|
|
1011
|
+
matchedPatterns: [...m.matchedPatterns, '[decoded:base64]'],
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
return matches;
|
|
1016
|
+
}
|
|
1017
|
+
/** Scan a SKILL.md file and return a unified ScanResult with content_hash. */
|
|
1018
|
+
scanSkillFull(content, filePath) {
|
|
1019
|
+
const matches = this.scanSkill(content);
|
|
1020
|
+
return {
|
|
1021
|
+
scan_type: 'skill',
|
|
1022
|
+
content_hash: computeContentHash(content),
|
|
1023
|
+
input_file: filePath,
|
|
1024
|
+
timestamp: new Date().toISOString(),
|
|
1025
|
+
rules_loaded: this.rules.length,
|
|
1026
|
+
matches,
|
|
1027
|
+
threat_count: matches.length,
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
/** Evaluate an MCP agent event and return a unified ScanResult with content_hash. */
|
|
1031
|
+
evaluateFull(event, filePath) {
|
|
1032
|
+
const matches = this.evaluate(event);
|
|
1033
|
+
// Hash content + fields to distinguish tool-call events with same content but different args
|
|
1034
|
+
const hashInput = event.fields
|
|
1035
|
+
? event.content + '\0' + JSON.stringify(event.fields)
|
|
1036
|
+
: event.content;
|
|
1037
|
+
return {
|
|
1038
|
+
scan_type: 'mcp',
|
|
1039
|
+
content_hash: computeContentHash(hashInput),
|
|
1040
|
+
input_file: filePath,
|
|
1041
|
+
timestamp: new Date().toISOString(),
|
|
1042
|
+
rules_loaded: this.rules.length,
|
|
1043
|
+
matches,
|
|
1044
|
+
threat_count: matches.length,
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
function escapeRegex(str) {
|
|
1049
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
1050
|
+
}
|
|
1051
|
+
/**
|
|
1052
|
+
* Strip inline flags like (?i) from regex patterns.
|
|
1053
|
+
* JavaScript RegExp uses flags as a constructor parameter, not inline.
|
|
1054
|
+
*/
|
|
1055
|
+
function normalizeRegex(pattern) {
|
|
1056
|
+
return pattern.replace(/^\(\?[imsx]+\)/, '');
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Normalize Unicode text to NFC form and strip zero-width characters.
|
|
1060
|
+
* This prevents evasion via combining characters, zero-width joiners, etc.
|
|
1061
|
+
*/
|
|
1062
|
+
function normalizeUnicode(text) {
|
|
1063
|
+
return text
|
|
1064
|
+
.normalize('NFC')
|
|
1065
|
+
.replace(/[\u200B\u200C\u200D\uFEFF\u2060\u180E\u200E\u200F\u202A-\u202E\u2066-\u2069]/g, '');
|
|
1066
|
+
}
|
|
1067
|
+
/** Maximum input length for regex evaluation to mitigate ReDoS */
|
|
1068
|
+
const MAX_EVAL_LENGTH = 100_000;
|
|
1069
|
+
/**
|
|
1070
|
+
* Safely test a regex pattern against input with length limits.
|
|
1071
|
+
* Returns false if input exceeds MAX_EVAL_LENGTH to prevent ReDoS.
|
|
1072
|
+
*/
|
|
1073
|
+
function safeRegexTest(regex, input) {
|
|
1074
|
+
if (input.length > MAX_EVAL_LENGTH)
|
|
1075
|
+
return false;
|
|
1076
|
+
return regex.test(input);
|
|
1077
|
+
}
|
|
1078
|
+
/**
|
|
1079
|
+
* Build a set of character ranges that fall inside markdown code blocks.
|
|
1080
|
+
* Covers both fenced (``` ```) and inline (`code`) blocks.
|
|
1081
|
+
* Used to suppress false positives when regex matches documentation examples
|
|
1082
|
+
* rather than actual attack payloads.
|
|
1083
|
+
*/
|
|
1084
|
+
function buildCodeBlockRanges(text) {
|
|
1085
|
+
const ranges = [];
|
|
1086
|
+
// Fenced code blocks: ```...```
|
|
1087
|
+
const fenced = /```[\s\S]*?```/g;
|
|
1088
|
+
let m;
|
|
1089
|
+
while ((m = fenced.exec(text)) !== null) {
|
|
1090
|
+
ranges.push([m.index, m.index + m[0].length]);
|
|
1091
|
+
}
|
|
1092
|
+
// Inline code: `...` (but not inside fenced blocks)
|
|
1093
|
+
const inline = /`[^`\n]+`/g;
|
|
1094
|
+
while ((m = inline.exec(text)) !== null) {
|
|
1095
|
+
const pos = m.index;
|
|
1096
|
+
const inFenced = ranges.some(([start, end]) => pos >= start && pos < end);
|
|
1097
|
+
if (!inFenced) {
|
|
1098
|
+
ranges.push([pos, pos + m[0].length]);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
return ranges;
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Check if a regex match position falls inside a code block.
|
|
1105
|
+
*/
|
|
1106
|
+
function isInsideCodeBlock(text, regex, codeRanges) {
|
|
1107
|
+
if (codeRanges.length === 0)
|
|
1108
|
+
return false;
|
|
1109
|
+
// Reset regex state and find match position
|
|
1110
|
+
const searchRegex = new RegExp(regex.source, regex.flags.includes('g') ? regex.flags : regex.flags + 'g');
|
|
1111
|
+
const m = searchRegex.exec(text);
|
|
1112
|
+
if (!m)
|
|
1113
|
+
return false;
|
|
1114
|
+
const matchPos = m.index;
|
|
1115
|
+
return codeRanges.some(([start, end]) => matchPos >= start && matchPos < end);
|
|
1116
|
+
}
|
|
1117
|
+
//# sourceMappingURL=engine.js.map
|