aiwaf 1.0.2 → 1.1.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.
@@ -1,4 +1,5 @@
1
1
  const rateLimiter = require('./rateLimiter');
2
+ const { createInspector } = require('./sqlInjection');
2
3
  const blacklistManager = require('./blacklistManager');
3
4
  const keywordDetector = require('./keywordDetector');
4
5
  const dynamicKeyword = require('./dynamicKeyword');
@@ -128,7 +129,20 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
128
129
 
129
130
 
130
131
  module.exports = function aiwaf(rawOpts = {}) {
132
+ if (rawOpts.AIWAF_NATIVE_PIPELINE !== undefined) {
133
+ if (Object.keys(rawOpts).some(key => key !== 'AIWAF_NATIVE_PIPELINE')) {
134
+ throw new Error('Native pipeline uses a dedicated profile; do not mix legacy options');
135
+ }
136
+ const ready = require('./nativePipeline')(rawOpts.AIWAF_NATIVE_PIPELINE);
137
+ // Compatibility wrapper for framework adapters. Await ready during application startup.
138
+ // No legacy modules are initialized and no fallback is selected on this branch.
139
+ const middleware = async (req, res, next) => (await ready)(req, res, next);
140
+ middleware.ready = ready;
141
+ middleware.inspectPayload = async req => (await ready).inspectPayload(req);
142
+ return middleware;
143
+ }
131
144
  let opts = normalizeSettings(rawOpts);
145
+ const inspectSql = createInspector(opts);
132
146
  opts.AIWAF_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_MIDDLEWARES);
133
147
  opts.AIWAF_DISABLE_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_DISABLE_MIDDLEWARES) || [];
134
148
  const pathRules = getEffectivePathRules(opts.AIWAF_PATH_RULES, { manifestPath: opts.AIWAF_PATH_MANIFEST });
@@ -174,7 +188,20 @@ module.exports = function aiwaf(rawOpts = {}) {
174
188
  ]).catch(() => {});
175
189
  }
176
190
 
177
- return async (req, res, next) => {
191
+ const inspectPayload = async req => {
192
+ const path = String(req.path || req.url || '/').split('?')[0].toLowerCase();
193
+ const ip = req.headers?.['x-forwarded-for']?.split(',')[0].trim() || req.ip;
194
+ const plan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
195
+ if (!enabledMiddlewares.has('ip_keyword_block') || !plan.shouldApply('ip_keyword_block')
196
+ || await exemptions.isExemptRequest(ip, path)) return null;
197
+ const finding = inspectSql(req);
198
+ if (finding?.mode === 'monitor') {
199
+ (opts.logger || console).warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: finding.mode });
200
+ return null;
201
+ }
202
+ return finding;
203
+ };
204
+ const middleware = async (req, res, next) => {
178
205
  const ipHdr = req.headers['x-forwarded-for'];
179
206
  const ip = ipHdr ? ipHdr.split(',')[0].trim() : req.ip;
180
207
  const path = String(req.path || req.url || '/').toLowerCase();
@@ -258,6 +285,9 @@ module.exports = function aiwaf(rawOpts = {}) {
258
285
  return deny(403, 'blocked', 'blacklist');
259
286
  }
260
287
 
288
+ const payloadFinding = await inspectPayload(req);
289
+ if (payloadFinding) return deny(payloadFinding.status, payloadFinding.rule, payloadFinding.rule);
290
+
261
291
  if (shouldApply('header_validation')) {
262
292
  const headerReason = headerValidation.validate(req);
263
293
  if (headerReason) {
@@ -372,17 +402,24 @@ module.exports = function aiwaf(rawOpts = {}) {
372
402
  }
373
403
 
374
404
  if (shouldApply('rate_limit')) {
375
- const rateOverrides = routePlan.getOverrides('RATE_LIMIT');
376
- await rateLimiter.record(ip, rateOverrides);
405
+ try {
406
+ const rateOverrides = routePlan.getOverrides('RATE_LIMIT');
407
+ await rateLimiter.record(ip, rateOverrides);
377
408
 
378
- if (await rateLimiter.isBlocked(ip, rateOverrides)) {
379
- if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
380
- console.error(`[AIWAF-BLOCK-RATE] ip=${ip}`);
409
+ if (await rateLimiter.isBlocked(ip, rateOverrides)) {
410
+ if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
411
+ console.error(`[AIWAF-BLOCK-RATE] ip=${ip}`);
412
+ }
413
+ if (await blacklistManager.isBlocked(ip)) {
414
+ return deny(403, 'blocked', 'flood_or_blacklist');
415
+ }
416
+ return deny(429, 'too_many_requests', 'rate_limit');
381
417
  }
382
- if (await blacklistManager.isBlocked(ip)) {
383
- return deny(403, 'blocked', 'flood_or_blacklist');
418
+ } catch (error) {
419
+ if (error.code === 'AIWAF_RATE_CACHE_UNAVAILABLE') {
420
+ return deny(503, 'temporarily_unavailable', 'rate_cache_unavailable');
384
421
  }
385
- return deny(429, 'too_many_requests', 'rate_limit');
422
+ throw error;
386
423
  }
387
424
  }
388
425
 
@@ -464,4 +501,6 @@ module.exports = function aiwaf(rawOpts = {}) {
464
501
 
465
502
  next();
466
503
  };
504
+ middleware.inspectPayload = inspectPayload;
505
+ return middleware;
467
506
  };
@@ -31,17 +31,22 @@ async function loadWasmFromDisk() {
31
31
  AiwafIsolationForest: bg.IsolationForest,
32
32
  IsolationForest: bg.IsolationForest,
33
33
  KeywordMatcher: bg.KeywordMatcher,
34
+ RouteMatcher: bg.RouteMatcher,
34
35
  validate_headers: bg.validate_headers,
35
36
  validate_headers_with_config: bg.validate_headers_with_config,
37
+ validate_url: bg.validate_url,
38
+ validate_content: bg.validate_content,
36
39
  analyze_recent_behavior: bg.analyze_recent_behavior,
37
40
  extract_features: bg.extract_features,
38
41
  extract_training_features: bg.extract_training_features,
42
+ extract_raw_training_features: bg.extract_raw_training_features,
39
43
  extract_features_batch_with_state: bg.extract_features_batch_with_state,
40
44
  finalize_feature_state: bg.finalize_feature_state,
41
45
  build_records: bg.build_records,
42
46
  rust_payload_from_records: bg.rust_payload_from_records,
43
47
  python_feature_from_record: bg.python_feature_from_record,
44
- python_features_batched: bg.python_features_batched
48
+ python_features_batched: bg.python_features_batched,
49
+ NativeRequestPipeline: bg.NativeRequestPipeline
45
50
  };
46
51
  }
47
52
 
@@ -395,6 +400,16 @@ async function extractWasmTrainingFeatures(records, staticKeywords = []) {
395
400
  }
396
401
  }
397
402
 
403
+ async function extractWasmRawTrainingFeatures(records, staticKeywords = [], statusIndices = []) {
404
+ const mod = await loadWasm();
405
+ if (!mod || typeof mod.extract_raw_training_features !== 'function') return null;
406
+ try {
407
+ return mod.extract_raw_training_features(records || [], staticKeywords || [], statusIndices || []);
408
+ } catch (err) {
409
+ return null;
410
+ }
411
+ }
412
+
398
413
  async function createKeywordMatcher(keywords = []) {
399
414
  const mod = await loadWasm();
400
415
  if (!mod || typeof mod.KeywordMatcher !== 'function') return null;
@@ -410,6 +425,22 @@ async function createKeywordMatcher(keywords = []) {
410
425
  }
411
426
  }
412
427
 
428
+ async function createRouteMatcher(prefixes = []) {
429
+ const mod = await loadWasm();
430
+ if (!mod || typeof mod.RouteMatcher !== 'function') return null;
431
+ try {
432
+ const matcher = new mod.RouteMatcher(prefixes);
433
+ return {
434
+ matchIndex(path) {
435
+ const index = matcher.match_index(path);
436
+ return Number.isInteger(index) ? index : null;
437
+ }
438
+ };
439
+ } catch (err) {
440
+ return null;
441
+ }
442
+ }
443
+
413
444
  async function extractWasmFeaturesBatchWithState(records, staticKeywords = [], state = null) {
414
445
  const mod = await loadWasm();
415
446
  if (!mod || typeof mod.extract_features_batch_with_state !== 'function') return null;
@@ -492,7 +523,29 @@ function getWasmStatus() {
492
523
  };
493
524
  }
494
525
 
526
+ async function createRequestPipeline(profile = {}, model = null) {
527
+ const mod = await loadWasm();
528
+ if (!mod || typeof mod.NativeRequestPipeline !== 'function') {
529
+ throw new Error('Native pipeline requires aiwaf-wasm with NativeRequestPipeline support; no fallback');
530
+ }
531
+ const native = new mod.NativeRequestPipeline(JSON.stringify(profile));
532
+ if (['begin','finish','inspect_payload','inspect_body','set_model','clear_model','diagnostics'].some(name => typeof native[name] !== 'function')) {
533
+ native.free();
534
+ throw new Error('Incompatible NativeRequestPipeline API; install the matching WASM build');
535
+ }
536
+ const setModel = value => {
537
+ if (value == null) { native.clear_model(); return; }
538
+ if (!value.__aiwafWasm || typeof value.toJSON !== 'function') throw new TypeError('A trained Rust/WASM model is required');
539
+ const Forest = mod.IsolationForest || mod.AiwafIsolationForest;
540
+ const snapshot = Forest.from_json(value.toJSON());
541
+ try { native.set_model(snapshot); } finally { snapshot.free(); }
542
+ };
543
+ try { if (model) setModel(model); } catch (error) { native.free(); throw error; }
544
+ return { native, setModel };
545
+ }
546
+
495
547
  module.exports = {
548
+ createRequestPipeline,
496
549
  createIsolationForest,
497
550
  createIsolationForestFromJSON,
498
551
  validateHeaders,
@@ -502,7 +555,9 @@ module.exports = {
502
555
  analyzeRecentBehavior,
503
556
  extractWasmFeatures,
504
557
  extractWasmTrainingFeatures,
558
+ extractWasmRawTrainingFeatures,
505
559
  createKeywordMatcher,
560
+ createRouteMatcher,
506
561
  extractWasmFeaturesBatchWithState,
507
562
  finalizeWasmFeatureState,
508
563
  buildWasmRecords,
@@ -0,0 +1,22 @@
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiwaf",
3
- "version": "1.0.2",
3
+ "version": "1.1.2",
4
4
  "description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -12,8 +12,9 @@
12
12
  "utils/",
13
13
  "train.js",
14
14
  "README.md",
15
- "INSTALLATION.md",
16
- "LICENSE"
15
+ "LICENSE",
16
+ "NOTICE",
17
+ "licenses/"
17
18
  ],
18
19
  "bin": {
19
20
  "aiwaf": "bin/aiwaf.js"
@@ -26,38 +27,51 @@
26
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",
27
28
  "aiwaf": "node bin/aiwaf.js",
28
29
  "perf:wasm": "node test/perf-wasm.js",
29
- "test:wasm-real": "node test/wasm-real.js"
30
+ "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
33
  },
31
34
  "allowScripts": {
32
35
  "sqlite3": true
33
36
  },
34
37
  "dependencies": {
35
38
  "@babel/parser": "^7.29.2",
36
- "aiwaf-wasm": "^0.2.0",
39
+ "aiwaf-wasm": "^0.2.2",
37
40
  "express": "^4.21.2",
38
- "glob": "^8.1.0",
39
- "jest": "^29.7.0",
41
+ "glob": "^13.0.6",
40
42
  "knex": "^2.4.2",
41
43
  "node-cache": "^5.1.2",
42
44
  "redis": "^4.6.5",
43
- "sqlite3": "^6.0.1",
44
- "supertest": "^7.1.0"
45
+ "sqlite3": "^6.0.1"
45
46
  },
46
47
  "devDependencies": {
47
- "fastify": "^4.29.1",
48
+ "@babel/plugin-transform-modules-commonjs": "^7.0.0",
49
+ "babel-jest": "^30.5.2",
50
+ "jest": "^30.5.2",
51
+ "supertest": "^7.1.0",
52
+ "fastify": "^5.12.7",
48
53
  "@hapi/hapi": "^21.3.12",
49
54
  "koa": "^2.15.4",
50
55
  "koa-bodyparser": "^4.4.1",
51
- "@nestjs/common": "^10.4.2",
52
- "@nestjs/core": "^10.4.2",
53
- "@nestjs/platform-express": "^10.4.2",
54
- "reflect-metadata": "^0.1.14",
56
+ "@nestjs/common": "^11.1.18",
57
+ "@nestjs/core": "^11.1.18",
58
+ "@nestjs/platform-express": "^11.1.18",
59
+ "reflect-metadata": "^0.2.2",
55
60
  "rxjs": "^7.8.1"
56
61
  },
57
62
  "jest": {
58
63
  "globalTeardown": "<rootDir>/test/jest.teardown.js",
59
64
  "forceExit": true,
60
65
  "coverageProvider": "v8",
66
+ "transform": {
67
+ "^.+\\.m?js$": [
68
+ "babel-jest",
69
+ { "plugins": ["@babel/plugin-transform-modules-commonjs"] }
70
+ ]
71
+ },
72
+ "transformIgnorePatterns": [
73
+ "node_modules[/\\\\](?!(?:.*[/\\\\])?cookie[/\\\\])"
74
+ ],
61
75
  "testPathIgnorePatterns": [
62
76
  "<rootDir>/test/wasm-adapter-real.test.js"
63
77
  ],
@@ -80,16 +94,10 @@
80
94
  "maxmind": "^4.3.0"
81
95
  },
82
96
  "overrides": {
83
- "body-parser": "^1.20.3",
84
- "qs": "^6.14.1",
85
- "path-to-regexp": "^0.1.13",
86
- "brace-expansion": "^1.1.13",
87
- "minimatch": "^5.1.8",
88
- "picomatch": "^2.3.2",
89
- "form-data": "^4.0.4",
90
- "js-yaml": "^3.14.2",
91
- "lodash": "^4.17.24",
92
- "tar-fs": "^2.1.4"
97
+ "qs": "^6.16.0",
98
+ "@istanbuljs/load-nyc-config": {
99
+ "js-yaml": "^4.1.1"
100
+ }
93
101
  },
94
102
  "keywords": [
95
103
  "waf",
@@ -106,5 +114,5 @@
106
114
  "directory": "js"
107
115
  },
108
116
  "author": "Aayush Gauba",
109
- "license": "MIT"
117
+ "license": "Elastic-2.0 AND MIT AND CC-BY-SA-4.0"
110
118
  }
package/INSTALLATION.md DELETED
@@ -1,144 +0,0 @@
1
- # AIWAF-JS Installation Guide
2
-
3
- This guide covers local setup, Redis setup, training setup, and common failure modes.
4
-
5
- ## Prerequisites
6
-
7
- - Node.js 18+ recommended
8
- - npm 9+ recommended
9
- - Build tooling required by `sqlite3` (platform dependent)
10
-
11
- ## 1. Install Package
12
-
13
- For application use:
14
-
15
- ```bash
16
- npm install aiwaf
17
- ```
18
-
19
- For local development in this repository:
20
-
21
- ```bash
22
- npm install
23
- ```
24
-
25
- ## 2. Basic Integration (Express)
26
-
27
- ```js
28
- const express = require('express');
29
- const aiwaf = require('aiwaf');
30
-
31
- const app = express();
32
- app.use(express.json());
33
-
34
- app.use(aiwaf({
35
- staticKeywords: ['.php', '.env', '.git'],
36
- dynamicTopN: 10,
37
- WINDOW_SEC: 10,
38
- MAX_REQ: 20,
39
- FLOOD_REQ: 40,
40
- HONEYPOT_FIELD: 'hp_field',
41
- uuidRoutePrefix: '/user'
42
- }));
43
- ```
44
-
45
- ## 3. Optional Redis Setup
46
-
47
- Set `REDIS_URL` (or `AIWAF_REDIS_URL`) before app startup:
48
-
49
- ```bash
50
- export REDIS_URL=redis://localhost:6379
51
- ```
52
-
53
- PowerShell:
54
-
55
- ```powershell
56
- $env:REDIS_URL = 'redis://localhost:6379'
57
- ```
58
-
59
- If Redis is not configured or not reachable, AIWAF-JS falls back to in-memory behavior.
60
-
61
- ## 3.1 Optional GeoIP MMDB Setup
62
-
63
- Install MMDB reader:
64
-
65
- ```bash
66
- npm install maxmind
67
- ```
68
-
69
- Place your database at `geolock/ipinfo_lite.mmdb` or set:
70
-
71
- ```bash
72
- export AIWAF_GEO_MMDB_PATH=/absolute/path/to/ipinfo_lite.mmdb
73
- ```
74
-
75
- ## 4. Train a Model from Logs
76
-
77
- By default, trainer reads `/var/log/nginx/access.log`. Override as needed:
78
-
79
- ```bash
80
- NODE_LOG_PATH=/path/to/access.log npm run train
81
- ```
82
-
83
- Include rotated logs:
84
-
85
- ```bash
86
- NODE_LOG_GLOB='/path/to/access.log.*' npm run train
87
- ```
88
-
89
- Output model artifact:
90
-
91
- - `resources/model.json`
92
-
93
- ## 5. Verify Installation
94
-
95
- Run tests:
96
-
97
- ```bash
98
- npm test
99
- ```
100
-
101
- Check CLI wiring:
102
-
103
- ```bash
104
- npm run aiwaf -- help
105
- ```
106
-
107
- Run a minimal app and hit a known benign route (`/`) and a suspicious route (for example path with `.php`) to validate block behavior.
108
-
109
- ## 6. Troubleshooting
110
-
111
- ### `Failed to load pretrained model`
112
-
113
- - Run `npm run train` to generate `resources/model.json`.
114
- - Ensure process has read access to the `resources/` directory.
115
-
116
- ### Redis warnings or connection failures
117
-
118
- - Verify `REDIS_URL` value and Redis server health.
119
- - Runtime is designed to continue with fallback behavior.
120
-
121
- ### SQLite errors (`blocked_ips` table not found)
122
-
123
- - Ensure process can create/write `./aiwaf.sqlite`.
124
- - `blacklistManager` auto-initializes the table, but write permissions are required.
125
- - If DB logging is unavailable, enable CSV middleware logs:
126
- - `AIWAF_MIDDLEWARE_LOG_CSV=true`
127
- - `AIWAF_MIDDLEWARE_LOG_CSV_PATH=logs/aiwaf-requests.csv`
128
- - Core tables also fall back automatically to CSV files in `logs/storage/` when DB operations fail.
129
-
130
- ### `sqlite3` install/build issues
131
-
132
- - Install platform-native build dependencies and reinstall packages.
133
- - On CI/container images, ensure compiler toolchain is present.
134
-
135
- ### Training finds no logs
136
-
137
- - Confirm `NODE_LOG_PATH` exists and is readable.
138
- - If using rotation, set `NODE_LOG_GLOB` to a valid glob.
139
-
140
- ## 7. Production Notes
141
-
142
- - Prefer Redis or a custom shared cache backend for multi-instance deployments.
143
- - Place middleware after body parsing middleware if honeypot detection is required.
144
- - Review rate limits and thresholds against real traffic profiles before broad rollout.