aiwaf 1.1.4 → 1.1.5
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 +141 -190
- package/bin/aiwaf.js +61 -57
- package/lib/blacklistManager.js +2 -358
- package/lib/blocklistManager.js +364 -0
- package/lib/csvStore.js +1 -1
- package/lib/nativePipeline.js +5 -3
- package/lib/rateLimiter.js +4 -4
- package/lib/wafMiddleware.js +8 -8
- package/lib/wasmAdapter.js +7 -1
- package/package.json +3 -5
- package/train.js +6 -6
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
const path = require('path');
|
|
2
|
+
const db = require('../utils/db');
|
|
3
|
+
const csvStore = require('./csvStore');
|
|
4
|
+
const {
|
|
5
|
+
FIRST_BLOCK_SECONDS,
|
|
6
|
+
evaluateReputation,
|
|
7
|
+
formatBlockReason,
|
|
8
|
+
normalizeReason
|
|
9
|
+
} = require('./reputation');
|
|
10
|
+
|
|
11
|
+
const headers = [
|
|
12
|
+
'id', 'ip_address', 'reason', 'reputation_reason', 'reasons', 'score', 'offenses',
|
|
13
|
+
'blocked_at', 'expires_at', 'duration', 'permanent', 'extended_request_info'
|
|
14
|
+
];
|
|
15
|
+
const csvPath = process.env.AIWAF_BLOCKED_IPS_CSV_PATH || path.join('logs', 'storage', 'blocked_ips.csv');
|
|
16
|
+
|
|
17
|
+
let initialized = false;
|
|
18
|
+
let dbAvailable = true;
|
|
19
|
+
|
|
20
|
+
const schemaColumns = {
|
|
21
|
+
reputation_reason: table => table.string('reputation_reason').defaultTo(''),
|
|
22
|
+
reasons: table => table.text('reasons').defaultTo('[]'),
|
|
23
|
+
score: table => table.integer('score').defaultTo(0),
|
|
24
|
+
offenses: table => table.integer('offenses').defaultTo(0),
|
|
25
|
+
expires_at: table => table.float('expires_at').nullable(),
|
|
26
|
+
duration: table => table.integer('duration').nullable(),
|
|
27
|
+
permanent: table => table.boolean('permanent').defaultTo(false),
|
|
28
|
+
extended_request_info: table => table.text('extended_request_info').defaultTo('{}')
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
function parseJson(value, fallback) {
|
|
32
|
+
if (value && typeof value === 'object') return value;
|
|
33
|
+
try { return value ? JSON.parse(value) : fallback; } catch (err) { return fallback; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function toTimestamp(value) {
|
|
37
|
+
if (value === null || value === undefined || value === '') return null;
|
|
38
|
+
const numeric = Number(value);
|
|
39
|
+
if (Number.isFinite(numeric)) return numeric;
|
|
40
|
+
const parsed = new Date(value).getTime();
|
|
41
|
+
return Number.isFinite(parsed) ? parsed / 1000 : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function normalizeRow(row = {}) {
|
|
45
|
+
const reason = normalizeReason(row.reason || 'legacy block');
|
|
46
|
+
const legacy = !row.reputation_reason;
|
|
47
|
+
return {
|
|
48
|
+
...row,
|
|
49
|
+
ip_address: String(row.ip_address || row.ip || '').trim(),
|
|
50
|
+
reason,
|
|
51
|
+
reputation_reason: row.reputation_reason || (legacy ? 'legacy_blacklist' : ''),
|
|
52
|
+
reasons: parseJson(row.reasons, legacy ? ['legacy_blacklist', reason] : [reason]),
|
|
53
|
+
score: Number(row.score || (legacy ? 100 : 0)),
|
|
54
|
+
offenses: Number(row.offenses || (legacy ? 1 : 0)),
|
|
55
|
+
blocked_at: toTimestamp(row.blocked_at) || Date.now() / 1000,
|
|
56
|
+
expires_at: toTimestamp(row.expires_at),
|
|
57
|
+
duration: row.duration === '' || row.duration === null || row.duration === undefined ? null : Number(row.duration),
|
|
58
|
+
permanent: row.permanent === true || row.permanent === 1 || String(row.permanent) === '1' || String(row.permanent).toLowerCase() === 'true' || legacy,
|
|
59
|
+
extended_request_info: parseJson(row.extended_request_info, {})
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function serializeRow(row) {
|
|
64
|
+
return {
|
|
65
|
+
...row,
|
|
66
|
+
reasons: JSON.stringify(row.reasons || []),
|
|
67
|
+
extended_request_info: JSON.stringify(row.extended_request_info || {}),
|
|
68
|
+
permanent: row.permanent ? 1 : 0
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isActive(row, now = Date.now() / 1000) {
|
|
73
|
+
return !!row && (row.permanent || !row.expires_at || Number(row.expires_at) > now);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function ensureDbColumns() {
|
|
77
|
+
if (typeof db.schema.hasColumn !== 'function' || typeof db.schema.table !== 'function') return;
|
|
78
|
+
for (const [name, addColumn] of Object.entries(schemaColumns)) {
|
|
79
|
+
if (!await db.schema.hasColumn('blocked_ips', name)) {
|
|
80
|
+
await db.schema.table('blocked_ips', addColumn);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function initialize() {
|
|
86
|
+
if (initialized) return dbAvailable;
|
|
87
|
+
|
|
88
|
+
try {
|
|
89
|
+
const exists = await db.schema.hasTable('blocked_ips');
|
|
90
|
+
if (!exists) {
|
|
91
|
+
await db.schema.createTable('blocked_ips', table => {
|
|
92
|
+
table.increments('id').primary();
|
|
93
|
+
table.string('ip_address').unique().notNullable();
|
|
94
|
+
table.string('reason').defaultTo('WAF blocked');
|
|
95
|
+
table.timestamp('blocked_at').defaultTo(db.fn.now());
|
|
96
|
+
Object.values(schemaColumns).forEach(addColumn => addColumn(table));
|
|
97
|
+
});
|
|
98
|
+
} else {
|
|
99
|
+
await ensureDbColumns();
|
|
100
|
+
}
|
|
101
|
+
dbAvailable = true;
|
|
102
|
+
} catch (err) {
|
|
103
|
+
dbAvailable = false;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
initialized = true;
|
|
107
|
+
return dbAvailable;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function csvRows() {
|
|
111
|
+
return csvStore.readRows(csvPath, headers).map(normalizeRow);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function rawRow(ip) {
|
|
115
|
+
const normalizedIp = String(ip || '').trim();
|
|
116
|
+
if (await initialize()) {
|
|
117
|
+
try {
|
|
118
|
+
const row = await db('blocked_ips').where('ip_address', normalizedIp).first();
|
|
119
|
+
return row ? normalizeRow(row) : null;
|
|
120
|
+
} catch (err) {
|
|
121
|
+
dbAvailable = false;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return csvRows().find(row => row.ip_address === normalizedIp) || null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function saveRow(row) {
|
|
128
|
+
if (dbAvailable) {
|
|
129
|
+
try {
|
|
130
|
+
const payload = serializeRow(row);
|
|
131
|
+
delete payload.id;
|
|
132
|
+
await db('blocked_ips').insert(payload).onConflict('ip_address').merge();
|
|
133
|
+
return;
|
|
134
|
+
} catch (err) {
|
|
135
|
+
dbAvailable = false;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
await csvStore.updateRows(csvPath, headers, current => {
|
|
139
|
+
const rows = current.map(normalizeRow);
|
|
140
|
+
const index = rows.findIndex(item => item.ip_address === row.ip_address);
|
|
141
|
+
const stored = { ...row, id: index >= 0 ? rows[index].id : csvStore.nextId(rows) };
|
|
142
|
+
if (index >= 0) rows[index] = stored;
|
|
143
|
+
else rows.push(stored);
|
|
144
|
+
return { rows: rows.map(serializeRow) };
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
module.exports = {
|
|
149
|
+
async isBlocked(ip) {
|
|
150
|
+
const row = await rawRow(ip);
|
|
151
|
+
// An expired snapshot is not authority to delete a concurrent refresh.
|
|
152
|
+
return isActive(row);
|
|
153
|
+
},
|
|
154
|
+
|
|
155
|
+
async block(ip, reason = 'WAF blocked', options = {}) {
|
|
156
|
+
const normalizedIp = String(ip || '').trim();
|
|
157
|
+
if (!normalizedIp) return false;
|
|
158
|
+
if (options.checkExemptions !== false) {
|
|
159
|
+
try {
|
|
160
|
+
const exemptionStore = require('./exemptionStore');
|
|
161
|
+
if (await exemptionStore.isIpExempt(normalizedIp)) return false;
|
|
162
|
+
} catch (err) {
|
|
163
|
+
// Storage failures must not disable blocking.
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
const now = Number(options.now ?? Date.now() / 1000);
|
|
167
|
+
const existing = await rawRow(normalizedIp);
|
|
168
|
+
const decision = evaluateReputation({ existing: existing || {}, reason, now });
|
|
169
|
+
const explicitDuration = options.duration === undefined ? null : Number(options.duration);
|
|
170
|
+
const permanent = options.permanent === true || explicitDuration === 0;
|
|
171
|
+
const duration = permanent ? null : (explicitDuration || decision.duration || FIRST_BLOCK_SECONDS);
|
|
172
|
+
await saveRow({
|
|
173
|
+
...(existing || {}),
|
|
174
|
+
ip_address: normalizedIp,
|
|
175
|
+
reason: normalizeReason(reason),
|
|
176
|
+
reputation_reason: formatBlockReason(decision),
|
|
177
|
+
reasons: decision.reasons,
|
|
178
|
+
score: decision.score,
|
|
179
|
+
offenses: decision.offenses,
|
|
180
|
+
blocked_at: now,
|
|
181
|
+
expires_at: permanent ? null : now + duration,
|
|
182
|
+
duration,
|
|
183
|
+
permanent,
|
|
184
|
+
extended_request_info: options.extendedRequestInfo || existing?.extended_request_info || {}
|
|
185
|
+
});
|
|
186
|
+
return true;
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
blockTemporary(ip, reason, minutes = 60, extendedRequestInfo = {}) {
|
|
190
|
+
return this.block(ip, reason, { duration: Number(minutes) * 60, extendedRequestInfo });
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
blockPermanent(ip, reason, extendedRequestInfo = {}) {
|
|
194
|
+
return this.block(ip, reason, { permanent: true, extendedRequestInfo });
|
|
195
|
+
},
|
|
196
|
+
|
|
197
|
+
async unblock(ip) {
|
|
198
|
+
const normalizedIp = String(ip || '').trim();
|
|
199
|
+
const useDb = await initialize();
|
|
200
|
+
if (useDb) {
|
|
201
|
+
try {
|
|
202
|
+
const deleted = await db('blocked_ips').where('ip_address', normalizedIp).del();
|
|
203
|
+
return deleted > 0;
|
|
204
|
+
} catch (err) {
|
|
205
|
+
dbAvailable = false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return csvStore.updateRows(csvPath, headers, current => {
|
|
210
|
+
const rows = current.map(normalizeRow);
|
|
211
|
+
const filtered = rows.filter(row => row.ip_address !== normalizedIp);
|
|
212
|
+
return { rows: filtered.map(serializeRow), result: filtered.length !== rows.length };
|
|
213
|
+
});
|
|
214
|
+
},
|
|
215
|
+
|
|
216
|
+
async getBlockedIPs({ activeOnly = true } = {}) {
|
|
217
|
+
let rows;
|
|
218
|
+
const useDb = await initialize();
|
|
219
|
+
if (useDb) {
|
|
220
|
+
try {
|
|
221
|
+
rows = (await db('blocked_ips').select('*').orderBy('blocked_at', 'desc')).map(normalizeRow);
|
|
222
|
+
} catch (err) {
|
|
223
|
+
dbAvailable = false;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
rows = rows || csvRows().sort((a, b) => b.blocked_at - a.blocked_at);
|
|
227
|
+
return activeOnly ? rows.filter(row => isActive(row)) : rows;
|
|
228
|
+
},
|
|
229
|
+
|
|
230
|
+
async getBlockInfo(ip) {
|
|
231
|
+
return rawRow(ip);
|
|
232
|
+
},
|
|
233
|
+
|
|
234
|
+
async cleanupExpired(now = Date.now() / 1000) {
|
|
235
|
+
if (await initialize()) {
|
|
236
|
+
try {
|
|
237
|
+
// Evaluate expiry in the DELETE itself, against the current row.
|
|
238
|
+
return await db('blocked_ips').where('permanent', false)
|
|
239
|
+
.whereNotNull('reputation_reason').whereNot('reputation_reason', '')
|
|
240
|
+
.where('expires_at', '>', 0).where('expires_at', '<=', now).del();
|
|
241
|
+
} catch (err) {
|
|
242
|
+
dbAvailable = false;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return csvStore.updateRows(csvPath, headers, current => {
|
|
246
|
+
const rows = current.map(normalizeRow);
|
|
247
|
+
const active = rows.filter(row => isActive(row, now));
|
|
248
|
+
return { rows: active.map(serializeRow), result: rows.length - active.length };
|
|
249
|
+
});
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
async getStatistics() {
|
|
253
|
+
const all = await this.getBlockedIPs({ activeOnly: false });
|
|
254
|
+
const active = all.filter(row => isActive(row));
|
|
255
|
+
const reasonCounts = {};
|
|
256
|
+
active.forEach(row => { reasonCounts[row.reason] = (reasonCounts[row.reason] || 0) + 1; });
|
|
257
|
+
return {
|
|
258
|
+
total: all.length,
|
|
259
|
+
active: active.length,
|
|
260
|
+
expired: all.length - active.length,
|
|
261
|
+
permanent: active.filter(row => row.permanent).length,
|
|
262
|
+
temporary: active.filter(row => !row.permanent).length,
|
|
263
|
+
average_score: active.length ? active.reduce((sum, row) => sum + row.score, 0) / active.length : 0,
|
|
264
|
+
reason_counts: reasonCounts
|
|
265
|
+
};
|
|
266
|
+
},
|
|
267
|
+
|
|
268
|
+
async getRecentBlocks(hours = 24) {
|
|
269
|
+
const cutoff = Date.now() / 1000 - Number(hours) * 3600;
|
|
270
|
+
return (await this.getBlockedIPs()).filter(row => row.blocked_at >= cutoff);
|
|
271
|
+
},
|
|
272
|
+
|
|
273
|
+
async getTopBlockedReasons(limit = 10) {
|
|
274
|
+
const stats = await this.getStatistics();
|
|
275
|
+
return Object.entries(stats.reason_counts)
|
|
276
|
+
.sort((a, b) => b[1] - a[1])
|
|
277
|
+
.slice(0, Number(limit))
|
|
278
|
+
.map(([reason, count]) => ({ reason, count }));
|
|
279
|
+
},
|
|
280
|
+
|
|
281
|
+
async bulkBlock(ips, reason, options = {}) {
|
|
282
|
+
const pairs = await Promise.all((ips || []).map(async ip => [ip, await this.block(ip, reason, options)]));
|
|
283
|
+
return Object.fromEntries(pairs);
|
|
284
|
+
},
|
|
285
|
+
|
|
286
|
+
async bulkUnblock(ips) {
|
|
287
|
+
const pairs = await Promise.all((ips || []).map(async ip => [ip, await this.unblock(ip)]));
|
|
288
|
+
return Object.fromEntries(pairs);
|
|
289
|
+
},
|
|
290
|
+
|
|
291
|
+
async addToAllowlist(ip, reason = 'Manual allowlist') {
|
|
292
|
+
const exemptionStore = require('./exemptionStore');
|
|
293
|
+
await exemptionStore.addIp(ip, reason);
|
|
294
|
+
await this.unblock(ip);
|
|
295
|
+
return true;
|
|
296
|
+
},
|
|
297
|
+
|
|
298
|
+
async removeFromAllowlist(ip) {
|
|
299
|
+
return require('./exemptionStore').removeIp(ip);
|
|
300
|
+
},
|
|
301
|
+
|
|
302
|
+
async isAllowlisted(ip) {
|
|
303
|
+
return require('./exemptionStore').isIpExempt(ip);
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
async getAllowlist() {
|
|
307
|
+
const exemptionStore = require('./exemptionStore');
|
|
308
|
+
return { ips: await exemptionStore.listIps(), paths: await exemptionStore.listPaths() };
|
|
309
|
+
},
|
|
310
|
+
|
|
311
|
+
async migrateLegacy({ duration = null, now = Date.now() / 1000 } = {}) {
|
|
312
|
+
const rows = await this.getBlockedIPs({ activeOnly: false });
|
|
313
|
+
let changed = 0;
|
|
314
|
+
for (const original of rows) {
|
|
315
|
+
if (original.reputation_reason && original.reputation_reason !== 'legacy_blacklist') continue;
|
|
316
|
+
const row = normalizeRow(original);
|
|
317
|
+
row.reputation_reason = duration ? 'legacy_blacklist_converted' : 'legacy_blacklist';
|
|
318
|
+
row.permanent = !duration;
|
|
319
|
+
row.duration = duration || null;
|
|
320
|
+
row.expires_at = duration ? Number(now) + Number(duration) : null;
|
|
321
|
+
await saveRow(row);
|
|
322
|
+
changed += 1;
|
|
323
|
+
}
|
|
324
|
+
return { total: rows.length, changed };
|
|
325
|
+
},
|
|
326
|
+
|
|
327
|
+
async exportRecords() {
|
|
328
|
+
return this.getBlockedIPs({ activeOnly: false });
|
|
329
|
+
},
|
|
330
|
+
|
|
331
|
+
async importRecords(rows = []) {
|
|
332
|
+
let imported = 0;
|
|
333
|
+
for (const raw of rows) {
|
|
334
|
+
const row = normalizeRow(raw);
|
|
335
|
+
if (!row.ip_address) continue;
|
|
336
|
+
await saveRow(row);
|
|
337
|
+
imported += 1;
|
|
338
|
+
}
|
|
339
|
+
return imported;
|
|
340
|
+
},
|
|
341
|
+
|
|
342
|
+
async clear() {
|
|
343
|
+
const useDb = await initialize();
|
|
344
|
+
if (useDb) {
|
|
345
|
+
try {
|
|
346
|
+
return await db('blocked_ips').del();
|
|
347
|
+
} catch (err) {
|
|
348
|
+
dbAvailable = false;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
return csvStore.updateRows(csvPath, headers, rows => ({ rows: [], result: rows.length }));
|
|
353
|
+
},
|
|
354
|
+
|
|
355
|
+
async initialize() {
|
|
356
|
+
return initialize();
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
// Compatibility method aliases; new applications should use allowlist names.
|
|
361
|
+
module.exports.addToWhitelist = module.exports.addToAllowlist;
|
|
362
|
+
module.exports.removeFromWhitelist = module.exports.removeFromAllowlist;
|
|
363
|
+
module.exports.isWhitelisted = module.exports.isAllowlisted;
|
|
364
|
+
module.exports.getWhitelist = module.exports.getAllowlist;
|
package/lib/csvStore.js
CHANGED
|
@@ -81,7 +81,7 @@ function writeRows(filePath, headers, rows) {
|
|
|
81
81
|
}
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
// All
|
|
84
|
+
// All blocklist mutations use this lock and read the current file inside it.
|
|
85
85
|
// A crash leaves the lock in place; recovery must first stop the owning writer.
|
|
86
86
|
async function updateRows(filePath, headers, update, timeoutMs = 60000) {
|
|
87
87
|
filePath = path.resolve(filePath);
|
package/lib/nativePipeline.js
CHANGED
|
@@ -89,6 +89,8 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
89
89
|
if (options[key] != null && (typeof options[key] !== 'function' || options[key].constructor.name === 'AsyncFunction')) throw new TypeError(`${key} must be synchronous`);
|
|
90
90
|
}
|
|
91
91
|
const profile = JSON.parse(JSON.stringify(options.profile || {}));
|
|
92
|
+
if (!Object.hasOwn(profile, 'blocklist') && Object.hasOwn(profile, 'blacklist')) profile.blocklist = profile.blacklist;
|
|
93
|
+
delete profile.blacklist;
|
|
92
94
|
const dataDir = path.resolve(options.dataDir || 'aiwaf_native_data');
|
|
93
95
|
// State files are dedicated to this adapter. Legacy ORM/CSV schemas are not mixed.
|
|
94
96
|
const blockPath = path.join(dataDir, 'native_blocks.csv');
|
|
@@ -100,12 +102,12 @@ module.exports = async function createNativeMiddleware(options = {}) {
|
|
|
100
102
|
if (persist) {
|
|
101
103
|
blocks = writer(blockPath, BLOCK_HEADER, true); opened.push(blocks);
|
|
102
104
|
keywords = writer(keywordPath, KEYWORD_HEADER, true); opened.push(keywords);
|
|
103
|
-
const
|
|
105
|
+
const blocklist = { ...(profile.blocklist || {}) };
|
|
104
106
|
for (const row of readRows(blockPath, ['ip','expires_at','reason'])) {
|
|
105
107
|
if (!row.ip || !row.expires_at || !Number.isFinite(Number(row.expires_at))) throw new Error('Invalid persisted block row');
|
|
106
|
-
|
|
108
|
+
blocklist[row.ip] = Number(row.expires_at);
|
|
107
109
|
}
|
|
108
|
-
profile.
|
|
110
|
+
profile.blocklist = blocklist;
|
|
109
111
|
profile.dynamic_keywords = [...new Set([...(profile.dynamic_keywords || []), ...readRows(keywordPath, ['keyword']).map(r => r.keyword)])];
|
|
110
112
|
}
|
|
111
113
|
engine = await createRequestPipeline(profile, options.model);
|
package/lib/rateLimiter.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const NodeCache = require('node-cache');
|
|
2
|
-
const
|
|
2
|
+
const blocklistManager = require('./blocklistManager');
|
|
3
3
|
|
|
4
4
|
let cacheBackend;
|
|
5
5
|
let opts;
|
|
@@ -119,7 +119,7 @@ module.exports = {
|
|
|
119
119
|
await cacheBackend.expire(key, effective.WINDOW_SEC * 2); // Extended TTL
|
|
120
120
|
const count = await cacheBackend.lLen(key);
|
|
121
121
|
if (count > effective.FLOOD_REQ) {
|
|
122
|
-
await
|
|
122
|
+
await blocklistManager.block(ip, 'flood');
|
|
123
123
|
}
|
|
124
124
|
} catch (err) {
|
|
125
125
|
console.warn('Rate cache unavailable in record().');
|
|
@@ -130,9 +130,9 @@ module.exports = {
|
|
|
130
130
|
async isBlocked(ip, overrides = {}) {
|
|
131
131
|
const effective = getEffectiveOpts(overrides);
|
|
132
132
|
try {
|
|
133
|
-
if (await
|
|
133
|
+
if (await blocklistManager.isBlocked(ip)) return true;
|
|
134
134
|
} catch (err) {
|
|
135
|
-
console.warn('
|
|
135
|
+
console.warn('Blocklist unavailable during rate check.');
|
|
136
136
|
if (opts.failureMode === 'closed') throw unavailable();
|
|
137
137
|
}
|
|
138
138
|
|
package/lib/wafMiddleware.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const rateLimiter = require('./rateLimiter');
|
|
2
2
|
const { createInspector } = require('./sqlInjection');
|
|
3
|
-
const
|
|
3
|
+
const blocklistManager = require('./blocklistManager');
|
|
4
4
|
const keywordDetector = require('./keywordDetector');
|
|
5
5
|
const dynamicKeyword = require('./dynamicKeyword');
|
|
6
6
|
const dynamicKeywordStore = require('./dynamicKeywordStore');
|
|
@@ -182,7 +182,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
182
182
|
|
|
183
183
|
if (opts.AIWAF_CLEAR_STATE_ON_START) {
|
|
184
184
|
Promise.allSettled([
|
|
185
|
-
|
|
185
|
+
blocklistManager.clear(),
|
|
186
186
|
requestLogStore.clear(),
|
|
187
187
|
dynamicKeywordStore.clear()
|
|
188
188
|
]).catch(() => {});
|
|
@@ -229,7 +229,7 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
229
229
|
}
|
|
230
230
|
const routePlan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
|
|
231
231
|
const shouldApply = name => enabledMiddlewares.has(normalizeMiddlewareName(name)) && routePlan.shouldApply(name);
|
|
232
|
-
const blockIp = reason =>
|
|
232
|
+
const blockIp = reason => blocklistManager.block(ip, reason, {
|
|
233
233
|
extendedRequestInfo: extractExtendedRequestInfo(req, {
|
|
234
234
|
enabled: opts.AIWAF_CAPTURE_EXTENDED_REQUEST_INFO,
|
|
235
235
|
maxHeaders: opts.AIWAF_EXTENDED_INFO_MAX_HEADERS,
|
|
@@ -278,11 +278,11 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
278
278
|
return next();
|
|
279
279
|
}
|
|
280
280
|
|
|
281
|
-
if (shouldApply('ip_keyword_block') && await
|
|
281
|
+
if (shouldApply('ip_keyword_block') && await blocklistManager.isBlocked(ip)) {
|
|
282
282
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
283
|
-
console.error(`[AIWAF-BLOCK-
|
|
283
|
+
console.error(`[AIWAF-BLOCK-BLOCKLIST] ip=${ip}`);
|
|
284
284
|
}
|
|
285
|
-
return deny(403, 'blocked', '
|
|
285
|
+
return deny(403, 'blocked', 'blocklist');
|
|
286
286
|
}
|
|
287
287
|
|
|
288
288
|
const payloadFinding = await inspectPayload(req);
|
|
@@ -410,8 +410,8 @@ module.exports = function aiwaf(rawOpts = {}) {
|
|
|
410
410
|
if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
|
|
411
411
|
console.error(`[AIWAF-BLOCK-RATE] ip=${ip}`);
|
|
412
412
|
}
|
|
413
|
-
if (await
|
|
414
|
-
return deny(403, 'blocked', '
|
|
413
|
+
if (await blocklistManager.isBlocked(ip)) {
|
|
414
|
+
return deny(403, 'blocked', 'flood_or_blocklist');
|
|
415
415
|
}
|
|
416
416
|
return deny(429, 'too_many_requests', 'rate_limit');
|
|
417
417
|
}
|
package/lib/wasmAdapter.js
CHANGED
|
@@ -529,7 +529,13 @@ async function createRequestPipeline(profile = {}, model = null) {
|
|
|
529
529
|
if (!mod || typeof mod.NativeRequestPipeline !== 'function') {
|
|
530
530
|
throw new Error('Native pipeline requires aiwaf-wasm with NativeRequestPipeline support; no fallback');
|
|
531
531
|
}
|
|
532
|
-
|
|
532
|
+
// Retain the existing wire key so published WASM companions remain compatible.
|
|
533
|
+
const wireProfile = { ...profile };
|
|
534
|
+
if (Object.hasOwn(wireProfile, 'blocklist')) {
|
|
535
|
+
wireProfile.blacklist = wireProfile.blocklist;
|
|
536
|
+
delete wireProfile.blocklist;
|
|
537
|
+
}
|
|
538
|
+
const native = new mod.NativeRequestPipeline(JSON.stringify(wireProfile));
|
|
533
539
|
if (['begin','finish','inspect_payload','inspect_body','set_model','clear_model','diagnostics'].some(name => typeof native[name] !== 'function')) {
|
|
534
540
|
native.free();
|
|
535
541
|
throw new Error('Incompatible NativeRequestPipeline API; install the matching WASM build');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aiwaf",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.5",
|
|
4
4
|
"description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"files": [
|
|
@@ -26,17 +26,15 @@
|
|
|
26
26
|
"test:coverage": "jest --runInBand --coverage",
|
|
27
27
|
"test:wasm": "jest --runInBand --runTestsByPath test/wasmAdapter.test.js test/wasm-header-config.test.js test/wasm-header-input.test.js test/wasm-retrain-behavior.test.js test/wasm-waf-integration.test.js && node test/wasm-real.js",
|
|
28
28
|
"aiwaf": "node bin/aiwaf.js",
|
|
29
|
-
"perf:wasm": "node test/perf-wasm.js",
|
|
30
29
|
"test:wasm-real": "node test/wasm-real.js",
|
|
31
|
-
"test:native": "node test/native-pipeline-real.js && node test/native-frameworks-real.js"
|
|
32
|
-
"perf:native": "node ../scripts/benchmark_js_pipeline.js"
|
|
30
|
+
"test:native": "node test/native-pipeline-real.js && node test/native-frameworks-real.js"
|
|
33
31
|
},
|
|
34
32
|
"allowScripts": {
|
|
35
33
|
"sqlite3": true
|
|
36
34
|
},
|
|
37
35
|
"dependencies": {
|
|
38
36
|
"@babel/parser": "^7.29.2",
|
|
39
|
-
"aiwaf-wasm": "^0.2.
|
|
37
|
+
"aiwaf-wasm": "^0.2.5",
|
|
40
38
|
"express": "^4.21.2",
|
|
41
39
|
"glob": "^13.0.6",
|
|
42
40
|
"knex": "^2.4.2",
|
package/train.js
CHANGED
|
@@ -6,7 +6,7 @@ const readline = require('readline');
|
|
|
6
6
|
const { createIsolationForest } = require('./lib/wasmAdapter');
|
|
7
7
|
const requestLogStore = require('./lib/requestLogStore');
|
|
8
8
|
const modelStore = require('./lib/modelStore');
|
|
9
|
-
const
|
|
9
|
+
const blocklistManager = require('./lib/blocklistManager');
|
|
10
10
|
const { calculateTrainingFeatures } = require('./lib/trainingFeatures');
|
|
11
11
|
const { withTrainingEvidence } = require('./lib/trainingEvidence');
|
|
12
12
|
const TRAINING_STATE_DIR = process.env.AIWAF_TRAINING_STATE_DIR
|
|
@@ -236,9 +236,9 @@ async function unblockExemptIps() {
|
|
|
236
236
|
const ips = rows.map(row => row.ip_address).filter(Boolean);
|
|
237
237
|
if (ips.length === 0) return;
|
|
238
238
|
for (const ip of ips) {
|
|
239
|
-
await
|
|
239
|
+
await blocklistManager.unblock(ip);
|
|
240
240
|
}
|
|
241
|
-
console.log(`Cleared ${ips.length} exempt IPs from
|
|
241
|
+
console.log(`Cleared ${ips.length} exempt IPs from blocklist`);
|
|
242
242
|
} catch (err) {
|
|
243
243
|
// ignore
|
|
244
244
|
}
|
|
@@ -458,7 +458,7 @@ async function train() {
|
|
|
458
458
|
if (count >= 6) {
|
|
459
459
|
const loginCount = ip404LoginCounts.get(ip) || 0;
|
|
460
460
|
if (count > loginCount) {
|
|
461
|
-
await evidence.block(ip, () =>
|
|
461
|
+
await evidence.block(ip, () => blocklistManager.block(ip, `Excessive 404s (non-login ${count}/${count + loginCount})`));
|
|
462
462
|
}
|
|
463
463
|
}
|
|
464
464
|
}
|
|
@@ -534,7 +534,7 @@ async function train() {
|
|
|
534
534
|
if (avgKwHits < 2 && max404s < 10 && avgBurst < 15 && totalRequests < 100) {
|
|
535
535
|
continue;
|
|
536
536
|
}
|
|
537
|
-
await evidence.block(ip, () =>
|
|
537
|
+
await evidence.block(ip, () => blocklistManager.block(ip, `AI anomaly + suspicious patterns (kw:${avgKwHits.toFixed(1)}, 404s:${max404s}, burst:${avgBurst.toFixed(1)})`));
|
|
538
538
|
}
|
|
539
539
|
} else {
|
|
540
540
|
console.log(`AI training skipped: ${parsedRequests.length} logs < ${MIN_AI_LOGS}`);
|
|
@@ -568,7 +568,7 @@ async function train() {
|
|
|
568
568
|
}
|
|
569
569
|
|
|
570
570
|
try {
|
|
571
|
-
const blocked = await
|
|
571
|
+
const blocked = await blocklistManager.getBlockedIPs();
|
|
572
572
|
summarizeGeo(blocked.map(row => row.ip_address).filter(Boolean), 'Geo summary for blocked IPs (top 10):');
|
|
573
573
|
} catch (err) {
|
|
574
574
|
// ignore
|