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.
@@ -54,6 +54,7 @@ module.exports = function createAdonisMiddleware(opts = {}) {
54
54
  if (!req.path) req.path = ctx.request?.url?.() || ctx.request?.url || req.url;
55
55
  if (!req.url) req.url = req.path;
56
56
  if (!req.ip) req.ip = ctx.request?.ip?.() || ctx.request?.ip;
57
+ if (req.body === undefined && typeof ctx.request?.body === 'function') req.body = ctx.request.body();
57
58
 
58
59
  // Don't override headers - the raw request already has them from the HTTP server
59
60
 
@@ -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
  };
@@ -32,16 +32,22 @@ function fastifyPlugin(fastify, opts = {}, done) {
32
32
  const middleware = createExpressMiddleware(opts);
33
33
 
34
34
  fastify.addHook('onRequest', async (request, reply) => {
35
- await new Promise(resolve => {
36
- const res = createExpressLikeResponse(reply);
37
- middleware(request.raw, res, resolve);
38
- });
35
+ const res = createExpressLikeResponse(reply);
36
+ await middleware(request.raw, res, () => {});
39
37
 
40
38
  if (reply.sent) {
41
39
  return reply;
42
40
  }
43
41
  });
44
42
 
43
+ fastify.addHook('preValidation', async (request, reply) => {
44
+ const finding = await middleware.inspectPayload({
45
+ headers: request.headers, ip: request.ip, url: request.raw.url,
46
+ body: request.body, query: request.query, aiwafRoute: request.raw.aiwafRoute
47
+ });
48
+ if (finding) return reply.code(finding.status).send({ error: finding.rule });
49
+ });
50
+
45
51
  done();
46
52
  }
47
53
 
@@ -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,
package/lib/hapiPlugin.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const createExpressMiddleware = require('./wafMiddleware');
2
+ const { version } = require('../package.json');
2
3
 
3
4
  function createExpressLikeResponse(h, rawRes) {
4
5
  const res = {
@@ -45,10 +46,19 @@ function createExpressLikeResponse(h, rawRes) {
45
46
 
46
47
  module.exports = {
47
48
  name: 'aiwaf',
48
- version: '1.0.0',
49
+ version,
49
50
  register: async (server, opts = {}) => {
50
51
  const middleware = createExpressMiddleware(opts);
51
52
 
53
+ server.ext('onPreHandler', async (request, h) => {
54
+ const finding = await middleware.inspectPayload({
55
+ headers: request.headers, ip: request.info?.remoteAddress,
56
+ path: request.path, url: request.url?.href,
57
+ body: request.payload, query: request.query, aiwafRoute: request.raw.req.aiwafRoute
58
+ });
59
+ return finding ? h.response({ error: finding.rule }).code(finding.status).takeover() : h.continue;
60
+ });
61
+
52
62
  server.ext('onRequest', async (request, h) => {
53
63
  const res = createExpressLikeResponse(h, request.raw.res);
54
64
  const req = request.raw.req;