aiwaf 1.0.1 → 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.
@@ -1,117 +1,117 @@
1
- class IsolationTree {
2
- constructor(depth = 0, maxDepth = 0) {
3
- this.depth = depth;
4
- this.maxDepth = maxDepth;
5
- this.left = null;
6
- this.right = null;
7
- this.splitAttr = null;
8
- this.splitValue = null;
9
- this.size = 0;
10
- }
11
-
12
- fit(data) {
13
- this.size = data.length;
14
- if (this.depth >= this.maxDepth || data.length <= 1) return;
15
- const numFeatures = data[0].length;
16
- this.splitAttr = Math.floor(Math.random() * numFeatures);
17
- let vals = data.map(row => row[this.splitAttr]);
18
- const min = Math.min(...vals), max = Math.max(...vals);
19
- if (min === max) return;
20
- this.splitValue = min + Math.random() * (max - min);
21
- const leftData = [], rightData = [];
22
- for (let row of data) {
23
- (row[this.splitAttr] < this.splitValue ? leftData : rightData).push(row);
24
- }
25
- this.left = new IsolationTree(this.depth + 1, this.maxDepth);
26
- this.right = new IsolationTree(this.depth + 1, this.maxDepth);
27
- this.left.fit(leftData);
28
- this.right.fit(rightData);
29
- }
30
-
31
- pathLength(point) {
32
- if (!this.left || !this.right) {
33
- return this.depth + c(this.size);
34
- }
35
- return point[this.splitAttr] < this.splitValue
36
- ? this.left.pathLength(point)
37
- : this.right.pathLength(point);
38
- }
39
-
40
- serialize() {
41
- return {
42
- depth: this.depth,
43
- maxDepth: this.maxDepth,
44
- splitAttr: this.splitAttr,
45
- splitValue: this.splitValue,
46
- size: this.size,
47
- left: this.left ? this.left.serialize() : null,
48
- right: this.right ? this.right.serialize() : null
49
- };
50
- }
51
-
52
- static deserialize(obj) {
53
- const tree = new IsolationTree(obj.depth, obj.maxDepth);
54
- tree.splitAttr = obj.splitAttr;
55
- tree.splitValue = obj.splitValue;
56
- tree.size = obj.size;
57
- tree.left = obj.left ? IsolationTree.deserialize(obj.left) : null;
58
- tree.right = obj.right ? IsolationTree.deserialize(obj.right) : null;
59
- return tree;
60
- }
61
- }
62
-
63
- // Average path length
64
- function c(n) {
65
- if (n <= 1) return 1;
66
- return 2 * (Math.log(n - 1) + 0.5772156649) - (2 * (n - 1) / n);
67
- }
68
-
69
- class IsolationForest {
70
- constructor({ nTrees = 100, sampleSize = 256 } = {}) {
71
- this.nTrees = nTrees;
72
- this.sampleSize = sampleSize;
73
- this.trees = [];
74
- }
75
-
76
- fit(data) {
77
- const heightLimit = Math.ceil(Math.log2(this.sampleSize));
78
- for (let i = 0; i < this.nTrees; i++) {
79
- const sample = [];
80
- for (let j = 0; j < this.sampleSize; j++) {
81
- sample.push(data[Math.floor(Math.random() * data.length)]);
82
- }
83
- const tree = new IsolationTree(0, heightLimit);
84
- tree.fit(sample);
85
- this.trees.push(tree);
86
- }
87
- }
88
-
89
- anomalyScore(point) {
90
- const pathLens = this.trees.map(t => t.pathLength(point));
91
- const avgPath = pathLens.reduce((a, b) => a + b, 0) / this.nTrees;
92
- return Math.pow(2, -avgPath / c(this.sampleSize));
93
- }
94
-
95
- isAnomaly(point, thresh = 0.5) {
96
- return this.anomalyScore(point) > thresh;
97
- }
98
-
99
- toJSON() {
100
- return {
101
- nTrees: this.nTrees,
102
- sampleSize: this.sampleSize,
103
- trees: this.trees.map(t => t.serialize())
104
- };
105
- }
106
-
107
- static fromJSON(obj) {
108
- const forest = new IsolationForest({
109
- nTrees: obj.nTrees,
110
- sampleSize: obj.sampleSize
111
- });
112
- forest.trees = obj.trees.map(IsolationTree.deserialize);
113
- return forest;
114
- }
115
- }
116
-
117
- module.exports = { IsolationForest };
1
+ class IsolationTree {
2
+ constructor(depth = 0, maxDepth = 0) {
3
+ this.depth = depth;
4
+ this.maxDepth = maxDepth;
5
+ this.left = null;
6
+ this.right = null;
7
+ this.splitAttr = null;
8
+ this.splitValue = null;
9
+ this.size = 0;
10
+ }
11
+
12
+ fit(data) {
13
+ this.size = data.length;
14
+ if (this.depth >= this.maxDepth || data.length <= 1) return;
15
+ const numFeatures = data[0].length;
16
+ this.splitAttr = Math.floor(Math.random() * numFeatures);
17
+ let vals = data.map(row => row[this.splitAttr]);
18
+ const min = Math.min(...vals), max = Math.max(...vals);
19
+ if (min === max) return;
20
+ this.splitValue = min + Math.random() * (max - min);
21
+ const leftData = [], rightData = [];
22
+ for (let row of data) {
23
+ (row[this.splitAttr] < this.splitValue ? leftData : rightData).push(row);
24
+ }
25
+ this.left = new IsolationTree(this.depth + 1, this.maxDepth);
26
+ this.right = new IsolationTree(this.depth + 1, this.maxDepth);
27
+ this.left.fit(leftData);
28
+ this.right.fit(rightData);
29
+ }
30
+
31
+ pathLength(point) {
32
+ if (!this.left || !this.right) {
33
+ return this.depth + c(this.size);
34
+ }
35
+ return point[this.splitAttr] < this.splitValue
36
+ ? this.left.pathLength(point)
37
+ : this.right.pathLength(point);
38
+ }
39
+
40
+ serialize() {
41
+ return {
42
+ depth: this.depth,
43
+ maxDepth: this.maxDepth,
44
+ splitAttr: this.splitAttr,
45
+ splitValue: this.splitValue,
46
+ size: this.size,
47
+ left: this.left ? this.left.serialize() : null,
48
+ right: this.right ? this.right.serialize() : null
49
+ };
50
+ }
51
+
52
+ static deserialize(obj) {
53
+ const tree = new IsolationTree(obj.depth, obj.maxDepth);
54
+ tree.splitAttr = obj.splitAttr;
55
+ tree.splitValue = obj.splitValue;
56
+ tree.size = obj.size;
57
+ tree.left = obj.left ? IsolationTree.deserialize(obj.left) : null;
58
+ tree.right = obj.right ? IsolationTree.deserialize(obj.right) : null;
59
+ return tree;
60
+ }
61
+ }
62
+
63
+ // Average path length
64
+ function c(n) {
65
+ if (n <= 1) return 1;
66
+ return 2 * (Math.log(n - 1) + 0.5772156649) - (2 * (n - 1) / n);
67
+ }
68
+
69
+ class IsolationForest {
70
+ constructor({ nTrees = 100, sampleSize = 256 } = {}) {
71
+ this.nTrees = nTrees;
72
+ this.sampleSize = sampleSize;
73
+ this.trees = [];
74
+ }
75
+
76
+ fit(data) {
77
+ const heightLimit = Math.ceil(Math.log2(this.sampleSize));
78
+ for (let i = 0; i < this.nTrees; i++) {
79
+ const sample = [];
80
+ for (let j = 0; j < this.sampleSize; j++) {
81
+ sample.push(data[Math.floor(Math.random() * data.length)]);
82
+ }
83
+ const tree = new IsolationTree(0, heightLimit);
84
+ tree.fit(sample);
85
+ this.trees.push(tree);
86
+ }
87
+ }
88
+
89
+ anomalyScore(point) {
90
+ const pathLens = this.trees.map(t => t.pathLength(point));
91
+ const avgPath = pathLens.reduce((a, b) => a + b, 0) / this.nTrees;
92
+ return Math.pow(2, -avgPath / c(this.sampleSize));
93
+ }
94
+
95
+ isAnomaly(point, thresh = 0.5) {
96
+ return this.anomalyScore(point) > thresh;
97
+ }
98
+
99
+ toJSON() {
100
+ return {
101
+ nTrees: this.nTrees,
102
+ sampleSize: this.sampleSize,
103
+ trees: this.trees.map(t => t.serialize())
104
+ };
105
+ }
106
+
107
+ static fromJSON(obj) {
108
+ const forest = new IsolationForest({
109
+ nTrees: obj.nTrees,
110
+ sampleSize: obj.sampleSize
111
+ });
112
+ forest.trees = obj.trees.map(IsolationTree.deserialize);
113
+ return forest;
114
+ }
115
+ }
116
+
117
+ module.exports = { IsolationForest };
@@ -1,5 +1,18 @@
1
- let staticKeywords = [];
2
- module.exports = {
3
- init(o) { staticKeywords = o.staticKeywords || []; },
4
- check(path) { return staticKeywords.find(kw => path.includes(kw)); }
5
- };
1
+ const { createKeywordMatcher } = require('./wasmAdapter');
2
+ let staticKeywords = [];
3
+ let matcherPromise = null;
4
+ module.exports = {
5
+ init(o) {
6
+ staticKeywords = o.staticKeywords || [];
7
+ matcherPromise = null;
8
+ },
9
+ check(path) { return staticKeywords.find(kw => path.includes(kw)); },
10
+ async checkAccelerated(path) {
11
+ if (!staticKeywords.length) return undefined;
12
+ if (!matcherPromise) matcherPromise = createKeywordMatcher(staticKeywords);
13
+ const pending = matcherPromise;
14
+ const matcher = await pending;
15
+ if (pending !== matcherPromise) return module.exports.check(path);
16
+ return matcher ? matcher.firstMatch(path) : module.exports.check(path);
17
+ }
18
+ };
@@ -41,6 +41,8 @@ module.exports = function createKoaMiddleware(opts = {}) {
41
41
  if (!req.path) req.path = ctx.path;
42
42
  if (!req.url) req.url = ctx.url;
43
43
  if (!req.ip) req.ip = ctx.ip;
44
+ if (req.body === undefined) req.body = ctx.request?.body;
45
+ if (req.query === undefined) req.query = ctx.query;
44
46
 
45
47
  // Don't override headers - use what's already on the raw request
46
48
  // ctx.headers is Koa's parsed version, but req.headers from Node.js has the originals
package/lib/pathRules.js CHANGED
@@ -106,11 +106,14 @@ function createRoutePlan(path, rules = [], context = {}) {
106
106
  const exempt = new Set((context.exemptMiddlewares || []).map(normalizeMiddlewareName));
107
107
  const fullyExempt = !!context.fullyExempt;
108
108
  const enabled = new Set();
109
+ const rule = getPathRule(path, rules);
110
+ const disabledValues = rule && (rule.DISABLE || rule.disable);
111
+ const disabled = new Set(Array.isArray(disabledValues) ? disabledValues.map(normalizeMiddlewareName) : []);
109
112
 
110
113
  ALL_MIDDLEWARES.forEach(name => {
111
114
  if (required.has(name)) {
112
115
  enabled.add(name);
113
- } else if (isMiddlewareDisabledForPath(path, rules, name) || fullyExempt || exempt.has(name)) {
116
+ } else if (disabled.has(name) || fullyExempt || exempt.has(name)) {
114
117
  return;
115
118
  } else {
116
119
  enabled.add(name);
@@ -122,7 +125,9 @@ function createRoutePlan(path, rules = [], context = {}) {
122
125
  return enabled.has(normalizeMiddlewareName(name));
123
126
  },
124
127
  getOverrides(sectionKey) {
125
- return getPathRuleOverrides(path, rules, sectionKey);
128
+ if (!rule || !sectionKey) return {};
129
+ const value = rule[String(sectionKey).toUpperCase()] || rule[String(sectionKey).toLowerCase()];
130
+ return value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};
126
131
  },
127
132
  enabledMiddlewares: enabled
128
133
  };
@@ -1,9 +1,9 @@
1
- // lib/redisManager.js
2
- const { createClient } = require('redis');
3
-
4
- let client = null;
5
- let isReady = false;
6
-
1
+ // lib/redisManager.js
2
+ const { createClient } = require('redis');
3
+
4
+ let client = null;
5
+ let isReady = false;
6
+
7
7
  function getRedisUrl() {
8
8
  return process.env.REDIS_URL || process.env.AIWAF_REDIS_URL;
9
9
  }
@@ -14,22 +14,22 @@ async function connect() {
14
14
  console.warn('No REDIS_URL set. Redis disabled.');
15
15
  return;
16
16
  }
17
-
18
- try {
17
+
18
+ try {
19
19
  client = createClient({ url: redisUrl });
20
20
  client.on('error', err => console.warn('Redis error:', err));
21
- await client.connect();
22
- isReady = true;
23
- console.log('Redis connected.');
24
- } catch (err) {
25
- console.warn('Redis connection failed. Falling back.');
26
- client = null;
27
- isReady = false;
28
- }
29
- }
30
-
31
- function getClient() {
32
- return isReady && client?.isOpen ? client : null;
33
- }
34
-
21
+ await client.connect();
22
+ isReady = true;
23
+ console.log('Redis connected.');
24
+ } catch (err) {
25
+ console.warn('Redis connection failed. Falling back.');
26
+ client = null;
27
+ isReady = false;
28
+ }
29
+ }
30
+
31
+ function getClient() {
32
+ return isReady && client?.isOpen ? client : null;
33
+ }
34
+
35
35
  module.exports = { connect, getClient, isReady: () => isReady };
@@ -0,0 +1,61 @@
1
+ // Deterministic, bounded signatures. Findings never include request values.
2
+ const RULES = [
3
+ ['sql_union_select', /\bunion\s+(?:all\s+)?select\b/i],
4
+ ['sql_boolean_tautology', /['"`]\s*(?:or|and)\s+(?:true\b|\d+\s*=\s*\d+|['"][^'"\r\n]{0,80}['"]\s*=\s*['"])/i],
5
+ ['sql_quote_comment', /['"`]\s*(?:--|#)/],
6
+ ['sql_stacked_statement', /;\s*(?:drop\s+table|delete\s+from|insert\s+into|update\s+\w+\s+set)\b/i]
7
+ ];
8
+
9
+ function createInspector(options = {}) {
10
+ const mode = String(options.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
11
+ if (!['block', 'monitor', 'off'].includes(mode)) throw new Error('Invalid AIWAF_SQL_INJECTION_MODE');
12
+ const maxBytes = Number(options.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
13
+ if (!Number.isInteger(maxBytes) || maxBytes < 1 || maxBytes > 1048576) throw new Error('AIWAF_PAYLOAD_MAX_BYTES must be 1..1048576');
14
+ return function inspect(req) {
15
+ if (mode === 'off') return null;
16
+ const stack = [[req.body, 0], [req.query, 0]];
17
+ // Also handles raw Node requests whose framework has not populated query.
18
+ const query = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
19
+ if (query) stack.push([query, 0]);
20
+ let bytes = 0, nodes = 0;
21
+ const seen = new Set();
22
+ const finding = (rule, status = 403) => ({ rule, status, mode });
23
+ while (stack.length) {
24
+ const [value, depth] = stack.pop();
25
+ if (++nodes > 4096 || depth > 16) return finding('payload_inspection_limit', 413);
26
+ if (value === undefined || value === null) continue;
27
+ // Frameworks may expose an unparsed upload stream; never traverse or consume it.
28
+ if (typeof value.pipe === 'function') continue;
29
+ if (Buffer.isBuffer(value)) {
30
+ if (value.length + bytes > maxBytes) return finding('payload_inspection_limit', 413);
31
+ stack.push([value.toString('utf8'), depth + 1]);
32
+ } else if (typeof value === 'object') {
33
+ if (seen.has(value)) return finding('payload_inspection_limit', 413);
34
+ seen.add(value);
35
+ for (const [key, item] of Object.entries(value)) {
36
+ stack.push([key, depth + 1], [item, depth + 1]);
37
+ if (stack.length > 4096) return finding('payload_inspection_limit', 413);
38
+ }
39
+ } else if (typeof value === 'string') {
40
+ bytes += Buffer.byteLength(value);
41
+ if (bytes > maxBytes) return finding('payload_inspection_limit', 413);
42
+ let normalized = value;
43
+ for (let round = 0; round < 2; round++) {
44
+ try { normalized = decodeURIComponent(normalized.replace(/\+/g, ' ')); } catch (_) { break; }
45
+ }
46
+ // Decode serialized JSON escapes before signature matching.
47
+ if (/^\s*[\[{]/.test(normalized)) {
48
+ try {
49
+ const parsed = JSON.parse(normalized);
50
+ stack.push([parsed, depth + 1]);
51
+ } catch (_) { /* Non-JSON strings still receive signature checks. */ }
52
+ }
53
+ normalized = normalized.replace(/\/\*[\s\S]*?\*\//g, ' ');
54
+ for (const [rule, pattern] of RULES) if (pattern.test(normalized)) return finding(rule);
55
+ }
56
+ }
57
+ return null;
58
+ };
59
+ }
60
+
61
+ module.exports = { createInspector };
@@ -0,0 +1,98 @@
1
+ const { extractWasmTrainingFeatures, extractWasmRawTrainingFeatures } = require('./wasmAdapter');
2
+
3
+ function modelFeaturesFromRust(features, expectedLength) {
4
+ if (!Array.isArray(features) || features.length !== expectedLength
5
+ || !features.every(rec => rec && Number.isFinite(Number(rec.burst_count)))) return null;
6
+ return features.map(rec => [
7
+ rec.path_len, rec.kw_hits, rec.status_idx, rec.resp_time, rec.burst_count, rec.total_404
8
+ ]);
9
+ }
10
+
11
+ function lowerBound(values, target) {
12
+ let left = 0;
13
+ let right = values.length;
14
+ while (left < right) {
15
+ const mid = (left + right) >>> 1;
16
+ if (values[mid] < target) left = mid + 1;
17
+ else right = mid;
18
+ }
19
+ return left;
20
+ }
21
+
22
+ function upperBound(values, target) {
23
+ let left = 0;
24
+ let right = values.length;
25
+ while (left < right) {
26
+ const mid = (left + right) >>> 1;
27
+ if (values[mid] <= target) left = mid + 1;
28
+ else right = mid;
29
+ }
30
+ return left;
31
+ }
32
+
33
+ async function calculateTrainingFeatures(parsedRequests, staticKeywords, statusIndices) {
34
+ const keywords = staticKeywords || [];
35
+ const statuses = statusIndices || [];
36
+ // Direct JS-object parsing currently costs more than the prepared-record path
37
+ // on typical Node workloads; keep it opt-in until workload benchmarks improve.
38
+ if (process.env.AIWAF_EXPERIMENTAL_WASM_RAW_TRAINING === '1'
39
+ && parsedRequests.length && keywords.every(kw => kw === String(kw).toLowerCase())
40
+ && typeof extractWasmRawTrainingFeatures === 'function') {
41
+ const rawFeatures = await extractWasmRawTrainingFeatures(parsedRequests, keywords, statuses);
42
+ const mapped = modelFeaturesFromRust(rawFeatures, parsedRequests.length);
43
+ if (mapped) return mapped;
44
+ }
45
+ const ip404Counts = new Map();
46
+ const timestampsByIp = new Map();
47
+
48
+ for (const req of parsedRequests) {
49
+ if (!timestampsByIp.has(req.ip)) timestampsByIp.set(req.ip, []);
50
+ const timestamp = req.timestamp instanceof Date
51
+ ? req.timestamp.getTime()
52
+ : new Date(req.timestamp).getTime();
53
+ if (Number.isFinite(timestamp)) timestampsByIp.get(req.ip).push(timestamp);
54
+ if (req.status === '404') {
55
+ ip404Counts.set(req.ip, (ip404Counts.get(req.ip) || 0) + 1);
56
+ }
57
+ }
58
+ for (const timestamps of timestampsByIp.values()) timestamps.sort((a, b) => a - b);
59
+
60
+ // JS's persisted model format uses statusIdx before responseTime. Preserve that order.
61
+ const records = parsedRequests.map(req => {
62
+ const path = String(req.path || '');
63
+ const timestampMs = req.timestamp instanceof Date
64
+ ? req.timestamp.getTime()
65
+ : new Date(req.timestamp).getTime();
66
+ return {
67
+ ip: String(req.ip),
68
+ path_lower: path.toLowerCase(),
69
+ path_len: path.length,
70
+ timestamp: timestampMs / 1000,
71
+ response_time: Number(req.responseTime),
72
+ status_idx: statuses.indexOf(req.status),
73
+ kw_check: true,
74
+ total_404: ip404Counts.get(req.ip) || 0
75
+ };
76
+ });
77
+
78
+ const canUseRust = records.every(rec => Number.isFinite(rec.timestamp) && Number.isFinite(rec.response_time))
79
+ && keywords.every(kw => kw === String(kw).toLowerCase());
80
+ if (canUseRust && records.length > 0) {
81
+ const rustFeatures = await extractWasmTrainingFeatures(records, keywords);
82
+ const mapped = modelFeaturesFromRust(rustFeatures, records.length);
83
+ if (mapped) return mapped;
84
+ }
85
+
86
+ return parsedRequests.map((req, index) => {
87
+ const path = String(req.path || '');
88
+ const timestampMs = records[index].timestamp * 1000;
89
+ const times = timestampsByIp.get(req.ip) || [];
90
+ const burst = Number.isFinite(timestampMs)
91
+ ? upperBound(times, timestampMs + 10000) - lowerBound(times, timestampMs - 10000)
92
+ : 0;
93
+ const kwHits = keywords.reduce((sum, kw) => sum + (path.toLowerCase().includes(kw) ? 1 : 0), 0);
94
+ return [path.length, kwHits, statuses.indexOf(req.status), req.responseTime, burst, ip404Counts.get(req.ip) || 0];
95
+ });
96
+ }
97
+
98
+ module.exports = { calculateTrainingFeatures };
@@ -1,4 +1,5 @@
1
1
  const rateLimiter = require('./rateLimiter');
2
+ const { createInspector } = require('./sqlInjection');
2
3
  const blacklistManager = require('./blacklistManager');
3
4
  const keywordDetector = require('./keywordDetector');
4
5
  const dynamicKeyword = require('./dynamicKeyword');
@@ -129,6 +130,7 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
129
130
 
130
131
  module.exports = function aiwaf(rawOpts = {}) {
131
132
  let opts = normalizeSettings(rawOpts);
133
+ const inspectSql = createInspector(opts);
132
134
  opts.AIWAF_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_MIDDLEWARES);
133
135
  opts.AIWAF_DISABLE_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_DISABLE_MIDDLEWARES) || [];
134
136
  const pathRules = getEffectivePathRules(opts.AIWAF_PATH_RULES, { manifestPath: opts.AIWAF_PATH_MANIFEST });
@@ -174,7 +176,20 @@ module.exports = function aiwaf(rawOpts = {}) {
174
176
  ]).catch(() => {});
175
177
  }
176
178
 
177
- return async (req, res, next) => {
179
+ const inspectPayload = async req => {
180
+ const path = String(req.path || req.url || '/').split('?')[0].toLowerCase();
181
+ const ip = req.headers?.['x-forwarded-for']?.split(',')[0].trim() || req.ip;
182
+ const plan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
183
+ if (!enabledMiddlewares.has('ip_keyword_block') || !plan.shouldApply('ip_keyword_block')
184
+ || await exemptions.isExemptRequest(ip, path)) return null;
185
+ const finding = inspectSql(req);
186
+ if (finding?.mode === 'monitor') {
187
+ (opts.logger || console).warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: finding.mode });
188
+ return null;
189
+ }
190
+ return finding;
191
+ };
192
+ const middleware = async (req, res, next) => {
178
193
  const ipHdr = req.headers['x-forwarded-for'];
179
194
  const ip = ipHdr ? ipHdr.split(',')[0].trim() : req.ip;
180
195
  const path = String(req.path || req.url || '/').toLowerCase();
@@ -258,6 +273,9 @@ module.exports = function aiwaf(rawOpts = {}) {
258
273
  return deny(403, 'blocked', 'blacklist');
259
274
  }
260
275
 
276
+ const payloadFinding = await inspectPayload(req);
277
+ if (payloadFinding) return deny(payloadFinding.status, payloadFinding.rule, payloadFinding.rule);
278
+
261
279
  if (shouldApply('header_validation')) {
262
280
  const headerReason = headerValidation.validate(req);
263
281
  if (headerReason) {
@@ -387,7 +405,7 @@ module.exports = function aiwaf(rawOpts = {}) {
387
405
  }
388
406
 
389
407
  if (shouldApply('ip_keyword_block')) {
390
- const staticMatch = keywordDetector.check(path);
408
+ const staticMatch = await keywordDetector.checkAccelerated(path);
391
409
  if (staticMatch && !exemptions.shouldSkipKeyword(staticMatch, path)) {
392
410
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
393
411
  console.error(`[AIWAF-BLOCK-STATIC-KW] match=${staticMatch}`);
@@ -396,7 +414,7 @@ module.exports = function aiwaf(rawOpts = {}) {
396
414
  return deny(403, 'blocked', `static:${staticMatch}`);
397
415
  }
398
416
 
399
- const dynamicMatch = dynamicKeyword.check(path);
417
+ const dynamicMatch = await dynamicKeyword.checkAccelerated(path);
400
418
  if (dynamicMatch && !exemptions.shouldSkipKeyword(dynamicMatch, path)) {
401
419
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
402
420
  console.error(`[AIWAF-BLOCK-DYNAMIC-KW] match=${dynamicMatch}`);
@@ -436,7 +454,7 @@ module.exports = function aiwaf(rawOpts = {}) {
436
454
  }))
437
455
  .filter(entry => now - entry.timestamp <= 5 * 60 * 1000);
438
456
 
439
- const stats = anomalyDetector.analyzeRecentBehavior(recentData);
457
+ const stats = await anomalyDetector.analyzeRecentBehaviorAccelerated(recentData);
440
458
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
441
459
  console.error(`[AIWAF-ANOMALY-STATS] should_block=${stats?.should_block}`);
442
460
  }
@@ -464,4 +482,6 @@ module.exports = function aiwaf(rawOpts = {}) {
464
482
 
465
483
  next();
466
484
  };
485
+ middleware.inspectPayload = inspectPayload;
486
+ return middleware;
467
487
  };