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.
@@ -30,10 +30,16 @@ async function loadWasmFromDisk() {
30
30
  return {
31
31
  AiwafIsolationForest: bg.IsolationForest,
32
32
  IsolationForest: bg.IsolationForest,
33
+ KeywordMatcher: bg.KeywordMatcher,
34
+ RouteMatcher: bg.RouteMatcher,
33
35
  validate_headers: bg.validate_headers,
34
36
  validate_headers_with_config: bg.validate_headers_with_config,
37
+ validate_url: bg.validate_url,
38
+ validate_content: bg.validate_content,
35
39
  analyze_recent_behavior: bg.analyze_recent_behavior,
36
40
  extract_features: bg.extract_features,
41
+ extract_training_features: bg.extract_training_features,
42
+ extract_raw_training_features: bg.extract_raw_training_features,
37
43
  extract_features_batch_with_state: bg.extract_features_batch_with_state,
38
44
  finalize_feature_state: bg.finalize_feature_state,
39
45
  build_records: bg.build_records,
@@ -219,8 +225,9 @@ function normalizeValidationResult(result, fallbackReason) {
219
225
 
220
226
  function normalizeRecentEntries(entries = []) {
221
227
  return (Array.isArray(entries) ? entries : []).map(entry => {
222
- const rawTimestamp = Number(entry.timestamp ?? entry.timestamp_epoch ?? Date.now());
223
- const timestamp = rawTimestamp > 1000000000000 ? rawTimestamp / 1000 : rawTimestamp;
228
+ const hasMilliseconds = entry.timestamp_ms !== undefined && entry.timestamp_ms !== null;
229
+ const rawTimestamp = Number(hasMilliseconds ? entry.timestamp_ms : (entry.timestamp ?? entry.timestamp_epoch ?? Date.now()));
230
+ const timestamp = (hasMilliseconds || rawTimestamp > 1000000000000) ? rawTimestamp / 1000 : rawTimestamp;
224
231
  return {
225
232
  path_lower: String(entry.path_lower || entry.path || '').toLowerCase(),
226
233
  timestamp: Number.isFinite(timestamp) ? timestamp : Date.now() / 1000,
@@ -382,6 +389,57 @@ async function extractWasmFeatures(records, staticKeywords = []) {
382
389
  }
383
390
  }
384
391
 
392
+ async function extractWasmTrainingFeatures(records, staticKeywords = []) {
393
+ const mod = await loadWasm();
394
+ if (!mod || typeof mod.extract_training_features !== 'function') return null;
395
+ try {
396
+ return mod.extract_training_features(records || [], staticKeywords || []);
397
+ } catch (err) {
398
+ return null;
399
+ }
400
+ }
401
+
402
+ async function extractWasmRawTrainingFeatures(records, staticKeywords = [], statusIndices = []) {
403
+ const mod = await loadWasm();
404
+ if (!mod || typeof mod.extract_raw_training_features !== 'function') return null;
405
+ try {
406
+ return mod.extract_raw_training_features(records || [], staticKeywords || [], statusIndices || []);
407
+ } catch (err) {
408
+ return null;
409
+ }
410
+ }
411
+
412
+ async function createKeywordMatcher(keywords = []) {
413
+ const mod = await loadWasm();
414
+ if (!mod || typeof mod.KeywordMatcher !== 'function') return null;
415
+ try {
416
+ const matcher = new mod.KeywordMatcher(keywords);
417
+ return {
418
+ firstMatch(path) {
419
+ return matcher.first_match(path) || null;
420
+ }
421
+ };
422
+ } catch (err) {
423
+ return null;
424
+ }
425
+ }
426
+
427
+ async function createRouteMatcher(prefixes = []) {
428
+ const mod = await loadWasm();
429
+ if (!mod || typeof mod.RouteMatcher !== 'function') return null;
430
+ try {
431
+ const matcher = new mod.RouteMatcher(prefixes);
432
+ return {
433
+ matchIndex(path) {
434
+ const index = matcher.match_index(path);
435
+ return Number.isInteger(index) ? index : null;
436
+ }
437
+ };
438
+ } catch (err) {
439
+ return null;
440
+ }
441
+ }
442
+
385
443
  async function extractWasmFeaturesBatchWithState(records, staticKeywords = [], state = null) {
386
444
  const mod = await loadWasm();
387
445
  if (!mod || typeof mod.extract_features_batch_with_state !== 'function') return null;
@@ -473,6 +531,10 @@ module.exports = {
473
531
  validateRecent,
474
532
  analyzeRecentBehavior,
475
533
  extractWasmFeatures,
534
+ extractWasmTrainingFeatures,
535
+ extractWasmRawTrainingFeatures,
536
+ createKeywordMatcher,
537
+ createRouteMatcher,
476
538
  extractWasmFeaturesBatchWithState,
477
539
  finalizeWasmFeatureState,
478
540
  buildWasmRecords,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiwaf",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -12,7 +12,6 @@
12
12
  "utils/",
13
13
  "train.js",
14
14
  "README.md",
15
- "INSTALLATION.md",
16
15
  "LICENSE"
17
16
  ],
18
17
  "bin": {
@@ -36,14 +35,14 @@
36
35
  "aiwaf-wasm": "^0.2.0",
37
36
  "express": "^4.21.2",
38
37
  "glob": "^8.1.0",
39
- "jest": "^29.7.0",
40
38
  "knex": "^2.4.2",
41
39
  "node-cache": "^5.1.2",
42
40
  "redis": "^4.6.5",
43
- "sqlite3": "^6.0.1",
44
- "supertest": "^7.1.0"
41
+ "sqlite3": "^6.0.1"
45
42
  },
46
43
  "devDependencies": {
44
+ "jest": "^29.7.0",
45
+ "supertest": "^7.1.0",
47
46
  "fastify": "^4.29.1",
48
47
  "@hapi/hapi": "^21.3.12",
49
48
  "koa": "^2.15.4",
@@ -102,7 +101,7 @@
102
101
  ],
103
102
  "repository": {
104
103
  "type": "git",
105
- "url": "git+https://github.com/aayushgauba/aiwaf.git",
104
+ "url": "git+https://github.com/aiwaf-project/aiwaf.git",
106
105
  "directory": "js"
107
106
  },
108
107
  "author": "Aayush Gauba",
package/train.js CHANGED
@@ -3,10 +3,11 @@ const path = require('path');
3
3
  const glob = require('glob');
4
4
  const zlib = require('zlib');
5
5
  const readline = require('readline');
6
- const { IsolationForest } = require('./lib/isolationForest');
6
+ const { createIsolationForest } = require('./lib/wasmAdapter');
7
7
  const requestLogStore = require('./lib/requestLogStore');
8
8
  const modelStore = require('./lib/modelStore');
9
9
  const blacklistManager = require('./lib/blacklistManager');
10
+ const { calculateTrainingFeatures } = require('./lib/trainingFeatures');
10
11
 
11
12
  const STATIC_KW = [
12
13
  '.php', '.xmlrpc', 'wp-', '.env', '.git', '.bak',
@@ -387,48 +388,6 @@ function parseDbEvent(event) {
387
388
  };
388
389
  }
389
390
 
390
- function calculateFeatures(parsedRequests) {
391
- const ipRequests = new Map();
392
- const ip404Counts = new Map();
393
-
394
- for (const req of parsedRequests) {
395
- if (!ipRequests.has(req.ip)) {
396
- ipRequests.set(req.ip, []);
397
- }
398
- ipRequests.get(req.ip).push(req);
399
-
400
- if (req.status === '404') {
401
- ip404Counts.set(req.ip, (ip404Counts.get(req.ip) || 0) + 1);
402
- }
403
- }
404
-
405
- const features = [];
406
-
407
- for (const req of parsedRequests) {
408
- const pathLen = req.path.length;
409
-
410
- const kwHits = STATIC_KW.reduce(
411
- (sum, kw) => sum + (req.path.toLowerCase().includes(kw) ? 1 : 0),
412
- 0
413
- );
414
-
415
- const statusIdx = STATUS_IDX.indexOf(req.status) >= 0
416
- ? STATUS_IDX.indexOf(req.status)
417
- : -1;
418
-
419
- const respTime = req.responseTime;
420
-
421
- const ipReqs = ipRequests.get(req.ip);
422
- const burst = ipReqs.filter(item => Math.abs(item.timestamp.getTime() - req.timestamp.getTime()) <= 10000).length;
423
-
424
- const total404 = ip404Counts.get(req.ip) || 0;
425
-
426
- features.push([pathLen, kwHits, statusIdx, respTime, burst, total404]);
427
- }
428
-
429
- return features;
430
- }
431
-
432
391
  (async () => {
433
392
  try {
434
393
  const rawAccessLines = await readAccessLogLines();
@@ -497,7 +456,7 @@ function calculateFeatures(parsedRequests) {
497
456
 
498
457
  console.log(`Parsed ${parsedRequests.length} valid requests`);
499
458
 
500
- const features = calculateFeatures(parsedRequests);
459
+ const features = await calculateTrainingFeatures(parsedRequests, STATIC_KW, STATUS_IDX);
501
460
  if (features.length === 0) {
502
461
  console.warn('No features generated.');
503
462
  return;
@@ -510,18 +469,18 @@ function calculateFeatures(parsedRequests) {
510
469
 
511
470
  let anomalyIps = new Set();
512
471
  if (parsedRequests.length >= MIN_AI_LOGS || FORCE_TRAINING) {
513
- const model = new IsolationForest({ nTrees: 100, sampleSize: 256 });
472
+ const model = await createIsolationForest({ nTrees: 100, sampleSize: 256 });
514
473
  model.fit(features);
515
474
 
516
- const modelData = {
517
- ...model.toJSON(),
518
- metadata: {
519
- createdAt: new Date().toISOString(),
520
- samplesCount: features.length,
521
- featureCount: 6,
522
- version: '1.1'
523
- }
475
+ const metadata = {
476
+ createdAt: new Date().toISOString(),
477
+ samplesCount: features.length,
478
+ featureCount: 6,
479
+ version: '1.1'
524
480
  };
481
+ const modelData = model.__aiwafWasm
482
+ ? { model_type: 'aiwaf_wasm.IsolationForest', model_state: model.toJSON(), metadata }
483
+ : { ...model.toJSON(), metadata };
525
484
 
526
485
  await modelStore.save(process.env, modelData, modelData.metadata);
527
486
  console.log(`Trained on ${features.length} samples`);
package/utils/cache.js CHANGED
@@ -1,3 +1,3 @@
1
- const NodeCache = require('node-cache');
2
- const redis = require('redis');
1
+ const NodeCache = require('node-cache');
2
+ const redis = require('redis');
3
3
  module.exports = (useRedis=false) => useRedis ? redis.createClient() : new NodeCache();
package/utils/db.js CHANGED
@@ -1,11 +1,11 @@
1
- const knex = require('knex');
2
-
3
- const isTest = process.env.NODE_ENV === 'test';
4
-
5
- module.exports = knex({
6
- client: 'sqlite3',
7
- connection: {
8
- filename: isTest ? ':memory:' : './aiwaf.sqlite'
9
- },
10
- useNullAsDefault: true,
1
+ const knex = require('knex');
2
+
3
+ const isTest = process.env.NODE_ENV === 'test';
4
+
5
+ module.exports = knex({
6
+ client: 'sqlite3',
7
+ connection: {
8
+ filename: isTest ? ':memory:' : './aiwaf.sqlite'
9
+ },
10
+ useNullAsDefault: true,
11
11
  });
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.