aiwaf 1.0.1 → 1.0.2

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/LICENSE CHANGED
@@ -1,21 +1,22 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Aayush Gauba
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Aayush Gauba
4
+ Copyright (c) 2026 AIWAF
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -9,16 +9,17 @@ with rate limiting, anomaly detection, honeypots, UUID tamper protection, smart
9
9
  keyword learning, file-extension probing detection, exempt path/IP awareness,
10
10
  and scheduled retraining.
11
11
 
12
- This monorepo contains both published packages:
12
+ This monorepo contains three independently published packages:
13
13
 
14
14
  - `py/aiwaf/` and the root Python packaging files publish `aiwaf` to PyPI.
15
15
  - `js/` publishes `aiwaf` to npm and supports Express, Fastify, Hapi, Koa, Next.js, NestJS, AdonisJS, and Sails.
16
+ - `rust/` publishes `aiwaf-rust` to PyPI as a separate package.
16
17
 
17
18
  Install the JavaScript package with `npm install aiwaf`. Its usage, configuration, framework adapters, and operational commands are documented in [JavaScript Package](#javascript-package-aiwaf).
18
19
 
19
- For local JavaScript development, run `npm ci` and `npm test` from `js/`. Releases are independent: push a `python-v*` tag (for example, `python-v1.0.8`) to publish the Python package to PyPI, or push a `js-v*` tag (for example, `js-v1.0.1`) to publish `aiwaf` to npm. Both publish workflows can also be started manually from GitHub Actions.
20
+ For local JavaScript development, run `npm ci` and `npm test` from `js/`. Releases are independent: push a `python-v*` tag (for example, `python-v1.0.8`) to publish the Python package to PyPI, a `js-v*` tag (for example, `js-v1.0.1`) to publish `aiwaf` to npm, or a `rust-v*` tag (for example, `rust-v0.2.1`) to publish `aiwaf-rust` to PyPI. The publish workflows can also be started manually from GitHub Actions.
20
21
 
21
- Run the complete monorepo test suite with `python aiwaf_test.py`. Use `--python-only` or `--js-only` when working on one package.
22
+ Run the Python and JavaScript test suites with `python aiwaf_test.py`. Use `--python-only` or `--js-only` when working on one package. For the Rust core, run `cargo test --manifest-path rust/Cargo.toml --locked -p aiwaf_core`.
22
23
 
23
24
  ## Latest Enhancements
24
25
 
@@ -1,5 +1,10 @@
1
1
  const { IsolationForest } = require('./isolationForest');
2
- const { createIsolationForest, getWasmStatus } = require('./wasmAdapter');
2
+ const {
3
+ createIsolationForest,
4
+ createIsolationForestFromJSON,
5
+ getWasmStatus,
6
+ analyzeRecentBehavior: analyzeRecentBehaviorWasm
7
+ } = require('./wasmAdapter');
3
8
  const modelStore = require('./modelStore');
4
9
  const requestLogStore = require('./requestLogStore');
5
10
  const { STATIC_KW } = require('./featureUtils');
@@ -23,6 +28,15 @@ async function loadModel(opts = {}) {
23
28
  const modelData = await modelStore.load(opts);
24
29
  if (!modelData) return;
25
30
 
31
+ if (modelData.model_type === 'aiwaf_wasm.IsolationForest' && modelData.model_state) {
32
+ const restored = await createIsolationForestFromJSON(modelData.model_state);
33
+ if (!restored.__aiwafWasm) throw new Error('WASM model cannot be restored without aiwaf-wasm');
34
+ model = restored;
35
+ modelMetadata = modelData.metadata || null;
36
+ trained = true;
37
+ return;
38
+ }
39
+
26
40
  if (modelData.metadata) {
27
41
  modelMetadata = modelData.metadata;
28
42
  model = IsolationForest.fromJSON(modelData);
@@ -70,6 +84,28 @@ function analyzeRecentBehavior(recentData = []) {
70
84
  const recentKwHits = [];
71
85
  let recent404s = 0;
72
86
  const recentBurstCounts = [];
87
+ const timestamps = recentData.map(entry => Number(entry.timestamp || 0)).sort((a, b) => a - b);
88
+
89
+ const lowerBound = target => {
90
+ let left = 0;
91
+ let right = timestamps.length;
92
+ while (left < right) {
93
+ const mid = (left + right) >>> 1;
94
+ if (timestamps[mid] < target) left = mid + 1;
95
+ else right = mid;
96
+ }
97
+ return left;
98
+ };
99
+ const upperBound = target => {
100
+ let left = 0;
101
+ let right = timestamps.length;
102
+ while (left < right) {
103
+ const mid = (left + right) >>> 1;
104
+ if (timestamps[mid] <= target) left = mid + 1;
105
+ else right = mid;
106
+ }
107
+ return left;
108
+ };
73
109
 
74
110
  for (const entry of recentData) {
75
111
  const entryTime = entry.timestamp || 0;
@@ -89,7 +125,7 @@ function analyzeRecentBehavior(recentData = []) {
89
125
  recent404s += 1;
90
126
  }
91
127
 
92
- const entryBurst = recentData.filter(item => Math.abs(entryTime - (item.timestamp || 0)) <= 10000).length;
128
+ const entryBurst = upperBound(entryTime + 10000) - lowerBound(entryTime - 10000);
93
129
  recentBurstCounts.push(entryBurst);
94
130
  }
95
131
 
@@ -128,6 +164,28 @@ function analyzeRecentBehavior(recentData = []) {
128
164
  };
129
165
  }
130
166
 
167
+ async function analyzeRecentBehaviorAccelerated(recentData = []) {
168
+ // Older aiwaf-wasm releases classify these ordinary discovery paths as scans.
169
+ // Also keep the JS semantics for malformed timestamps or non-numeric statuses.
170
+ const safeForWasm = recentData.every(entry =>
171
+ typeof entry.status === 'number'
172
+ && Number.isFinite(entry.timestamp)
173
+ && !/robots\.txt|sitemap\.xml/.test(String(entry.path || '').toLowerCase())
174
+ );
175
+ if (recentData.length > 0 && safeForWasm) {
176
+ const entries = recentData.map(entry => ({
177
+ ...entry,
178
+ timestamp_ms: Number(entry.timestamp || 0),
179
+ kw_check: !exemptions.shouldSkipKeyword('', String(entry.path || ''))
180
+ }));
181
+ const stats = await analyzeRecentBehaviorWasm(entries, STATIC_KW);
182
+ if (stats && typeof stats.should_block === 'boolean' && Number.isFinite(Number(stats.avg_burst))) {
183
+ return stats;
184
+ }
185
+ }
186
+ return analyzeRecentBehavior(recentData);
187
+ }
188
+
131
189
  module.exports = {
132
190
  async init(opts = {}) {
133
191
  minAiLogs = Number.isFinite(Number(opts.AIWAF_MIN_AI_LOGS))
@@ -184,6 +242,7 @@ module.exports = {
184
242
  },
185
243
 
186
244
  analyzeRecentBehavior,
245
+ analyzeRecentBehaviorAccelerated,
187
246
  isScanningPath,
188
247
 
189
248
  maybeLearnKeyword(path, statusCode, opts = {}) {
@@ -1,7 +1,17 @@
1
1
  // lib/dynamicKeyword.js
2
2
  const dynamicKeywordStore = require('./dynamicKeywordStore');
3
+ const { createKeywordMatcher } = require('./wasmAdapter');
3
4
 
4
5
  let opts, counts;
6
+ let activeKeywords = [];
7
+ let matcherPromise = null;
8
+
9
+ function refreshActiveKeywords() {
10
+ activeKeywords = Object.entries(counts)
11
+ .filter(([, count]) => count > opts.dynamicTopN)
12
+ .map(([keyword]) => keyword);
13
+ matcherPromise = null;
14
+ }
5
15
 
6
16
  module.exports = {
7
17
  init(o = {}) {
@@ -9,11 +19,13 @@ module.exports = {
9
19
  const topN = o.dynamicTopN ?? o.DYNAMIC_TOP_N ?? 10;
10
20
  opts = { dynamicTopN: topN };
11
21
  counts = {};
22
+ refreshActiveKeywords();
12
23
  dynamicKeywordStore.initialize().catch(() => {});
13
24
  dynamicKeywordStore.list(2000).then(rows => {
14
25
  rows.forEach(row => {
15
26
  counts[row.keyword] = Number(row.count || 0);
16
27
  });
28
+ refreshActiveKeywords();
17
29
  }).catch(() => {});
18
30
  },
19
31
 
@@ -21,7 +33,9 @@ module.exports = {
21
33
  segments.forEach(s => {
22
34
  const key = String(s).toLowerCase();
23
35
  if (!key) return;
36
+ const prior = counts[key] || 0;
24
37
  counts[key] = (counts[key] || 0) + 1;
38
+ if (prior <= opts.dynamicTopN && counts[key] > opts.dynamicTopN) refreshActiveKeywords();
25
39
  dynamicKeywordStore.increment(key).catch(() => {});
26
40
  });
27
41
  },
@@ -30,13 +44,20 @@ module.exports = {
30
44
  const segments = String(path || '').split('/').filter(s => s.length > 3);
31
45
  module.exports.learnSegments(segments);
32
46
  },
33
-
34
- check(path) {
35
- // only block segments whose count exceeds the threshold
47
+
48
+ check(path) {
49
+ // only block segments whose count exceeds the threshold
50
+ const pathLower = String(path || '').toLowerCase();
51
+ return activeKeywords.find(keyword => pathLower.includes(keyword)) || null;
52
+ },
53
+
54
+ async checkAccelerated(path) {
55
+ if (!activeKeywords.length) return null;
36
56
  const pathLower = String(path || '').toLowerCase();
37
- return Object.entries(counts)
38
- .find(([seg, cnt]) => cnt > opts.dynamicTopN && pathLower.includes(seg))
39
- ?. [0] // return the segment string
40
- || null;
57
+ if (!matcherPromise) matcherPromise = createKeywordMatcher(activeKeywords);
58
+ const pending = matcherPromise;
59
+ const matcher = await pending;
60
+ if (pending !== matcherPromise) return module.exports.check(path);
61
+ return matcher ? matcher.firstMatch(pathLower) : module.exports.check(path);
41
62
  }
42
63
  };
@@ -1,15 +1,15 @@
1
1
  const STATIC_KW = ['.php', '.xmlrpc', 'wp-', '.env', '.git', '.bak', 'shell'];
2
2
  const STATUS_IDX = ['200', '403', '404', '500'];
3
- const defaultCache = new Map();
4
- const { getClient } = require('./redisClient');
5
-
3
+ const defaultCache = new Map();
4
+ const { getClient } = require('./redisClient');
5
+
6
6
  let customCache = null;
7
7
  let cleanupInterval = null;
8
-
9
- // In-memory tracking for burst and 404 calculations
10
- const ipRequestHistory = new Map(); // IP -> array of timestamps
11
- const ip404Counts = new Map(); // IP -> count of 404s
12
-
8
+
9
+ // In-memory tracking for burst and 404 calculations
10
+ const ipRequestHistory = new Map(); // IP -> array of timestamps
11
+ const ip404Counts = new Map(); // IP -> count of 404s
12
+
13
13
  function init(opts = {}) {
14
14
  customCache = opts.cache || null;
15
15
 
@@ -18,15 +18,15 @@ function init(opts = {}) {
18
18
  // Clean up old entries every 5 minutes
19
19
  cleanupInterval = setInterval(() => {
20
20
  const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
21
-
22
- for (const [ip, timestamps] of ipRequestHistory.entries()) {
23
- const recentTimestamps = timestamps.filter(t => t > fiveMinutesAgo);
24
- if (recentTimestamps.length > 0) {
25
- ipRequestHistory.set(ip, recentTimestamps);
26
- } else {
27
- ipRequestHistory.delete(ip);
28
- }
29
- }
21
+
22
+ for (const [ip, timestamps] of ipRequestHistory.entries()) {
23
+ const recentTimestamps = timestamps.filter(t => t > fiveMinutesAgo);
24
+ if (recentTimestamps.length > 0) {
25
+ ipRequestHistory.set(ip, recentTimestamps);
26
+ } else {
27
+ ipRequestHistory.delete(ip);
28
+ }
29
+ }
30
30
  }, 5 * 60 * 1000);
31
31
  if (typeof cleanupInterval.unref === 'function') {
32
32
  cleanupInterval.unref();
@@ -41,134 +41,134 @@ function cleanup() {
41
41
  ipRequestHistory.clear();
42
42
  ip404Counts.clear();
43
43
  }
44
-
45
- function recordRequest(ip, statusCode) {
46
- const now = Date.now();
47
-
48
- // Record timestamp for burst calculation
49
- if (!ipRequestHistory.has(ip)) {
50
- ipRequestHistory.set(ip, []);
51
- }
52
- ipRequestHistory.get(ip).push(now);
53
-
54
- // Keep only last 100 requests per IP to prevent memory bloat
55
- const history = ipRequestHistory.get(ip);
56
- if (history.length > 100) {
57
- history.splice(0, history.length - 100);
58
- }
59
-
60
- // Track 404 counts
61
- if (statusCode === 404) {
62
- ip404Counts.set(ip, (ip404Counts.get(ip) || 0) + 1);
63
- }
64
- }
65
-
66
- function calculateBurstCount(ip) {
67
- if (!ipRequestHistory.has(ip)) return 0;
68
-
69
- const now = Date.now();
70
- const tenSecondsAgo = now - 10000; // 10 seconds
71
- const recentRequests = ipRequestHistory.get(ip).filter(t => t > tenSecondsAgo);
72
-
73
- return recentRequests.length;
74
- }
75
-
76
- function get404Count(ip) {
77
- return ip404Counts.get(ip) || 0;
78
- }
79
-
80
- // Helper to mark request start time for response time calculation
81
- function markRequestStart(req) {
82
- req._startTime = Date.now();
83
- }
84
-
85
- // Helper to calculate response time from marked start
86
- function getResponseTime(req) {
87
- if (req._startTime) {
88
- return Date.now() - req._startTime;
89
- }
90
- return 0;
91
- }
92
-
93
- async function extractFeatures(req, res = null) {
44
+
45
+ function recordRequest(ip, statusCode) {
46
+ const now = Date.now();
47
+
48
+ // Record timestamp for burst calculation
49
+ if (!ipRequestHistory.has(ip)) {
50
+ ipRequestHistory.set(ip, []);
51
+ }
52
+ ipRequestHistory.get(ip).push(now);
53
+
54
+ // Keep only last 100 requests per IP to prevent memory bloat
55
+ const history = ipRequestHistory.get(ip);
56
+ if (history.length > 100) {
57
+ history.splice(0, history.length - 100);
58
+ }
59
+
60
+ // Track 404 counts
61
+ if (statusCode === 404) {
62
+ ip404Counts.set(ip, (ip404Counts.get(ip) || 0) + 1);
63
+ }
64
+ }
65
+
66
+ function calculateBurstCount(ip) {
67
+ if (!ipRequestHistory.has(ip)) return 0;
68
+
69
+ const now = Date.now();
70
+ const tenSecondsAgo = now - 10000; // 10 seconds
71
+ const recentRequests = ipRequestHistory.get(ip).filter(t => t > tenSecondsAgo);
72
+
73
+ return recentRequests.length;
74
+ }
75
+
76
+ function get404Count(ip) {
77
+ return ip404Counts.get(ip) || 0;
78
+ }
79
+
80
+ // Helper to mark request start time for response time calculation
81
+ function markRequestStart(req) {
82
+ req._startTime = Date.now();
83
+ }
84
+
85
+ // Helper to calculate response time from marked start
86
+ function getResponseTime(req) {
87
+ if (req._startTime) {
88
+ return Date.now() - req._startTime;
89
+ }
90
+ return 0;
91
+ }
92
+
93
+ async function extractFeatures(req, res = null) {
94
94
  const uri = req.path || req.url;
95
95
  const ip = req.ip || req.socket?.remoteAddress || req.connection?.remoteAddress || 'unknown';
96
-
97
- // Get status code from response if available, otherwise default to 200
98
- let statusCode = 200;
99
- if (res && res.statusCode) {
100
- statusCode = res.statusCode;
101
- } else if (req.res && req.res.statusCode) {
102
- statusCode = req.res.statusCode;
103
- }
104
-
105
- // Record this request for burst/404 tracking
106
- recordRequest(ip, statusCode);
107
-
108
- const redis = getClient();
109
- const cacheKey = `features:${uri.toLowerCase()}:${ip}`;
110
-
111
- // Custom cache logic
112
- if (customCache?.get && customCache?.set) {
113
- try {
114
- const cached = await customCache.get(cacheKey);
115
- if (cached) return cached;
116
- } catch (err) {
117
- console.warn('Custom cache read failed:', err.message);
118
- }
119
- }
120
-
121
- // Redis check
122
- if (redis) {
123
- try {
124
- const cached = await redis.get(cacheKey);
125
- if (cached) return JSON.parse(cached);
126
- } catch (err) {
96
+
97
+ // Get status code from response if available, otherwise default to 200
98
+ let statusCode = 200;
99
+ if (res && res.statusCode) {
100
+ statusCode = res.statusCode;
101
+ } else if (req.res && req.res.statusCode) {
102
+ statusCode = req.res.statusCode;
103
+ }
104
+
105
+ // Record this request for burst/404 tracking
106
+ recordRequest(ip, statusCode);
107
+
108
+ const redis = getClient();
109
+ const cacheKey = `features:${uri.toLowerCase()}:${ip}`;
110
+
111
+ // Custom cache logic
112
+ if (customCache?.get && customCache?.set) {
113
+ try {
114
+ const cached = await customCache.get(cacheKey);
115
+ if (cached) return cached;
116
+ } catch (err) {
117
+ console.warn('Custom cache read failed:', err.message);
118
+ }
119
+ }
120
+
121
+ // Redis check
122
+ if (redis) {
123
+ try {
124
+ const cached = await redis.get(cacheKey);
125
+ if (cached) return JSON.parse(cached);
126
+ } catch (err) {
127
127
  console.warn('Redis read failed. Falling back.', err.message);
128
- }
129
- }
130
-
131
- // Compute features
132
- const pathLen = uri.length;
133
- const kwHits = STATIC_KW.reduce((count, kw) => count + (uri.toLowerCase().includes(kw) ? 1 : 0), 0);
134
- const statusIdx = STATUS_IDX.indexOf(String(statusCode));
135
-
136
- // Response time - try multiple sources
137
- let responseTime = 0;
138
- if (req.headers && req.headers['x-response-time']) {
139
- responseTime = parseFloat(req.headers['x-response-time']);
140
- } else if (req.responseTime) {
141
- responseTime = req.responseTime;
142
- } else if (req._startTime) {
143
- responseTime = Date.now() - req._startTime;
144
- }
145
-
146
- // Calculate real burst and 404 counts
147
- const burst = calculateBurstCount(ip);
148
- const total404 = get404Count(ip);
149
-
150
- const features = [pathLen, kwHits, statusIdx, responseTime, burst, total404];
151
-
152
- // Write back to cache with shorter TTL for dynamic features
153
- const ttl = 30; // 30 seconds TTL
154
-
155
- if (customCache?.set) {
156
- try {
157
- await customCache.set(cacheKey, features, ttl);
158
- } catch (err) {
159
- console.warn('Custom cache write failed:', err.message);
160
- }
161
- } else if (redis) {
162
- try {
163
- await redis.set(cacheKey, JSON.stringify(features), { EX: ttl });
164
- } catch (err) {
128
+ }
129
+ }
130
+
131
+ // Compute features
132
+ const pathLen = uri.length;
133
+ const kwHits = STATIC_KW.reduce((count, kw) => count + (uri.toLowerCase().includes(kw) ? 1 : 0), 0);
134
+ const statusIdx = STATUS_IDX.indexOf(String(statusCode));
135
+
136
+ // Response time - try multiple sources
137
+ let responseTime = 0;
138
+ if (req.headers && req.headers['x-response-time']) {
139
+ responseTime = parseFloat(req.headers['x-response-time']);
140
+ } else if (req.responseTime) {
141
+ responseTime = req.responseTime;
142
+ } else if (req._startTime) {
143
+ responseTime = Date.now() - req._startTime;
144
+ }
145
+
146
+ // Calculate real burst and 404 counts
147
+ const burst = calculateBurstCount(ip);
148
+ const total404 = get404Count(ip);
149
+
150
+ const features = [pathLen, kwHits, statusIdx, responseTime, burst, total404];
151
+
152
+ // Write back to cache with shorter TTL for dynamic features
153
+ const ttl = 30; // 30 seconds TTL
154
+
155
+ if (customCache?.set) {
156
+ try {
157
+ await customCache.set(cacheKey, features, ttl);
158
+ } catch (err) {
159
+ console.warn('Custom cache write failed:', err.message);
160
+ }
161
+ } else if (redis) {
162
+ try {
163
+ await redis.set(cacheKey, JSON.stringify(features), { EX: ttl });
164
+ } catch (err) {
165
165
  console.warn('Redis write failed. Ignoring.', err.message);
166
- }
167
- }
168
-
169
- return features;
170
- }
171
-
166
+ }
167
+ }
168
+
169
+ return features;
170
+ }
171
+
172
172
  module.exports = {
173
173
  extractFeatures,
174
174
  init,
@@ -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
+ };
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,85 @@
1
+ const { extractWasmTrainingFeatures } = require('./wasmAdapter');
2
+
3
+ function lowerBound(values, target) {
4
+ let left = 0;
5
+ let right = values.length;
6
+ while (left < right) {
7
+ const mid = (left + right) >>> 1;
8
+ if (values[mid] < target) left = mid + 1;
9
+ else right = mid;
10
+ }
11
+ return left;
12
+ }
13
+
14
+ function upperBound(values, target) {
15
+ let left = 0;
16
+ let right = values.length;
17
+ while (left < right) {
18
+ const mid = (left + right) >>> 1;
19
+ if (values[mid] <= target) left = mid + 1;
20
+ else right = mid;
21
+ }
22
+ return left;
23
+ }
24
+
25
+ async function calculateTrainingFeatures(parsedRequests, staticKeywords, statusIndices) {
26
+ const keywords = staticKeywords || [];
27
+ const statuses = statusIndices || [];
28
+ const ip404Counts = new Map();
29
+ const timestampsByIp = new Map();
30
+
31
+ for (const req of parsedRequests) {
32
+ if (!timestampsByIp.has(req.ip)) timestampsByIp.set(req.ip, []);
33
+ const timestamp = req.timestamp instanceof Date
34
+ ? req.timestamp.getTime()
35
+ : new Date(req.timestamp).getTime();
36
+ if (Number.isFinite(timestamp)) timestampsByIp.get(req.ip).push(timestamp);
37
+ if (req.status === '404') {
38
+ ip404Counts.set(req.ip, (ip404Counts.get(req.ip) || 0) + 1);
39
+ }
40
+ }
41
+ for (const timestamps of timestampsByIp.values()) timestamps.sort((a, b) => a - b);
42
+
43
+ // JS's persisted model format uses statusIdx before responseTime. Preserve that order.
44
+ const records = parsedRequests.map(req => {
45
+ const path = String(req.path || '');
46
+ const timestampMs = req.timestamp instanceof Date
47
+ ? req.timestamp.getTime()
48
+ : new Date(req.timestamp).getTime();
49
+ return {
50
+ ip: String(req.ip),
51
+ path_lower: path.toLowerCase(),
52
+ path_len: path.length,
53
+ timestamp: timestampMs / 1000,
54
+ response_time: Number(req.responseTime),
55
+ status_idx: statuses.indexOf(req.status),
56
+ kw_check: true,
57
+ total_404: ip404Counts.get(req.ip) || 0
58
+ };
59
+ });
60
+
61
+ const canUseRust = records.every(rec => Number.isFinite(rec.timestamp) && Number.isFinite(rec.response_time))
62
+ && keywords.every(kw => kw === String(kw).toLowerCase());
63
+ if (canUseRust && records.length > 0) {
64
+ const rustFeatures = await extractWasmTrainingFeatures(records, keywords);
65
+ if (Array.isArray(rustFeatures) && rustFeatures.length === records.length
66
+ && rustFeatures.every(rec => rec && Number.isFinite(Number(rec.burst_count)))) {
67
+ return rustFeatures.map(rec => [
68
+ rec.path_len, rec.kw_hits, rec.status_idx, rec.resp_time, rec.burst_count, rec.total_404
69
+ ]);
70
+ }
71
+ }
72
+
73
+ return parsedRequests.map((req, index) => {
74
+ const path = String(req.path || '');
75
+ const timestampMs = records[index].timestamp * 1000;
76
+ const times = timestampsByIp.get(req.ip) || [];
77
+ const burst = Number.isFinite(timestampMs)
78
+ ? upperBound(times, timestampMs + 10000) - lowerBound(times, timestampMs - 10000)
79
+ : 0;
80
+ const kwHits = keywords.reduce((sum, kw) => sum + (path.toLowerCase().includes(kw) ? 1 : 0), 0);
81
+ return [path.length, kwHits, statuses.indexOf(req.status), req.responseTime, burst, ip404Counts.get(req.ip) || 0];
82
+ });
83
+ }
84
+
85
+ module.exports = { calculateTrainingFeatures };
@@ -387,7 +387,7 @@ module.exports = function aiwaf(rawOpts = {}) {
387
387
  }
388
388
 
389
389
  if (shouldApply('ip_keyword_block')) {
390
- const staticMatch = keywordDetector.check(path);
390
+ const staticMatch = await keywordDetector.checkAccelerated(path);
391
391
  if (staticMatch && !exemptions.shouldSkipKeyword(staticMatch, path)) {
392
392
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
393
393
  console.error(`[AIWAF-BLOCK-STATIC-KW] match=${staticMatch}`);
@@ -396,7 +396,7 @@ module.exports = function aiwaf(rawOpts = {}) {
396
396
  return deny(403, 'blocked', `static:${staticMatch}`);
397
397
  }
398
398
 
399
- const dynamicMatch = dynamicKeyword.check(path);
399
+ const dynamicMatch = await dynamicKeyword.checkAccelerated(path);
400
400
  if (dynamicMatch && !exemptions.shouldSkipKeyword(dynamicMatch, path)) {
401
401
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
402
402
  console.error(`[AIWAF-BLOCK-DYNAMIC-KW] match=${dynamicMatch}`);
@@ -436,7 +436,7 @@ module.exports = function aiwaf(rawOpts = {}) {
436
436
  }))
437
437
  .filter(entry => now - entry.timestamp <= 5 * 60 * 1000);
438
438
 
439
- const stats = anomalyDetector.analyzeRecentBehavior(recentData);
439
+ const stats = await anomalyDetector.analyzeRecentBehaviorAccelerated(recentData);
440
440
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
441
441
  console.error(`[AIWAF-ANOMALY-STATS] should_block=${stats?.should_block}`);
442
442
  }
@@ -30,10 +30,12 @@ async function loadWasmFromDisk() {
30
30
  return {
31
31
  AiwafIsolationForest: bg.IsolationForest,
32
32
  IsolationForest: bg.IsolationForest,
33
+ KeywordMatcher: bg.KeywordMatcher,
33
34
  validate_headers: bg.validate_headers,
34
35
  validate_headers_with_config: bg.validate_headers_with_config,
35
36
  analyze_recent_behavior: bg.analyze_recent_behavior,
36
37
  extract_features: bg.extract_features,
38
+ extract_training_features: bg.extract_training_features,
37
39
  extract_features_batch_with_state: bg.extract_features_batch_with_state,
38
40
  finalize_feature_state: bg.finalize_feature_state,
39
41
  build_records: bg.build_records,
@@ -219,8 +221,9 @@ function normalizeValidationResult(result, fallbackReason) {
219
221
 
220
222
  function normalizeRecentEntries(entries = []) {
221
223
  return (Array.isArray(entries) ? entries : []).map(entry => {
222
- const rawTimestamp = Number(entry.timestamp ?? entry.timestamp_epoch ?? Date.now());
223
- const timestamp = rawTimestamp > 1000000000000 ? rawTimestamp / 1000 : rawTimestamp;
224
+ const hasMilliseconds = entry.timestamp_ms !== undefined && entry.timestamp_ms !== null;
225
+ const rawTimestamp = Number(hasMilliseconds ? entry.timestamp_ms : (entry.timestamp ?? entry.timestamp_epoch ?? Date.now()));
226
+ const timestamp = (hasMilliseconds || rawTimestamp > 1000000000000) ? rawTimestamp / 1000 : rawTimestamp;
224
227
  return {
225
228
  path_lower: String(entry.path_lower || entry.path || '').toLowerCase(),
226
229
  timestamp: Number.isFinite(timestamp) ? timestamp : Date.now() / 1000,
@@ -382,6 +385,31 @@ async function extractWasmFeatures(records, staticKeywords = []) {
382
385
  }
383
386
  }
384
387
 
388
+ async function extractWasmTrainingFeatures(records, staticKeywords = []) {
389
+ const mod = await loadWasm();
390
+ if (!mod || typeof mod.extract_training_features !== 'function') return null;
391
+ try {
392
+ return mod.extract_training_features(records || [], staticKeywords || []);
393
+ } catch (err) {
394
+ return null;
395
+ }
396
+ }
397
+
398
+ async function createKeywordMatcher(keywords = []) {
399
+ const mod = await loadWasm();
400
+ if (!mod || typeof mod.KeywordMatcher !== 'function') return null;
401
+ try {
402
+ const matcher = new mod.KeywordMatcher(keywords);
403
+ return {
404
+ firstMatch(path) {
405
+ return matcher.first_match(path) || null;
406
+ }
407
+ };
408
+ } catch (err) {
409
+ return null;
410
+ }
411
+ }
412
+
385
413
  async function extractWasmFeaturesBatchWithState(records, staticKeywords = [], state = null) {
386
414
  const mod = await loadWasm();
387
415
  if (!mod || typeof mod.extract_features_batch_with_state !== 'function') return null;
@@ -473,6 +501,8 @@ module.exports = {
473
501
  validateRecent,
474
502
  analyzeRecentBehavior,
475
503
  extractWasmFeatures,
504
+ extractWasmTrainingFeatures,
505
+ createKeywordMatcher,
476
506
  extractWasmFeaturesBatchWithState,
477
507
  finalizeWasmFeatureState,
478
508
  buildWasmRecords,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiwaf",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -102,7 +102,7 @@
102
102
  ],
103
103
  "repository": {
104
104
  "type": "git",
105
- "url": "git+https://github.com/aayushgauba/aiwaf.git",
105
+ "url": "git+https://github.com/aiwaf-project/aiwaf.git",
106
106
  "directory": "js"
107
107
  },
108
108
  "author": "Aayush Gauba",
package/train.js CHANGED
@@ -3,10 +3,11 @@ const path = require('path');
3
3
  const glob = require('glob');
4
4
  const zlib = require('zlib');
5
5
  const readline = require('readline');
6
- const { IsolationForest } = require('./lib/isolationForest');
6
+ const { createIsolationForest } = require('./lib/wasmAdapter');
7
7
  const requestLogStore = require('./lib/requestLogStore');
8
8
  const modelStore = require('./lib/modelStore');
9
9
  const blacklistManager = require('./lib/blacklistManager');
10
+ const { calculateTrainingFeatures } = require('./lib/trainingFeatures');
10
11
 
11
12
  const STATIC_KW = [
12
13
  '.php', '.xmlrpc', 'wp-', '.env', '.git', '.bak',
@@ -387,48 +388,6 @@ function parseDbEvent(event) {
387
388
  };
388
389
  }
389
390
 
390
- function calculateFeatures(parsedRequests) {
391
- const ipRequests = new Map();
392
- const ip404Counts = new Map();
393
-
394
- for (const req of parsedRequests) {
395
- if (!ipRequests.has(req.ip)) {
396
- ipRequests.set(req.ip, []);
397
- }
398
- ipRequests.get(req.ip).push(req);
399
-
400
- if (req.status === '404') {
401
- ip404Counts.set(req.ip, (ip404Counts.get(req.ip) || 0) + 1);
402
- }
403
- }
404
-
405
- const features = [];
406
-
407
- for (const req of parsedRequests) {
408
- const pathLen = req.path.length;
409
-
410
- const kwHits = STATIC_KW.reduce(
411
- (sum, kw) => sum + (req.path.toLowerCase().includes(kw) ? 1 : 0),
412
- 0
413
- );
414
-
415
- const statusIdx = STATUS_IDX.indexOf(req.status) >= 0
416
- ? STATUS_IDX.indexOf(req.status)
417
- : -1;
418
-
419
- const respTime = req.responseTime;
420
-
421
- const ipReqs = ipRequests.get(req.ip);
422
- const burst = ipReqs.filter(item => Math.abs(item.timestamp.getTime() - req.timestamp.getTime()) <= 10000).length;
423
-
424
- const total404 = ip404Counts.get(req.ip) || 0;
425
-
426
- features.push([pathLen, kwHits, statusIdx, respTime, burst, total404]);
427
- }
428
-
429
- return features;
430
- }
431
-
432
391
  (async () => {
433
392
  try {
434
393
  const rawAccessLines = await readAccessLogLines();
@@ -497,7 +456,7 @@ function calculateFeatures(parsedRequests) {
497
456
 
498
457
  console.log(`Parsed ${parsedRequests.length} valid requests`);
499
458
 
500
- const features = calculateFeatures(parsedRequests);
459
+ const features = await calculateTrainingFeatures(parsedRequests, STATIC_KW, STATUS_IDX);
501
460
  if (features.length === 0) {
502
461
  console.warn('No features generated.');
503
462
  return;
@@ -510,18 +469,18 @@ function calculateFeatures(parsedRequests) {
510
469
 
511
470
  let anomalyIps = new Set();
512
471
  if (parsedRequests.length >= MIN_AI_LOGS || FORCE_TRAINING) {
513
- const model = new IsolationForest({ nTrees: 100, sampleSize: 256 });
472
+ const model = await createIsolationForest({ nTrees: 100, sampleSize: 256 });
514
473
  model.fit(features);
515
474
 
516
- const modelData = {
517
- ...model.toJSON(),
518
- metadata: {
519
- createdAt: new Date().toISOString(),
520
- samplesCount: features.length,
521
- featureCount: 6,
522
- version: '1.1'
523
- }
475
+ const metadata = {
476
+ createdAt: new Date().toISOString(),
477
+ samplesCount: features.length,
478
+ featureCount: 6,
479
+ version: '1.1'
524
480
  };
481
+ const modelData = model.__aiwafWasm
482
+ ? { model_type: 'aiwaf_wasm.IsolationForest', model_state: model.toJSON(), metadata }
483
+ : { ...model.toJSON(), metadata };
525
484
 
526
485
  await modelStore.save(process.env, modelData, modelData.metadata);
527
486
  console.log(`Trained on ${features.length} samples`);
package/utils/cache.js CHANGED
@@ -1,3 +1,3 @@
1
- const NodeCache = require('node-cache');
2
- const redis = require('redis');
1
+ const NodeCache = require('node-cache');
2
+ const redis = require('redis');
3
3
  module.exports = (useRedis=false) => useRedis ? redis.createClient() : new NodeCache();
package/utils/db.js CHANGED
@@ -1,11 +1,11 @@
1
- const knex = require('knex');
2
-
3
- const isTest = process.env.NODE_ENV === 'test';
4
-
5
- module.exports = knex({
6
- client: 'sqlite3',
7
- connection: {
8
- filename: isTest ? ':memory:' : './aiwaf.sqlite'
9
- },
10
- useNullAsDefault: true,
1
+ const knex = require('knex');
2
+
3
+ const isTest = process.env.NODE_ENV === 'test';
4
+
5
+ module.exports = knex({
6
+ client: 'sqlite3',
7
+ connection: {
8
+ filename: isTest ? ':memory:' : './aiwaf.sqlite'
9
+ },
10
+ useNullAsDefault: true,
11
11
  });