aiwaf 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,8 @@
1
1
  const rateLimiter = require('./rateLimiter');
2
2
  const { createInspector } = require('./sqlInjection');
3
- const blacklistManager = require('./blacklistManager');
3
+ const wasmChecks = require('./wasmChecks');
4
+ const routeRisks = require('./routeRisks');
5
+ const blocklistManager = require('./blocklistManager');
4
6
  const keywordDetector = require('./keywordDetector');
5
7
  const dynamicKeyword = require('./dynamicKeyword');
6
8
  const dynamicKeywordStore = require('./dynamicKeywordStore');
@@ -12,7 +14,7 @@ const geoBlocker = require('./geoBlocker');
12
14
  const middlewareLogger = require('./middlewareLogger');
13
15
  const exemptions = require('./exemptions');
14
16
  const requestLogStore = require('./requestLogStore');
15
- const { extractExtendedRequestInfo } = require('./runtimeUtils');
17
+ const { extractExtendedRequestInfo, getRequestIp } = require('./runtimeUtils');
16
18
  const { extractFeatures, init: initFeatureUtils, markRequestStart, STATIC_KW } = require('./featureUtils');
17
19
  const { normalizeSettings } = require('./settingsCompat');
18
20
  const {
@@ -146,6 +148,10 @@ module.exports = function aiwaf(rawOpts = {}) {
146
148
  opts.AIWAF_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_MIDDLEWARES);
147
149
  opts.AIWAF_DISABLE_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_DISABLE_MIDDLEWARES) || [];
148
150
  const pathRules = getEffectivePathRules(opts.AIWAF_PATH_RULES, { manifestPath: opts.AIWAF_PATH_MANIFEST });
151
+ const observeRisks = routeRisks.createObserver(opts);
152
+ // The SQL check and route checks run in aiwaf-wasm. Requests wait for it, and fail if it's missing.
153
+ const checksReady = wasmChecks.load();
154
+ checksReady.catch(() => {});
149
155
 
150
156
  let enabledMiddlewares = planEnabledMiddlewares({
151
157
  orderedAvailable: [
@@ -182,7 +188,7 @@ module.exports = function aiwaf(rawOpts = {}) {
182
188
 
183
189
  if (opts.AIWAF_CLEAR_STATE_ON_START) {
184
190
  Promise.allSettled([
185
- blacklistManager.clear(),
191
+ blocklistManager.clear(),
186
192
  requestLogStore.clear(),
187
193
  dynamicKeywordStore.clear()
188
194
  ]).catch(() => {});
@@ -190,10 +196,13 @@ module.exports = function aiwaf(rawOpts = {}) {
190
196
 
191
197
  const inspectPayload = async req => {
192
198
  const path = String(req.path || req.url || '/').split('?')[0].toLowerCase();
193
- const ip = req.headers?.['x-forwarded-for']?.split(',')[0].trim() || req.ip;
199
+ const ip = getRequestIp(req, opts.AIWAF_TRUSTED_PROXIES);
194
200
  const plan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
195
201
  if (!enabledMiddlewares.has('ip_keyword_block') || !plan.shouldApply('ip_keyword_block')
196
202
  || await exemptions.isExemptRequest(ip, path)) return null;
203
+ await checksReady;
204
+ const riskFinding = observeRisks ? observeRisks(req) : null;
205
+ if (riskFinding) return riskFinding;
197
206
  const finding = inspectSql(req);
198
207
  if (finding?.mode === 'monitor') {
199
208
  (opts.logger || console).warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: finding.mode });
@@ -202,8 +211,9 @@ module.exports = function aiwaf(rawOpts = {}) {
202
211
  return finding;
203
212
  };
204
213
  const middleware = async (req, res, next) => {
205
- const ipHdr = req.headers['x-forwarded-for'];
206
- const ip = ipHdr ? ipHdr.split(',')[0].trim() : req.ip;
214
+ const ip = getRequestIp(req, opts.AIWAF_TRUSTED_PROXIES);
215
+ // Geo checks and logging must judge the same address as this middleware.
216
+ req.aiwafClientIp = ip;
207
217
  const path = String(req.path || req.url || '/').toLowerCase();
208
218
  const method = String(req.method || 'GET').toUpperCase();
209
219
  if (isAutoSelection(opts.AIWAF_MIDDLEWARES)) {
@@ -229,7 +239,7 @@ module.exports = function aiwaf(rawOpts = {}) {
229
239
  }
230
240
  const routePlan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
231
241
  const shouldApply = name => enabledMiddlewares.has(normalizeMiddlewareName(name)) && routePlan.shouldApply(name);
232
- const blockIp = reason => blacklistManager.block(ip, reason, {
242
+ const blockIp = reason => blocklistManager.block(ip, reason, {
233
243
  extendedRequestInfo: extractExtendedRequestInfo(req, {
234
244
  enabled: opts.AIWAF_CAPTURE_EXTENDED_REQUEST_INFO,
235
245
  maxHeaders: opts.AIWAF_EXTENDED_INFO_MAX_HEADERS,
@@ -278,11 +288,11 @@ module.exports = function aiwaf(rawOpts = {}) {
278
288
  return next();
279
289
  }
280
290
 
281
- if (shouldApply('ip_keyword_block') && await blacklistManager.isBlocked(ip)) {
291
+ if (shouldApply('ip_keyword_block') && await blocklistManager.isBlocked(ip)) {
282
292
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
283
- console.error(`[AIWAF-BLOCK-BLACKLIST] ip=${ip}`);
293
+ console.error(`[AIWAF-BLOCK-BLOCKLIST] ip=${ip}`);
284
294
  }
285
- return deny(403, 'blocked', 'blacklist');
295
+ return deny(403, 'blocked', 'blocklist');
286
296
  }
287
297
 
288
298
  const payloadFinding = await inspectPayload(req);
@@ -410,8 +420,8 @@ module.exports = function aiwaf(rawOpts = {}) {
410
420
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
411
421
  console.error(`[AIWAF-BLOCK-RATE] ip=${ip}`);
412
422
  }
413
- if (await blacklistManager.isBlocked(ip)) {
414
- return deny(403, 'blocked', 'flood_or_blacklist');
423
+ if (await blocklistManager.isBlocked(ip)) {
424
+ return deny(403, 'blocked', 'flood_or_blocklist');
415
425
  }
416
426
  return deny(429, 'too_many_requests', 'rate_limit');
417
427
  }
@@ -47,7 +47,13 @@ async function loadWasmFromDisk() {
47
47
  python_feature_from_record: bg.python_feature_from_record,
48
48
  python_features_batched: bg.python_features_batched,
49
49
  NativeRequestPipeline: bg.NativeRequestPipeline,
50
- NativeTrainingEvidence: bg.NativeTrainingEvidence
50
+ NativeTrainingEvidence: bg.NativeTrainingEvidence,
51
+ RouteRiskChecker: bg.RouteRiskChecker,
52
+ route_rule: bg.route_rule,
53
+ sql_inspect: bg.sql_inspect,
54
+ sql_inspect_headers: bg.sql_inspect_headers,
55
+ sql_inspect_path: bg.sql_inspect_path,
56
+ sql_tokenizer: bg.sql_tokenizer
51
57
  };
52
58
  }
53
59
 
@@ -529,7 +535,13 @@ async function createRequestPipeline(profile = {}, model = null) {
529
535
  if (!mod || typeof mod.NativeRequestPipeline !== 'function') {
530
536
  throw new Error('Native pipeline requires aiwaf-wasm with NativeRequestPipeline support; no fallback');
531
537
  }
532
- const native = new mod.NativeRequestPipeline(JSON.stringify(profile));
538
+ // Retain the existing wire key so published WASM companions remain compatible.
539
+ const wireProfile = { ...profile };
540
+ if (Object.hasOwn(wireProfile, 'blocklist')) {
541
+ wireProfile.blacklist = wireProfile.blocklist;
542
+ delete wireProfile.blocklist;
543
+ }
544
+ const native = new mod.NativeRequestPipeline(JSON.stringify(wireProfile));
533
545
  if (['begin','finish','inspect_payload','inspect_body','set_model','clear_model','diagnostics'].some(name => typeof native[name] !== 'function')) {
534
546
  native.free();
535
547
  throw new Error('Incompatible NativeRequestPipeline API; install the matching WASM build');
@@ -554,6 +566,7 @@ async function createTrainingEvidence(state) {
554
566
  }
555
567
 
556
568
  module.exports = {
569
+ loadWasm,
557
570
  createTrainingEvidence,
558
571
  createRequestPipeline,
559
572
  createIsolationForest,
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ // The SQL check and route checks run in aiwaf-wasm, which Node.js requires, as Python requires
4
+ // aiwaf-rust. There is no JavaScript copy. Call load() once before the first check.
5
+ const NEEDED = ['sql_inspect', 'sql_inspect_headers', 'sql_inspect_path', 'sql_tokenizer', 'route_rule', 'RouteRiskChecker'];
6
+ const MESSAGE = "AIWAF's request checks need aiwaf-wasm 0.2.6 or newer. Run: npm install aiwaf-wasm@^0.2.6";
7
+
8
+ let pending = null;
9
+ let loaded = null;
10
+
11
+ function check(mod) {
12
+ if (!mod || NEEDED.some(name => typeof mod[name] !== 'function')) throw new Error(MESSAGE);
13
+ return mod;
14
+ }
15
+
16
+ /** Loads aiwaf-wasm once. Rejects with an install hint when it's missing or too old. */
17
+ function load() {
18
+ if (!pending) {
19
+ pending = require('./wasmAdapter').loadWasm().then(mod => {
20
+ loaded = check(mod);
21
+ return loaded;
22
+ });
23
+ // A failed load is reported to whoever awaits it, and retried on the next call.
24
+ pending.catch(() => { pending = null; });
25
+ }
26
+ return pending;
27
+ }
28
+
29
+ /** Returns the loaded module. Throws when load() hasn't finished. */
30
+ function get() {
31
+ if (!loaded) throw new Error(`aiwaf-wasm isn't loaded yet. Await its load() first. ${MESSAGE}`);
32
+ return loaded;
33
+ }
34
+
35
+ /** Returns the loaded module, or null when load() hasn't finished. */
36
+ function loadedModule() {
37
+ return loaded;
38
+ }
39
+
40
+ module.exports = { load, get, loadedModule, MESSAGE };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiwaf",
3
- "version": "1.1.4",
3
+ "version": "1.1.6",
4
4
  "description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -22,23 +22,21 @@
22
22
  "scripts": {
23
23
  "retrain": "AIWAF_LOG_PATH=/var/log/nginx/access.log npm run train",
24
24
  "train": "node train.js",
25
- "test": "jest --runInBand",
26
- "test:coverage": "jest --runInBand --coverage",
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",
25
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand",
26
+ "test:coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --runInBand --coverage",
27
+ "test:wasm": "node --experimental-vm-modules node_modules/jest/bin/jest.js --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.4",
37
+ "aiwaf-wasm": "^0.2.6",
40
38
  "express": "^4.21.2",
41
- "glob": "^13.0.6",
39
+ "glob": "^14.0.6",
42
40
  "knex": "^2.4.2",
43
41
  "node-cache": "^5.1.2",
44
42
  "redis": "^4.6.5",
@@ -59,41 +57,6 @@
59
57
  "reflect-metadata": "^0.2.2",
60
58
  "rxjs": "^7.8.1"
61
59
  },
62
- "jest": {
63
- "globalTeardown": "<rootDir>/test/jest.teardown.js",
64
- "forceExit": true,
65
- "coverageProvider": "v8",
66
- "transform": {
67
- "^.+\\.m?js$": [
68
- "babel-jest",
69
- {
70
- "plugins": [
71
- "@babel/plugin-transform-modules-commonjs"
72
- ]
73
- }
74
- ]
75
- },
76
- "transformIgnorePatterns": [
77
- "node_modules[/\\\\](?!(?:.*[/\\\\])?cookie[/\\\\])"
78
- ],
79
- "testPathIgnorePatterns": [
80
- "<rootDir>/test/wasm-adapter-real.test.js"
81
- ],
82
- "collectCoverageFrom": [
83
- "index.js",
84
- "train.js",
85
- "lib/**/*.js",
86
- "utils/**/*.js"
87
- ],
88
- "coverageThreshold": {
89
- "global": {
90
- "branches": 66,
91
- "functions": 100,
92
- "lines": 80,
93
- "statements": 80
94
- }
95
- }
96
- },
97
60
  "optionalDependencies": {
98
61
  "maxmind": "^4.3.0"
99
62
  },
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 blacklistManager = require('./lib/blacklistManager');
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 blacklistManager.unblock(ip);
239
+ await blocklistManager.unblock(ip);
240
240
  }
241
- console.log(`Cleared ${ips.length} exempt IPs from blacklist`);
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, () => blacklistManager.block(ip, `Excessive 404s (non-login ${count}/${count + loginCount})`));
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, () => blacklistManager.block(ip, `AI anomaly + suspicious patterns (kw:${avgKwHits.toFixed(1)}, 404s:${max404s}, burst:${avgBurst.toFixed(1)})`));
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 blacklistManager.getBlockedIPs();
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