aiwaf 1.1.3 → 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.
@@ -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
@@ -72,7 +72,39 @@ function writeRows(filePath, headers, rows) {
72
72
  for (const row of rows) {
73
73
  lines.push(headers.map(header => escapeCsv(row[header] ?? '')).join(','));
74
74
  }
75
- fs.writeFileSync(filePath, `${lines.join('\n')}\n`, 'utf8');
75
+ const temp = `${filePath}.${process.pid}.${require('crypto').randomUUID()}.tmp`;
76
+ try {
77
+ fs.writeFileSync(temp, `${lines.join('\n')}\n`, 'utf8');
78
+ fs.renameSync(temp, filePath);
79
+ } finally {
80
+ if (fs.existsSync(temp)) fs.unlinkSync(temp);
81
+ }
82
+ }
83
+
84
+ // All blocklist mutations use this lock and read the current file inside it.
85
+ // A crash leaves the lock in place; recovery must first stop the owning writer.
86
+ async function updateRows(filePath, headers, update, timeoutMs = 60000) {
87
+ filePath = path.resolve(filePath);
88
+ ensureDir(filePath);
89
+ const lock = `${filePath}.lock`;
90
+ const deadline = Date.now() + timeoutMs;
91
+ for (;;) {
92
+ try {
93
+ fs.mkdirSync(lock);
94
+ break;
95
+ } catch (error) {
96
+ if (error.code !== 'EEXIST') throw error;
97
+ if (Date.now() >= deadline) throw new Error(`CSV mutation lock timeout: ${lock}`);
98
+ await new Promise(resolve => setTimeout(resolve, 25));
99
+ }
100
+ }
101
+ try {
102
+ const { rows, result } = update(readRows(filePath, headers));
103
+ writeRows(filePath, headers, rows);
104
+ return result;
105
+ } finally {
106
+ fs.rmdirSync(lock);
107
+ }
76
108
  }
77
109
 
78
110
  function appendRow(filePath, headers, row) {
@@ -97,5 +129,6 @@ module.exports = {
97
129
  readRows,
98
130
  writeRows,
99
131
  appendRow,
132
+ updateRows,
100
133
  nextId
101
134
  };
@@ -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 blacklist = { ...(profile.blacklist || {}) };
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
- blacklist[row.ip] = Number(row.expires_at);
108
+ blocklist[row.ip] = Number(row.expires_at);
107
109
  }
108
- profile.blacklist = blacklist;
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);
@@ -1,5 +1,5 @@
1
1
  const NodeCache = require('node-cache');
2
- const blacklistManager = require('./blacklistManager');
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 blacklistManager.block(ip, 'flood');
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 blacklistManager.isBlocked(ip)) return true;
133
+ if (await blocklistManager.isBlocked(ip)) return true;
134
134
  } catch (err) {
135
- console.warn('Blacklist unavailable during rate check.');
135
+ console.warn('Blocklist unavailable during rate check.');
136
136
  if (opts.failureMode === 'closed') throw unavailable();
137
137
  }
138
138
 
@@ -0,0 +1,59 @@
1
+ // WASM owns receipt identity and decisions; Node owns durable filesystem I/O.
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { createTrainingEvidence } = require('./wasmAdapter');
5
+
6
+ async function acquire(directory, timeoutMs = 60000) {
7
+ fs.mkdirSync(directory, { recursive: true });
8
+ const lock = path.join(directory, 'node_training_evidence.lock');
9
+ const deadline = Date.now() + timeoutMs;
10
+ for (;;) {
11
+ try { fs.mkdirSync(lock); break; } catch (error) {
12
+ if (error.code !== 'EEXIST') throw error;
13
+ if (Date.now() >= deadline) throw new Error(`Training evidence is locked: ${lock}. If a trainer crashed, confirm it has stopped before removing this lock directory.`);
14
+ await new Promise(resolve => setTimeout(resolve, 100));
15
+ }
16
+ }
17
+ return () => fs.rmdirSync(lock);
18
+ }
19
+
20
+ function persist(file, state) {
21
+ const temporary = `${file}.tmp`;
22
+ const fd = fs.openSync(temporary, 'w');
23
+ try { fs.writeFileSync(fd, state); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
24
+ fs.renameSync(temporary, file);
25
+ if (process.platform !== 'win32') {
26
+ const directory = fs.openSync(path.dirname(file), 'r');
27
+ try { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }
28
+ }
29
+ }
30
+
31
+ async function withTrainingEvidence(directory, action, timeoutMs) {
32
+ const release = await acquire(path.resolve(directory), timeoutMs);
33
+ let native;
34
+ try {
35
+ const file = path.join(path.resolve(directory), 'node_training_evidence.json');
36
+ let state;
37
+ try { state = fs.readFileSync(file, 'utf8'); } catch (error) {
38
+ if (error.code !== 'ENOENT') throw error;
39
+ state = '{"version":1,"ips":{}}';
40
+ }
41
+ native = await createTrainingEvidence(state);
42
+ return await action({
43
+ fresh(records) {
44
+ const fields = records.map(row => [row.ip, row.timestamp.toISOString(), row.path, String(row.status)]);
45
+ return JSON.parse(native.fresh_indices(JSON.stringify(fields))).map(index => records[index]);
46
+ },
47
+ async block(ip, perform) {
48
+ if (!native.can_block(ip) || await perform() === false) return false;
49
+ persist(file, native.committed_state(ip));
50
+ native.commit(ip);
51
+ return true;
52
+ }
53
+ });
54
+ } finally {
55
+ try { if (native) native.free(); } finally { release(); }
56
+ }
57
+ }
58
+
59
+ module.exports = { withTrainingEvidence };
@@ -1,6 +1,6 @@
1
1
  const rateLimiter = require('./rateLimiter');
2
2
  const { createInspector } = require('./sqlInjection');
3
- const blacklistManager = require('./blacklistManager');
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
- blacklistManager.clear(),
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 => blacklistManager.block(ip, 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 blacklistManager.isBlocked(ip)) {
281
+ if (shouldApply('ip_keyword_block') && await blocklistManager.isBlocked(ip)) {
282
282
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
283
- console.error(`[AIWAF-BLOCK-BLACKLIST] ip=${ip}`);
283
+ console.error(`[AIWAF-BLOCK-BLOCKLIST] ip=${ip}`);
284
284
  }
285
- return deny(403, 'blocked', 'blacklist');
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 blacklistManager.isBlocked(ip)) {
414
- return deny(403, 'blocked', 'flood_or_blacklist');
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
  }
@@ -46,7 +46,8 @@ async function loadWasmFromDisk() {
46
46
  rust_payload_from_records: bg.rust_payload_from_records,
47
47
  python_feature_from_record: bg.python_feature_from_record,
48
48
  python_features_batched: bg.python_features_batched,
49
- NativeRequestPipeline: bg.NativeRequestPipeline
49
+ NativeRequestPipeline: bg.NativeRequestPipeline,
50
+ NativeTrainingEvidence: bg.NativeTrainingEvidence
50
51
  };
51
52
  }
52
53
 
@@ -528,7 +529,13 @@ async function createRequestPipeline(profile = {}, model = null) {
528
529
  if (!mod || typeof mod.NativeRequestPipeline !== 'function') {
529
530
  throw new Error('Native pipeline requires aiwaf-wasm with NativeRequestPipeline support; no fallback');
530
531
  }
531
- const native = new mod.NativeRequestPipeline(JSON.stringify(profile));
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));
532
539
  if (['begin','finish','inspect_payload','inspect_body','set_model','clear_model','diagnostics'].some(name => typeof native[name] !== 'function')) {
533
540
  native.free();
534
541
  throw new Error('Incompatible NativeRequestPipeline API; install the matching WASM build');
@@ -544,7 +551,16 @@ async function createRequestPipeline(profile = {}, model = null) {
544
551
  return { native, setModel };
545
552
  }
546
553
 
554
+ async function createTrainingEvidence(state) {
555
+ const mod = await loadWasm();
556
+ if (!mod || typeof mod.NativeTrainingEvidence !== 'function') {
557
+ throw new Error('Training replay protection requires aiwaf-wasm>=0.2.4 with NativeTrainingEvidence; install the matching build');
558
+ }
559
+ return new mod.NativeTrainingEvidence(state);
560
+ }
561
+
547
562
  module.exports = {
563
+ createTrainingEvidence,
548
564
  createRequestPipeline,
549
565
  createIsolationForest,
550
566
  createIsolationForestFromJSON,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiwaf",
3
- "version": "1.1.3",
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.3",
37
+ "aiwaf-wasm": "^0.2.5",
40
38
  "express": "^4.21.2",
41
39
  "glob": "^13.0.6",
42
40
  "knex": "^2.4.2",
@@ -66,7 +64,11 @@
66
64
  "transform": {
67
65
  "^.+\\.m?js$": [
68
66
  "babel-jest",
69
- { "plugins": ["@babel/plugin-transform-modules-commonjs"] }
67
+ {
68
+ "plugins": [
69
+ "@babel/plugin-transform-modules-commonjs"
70
+ ]
71
+ }
70
72
  ]
71
73
  },
72
74
  "transformIgnorePatterns": [