aiwaf 1.0.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.
Files changed (50) hide show
  1. package/INSTALLATION.md +144 -0
  2. package/LICENSE +21 -0
  3. package/README.md +621 -0
  4. package/bin/aiwaf.js +349 -0
  5. package/index.js +62 -0
  6. package/lib/adonisMiddleware.js +82 -0
  7. package/lib/anomalyDetector.js +221 -0
  8. package/lib/blacklistManager.js +134 -0
  9. package/lib/blockResponses.js +25 -0
  10. package/lib/csvStore.js +84 -0
  11. package/lib/dynamicKeyword.js +42 -0
  12. package/lib/dynamicKeywordStore.js +169 -0
  13. package/lib/exemptionStore.js +204 -0
  14. package/lib/exemptions.js +56 -0
  15. package/lib/fastifyPlugin.js +49 -0
  16. package/lib/featureUtils.js +183 -0
  17. package/lib/geoBlocker.js +159 -0
  18. package/lib/geoPolicy.js +42 -0
  19. package/lib/geoStore.js +111 -0
  20. package/lib/hapiPlugin.js +92 -0
  21. package/lib/headerValidation.js +275 -0
  22. package/lib/honeypotDetector.js +91 -0
  23. package/lib/isolationForest.js +117 -0
  24. package/lib/keywordDetector.js +5 -0
  25. package/lib/keywordFallbackStore.js +39 -0
  26. package/lib/koaMiddleware.js +68 -0
  27. package/lib/middlewareLogger.js +123 -0
  28. package/lib/middlewarePlan.js +72 -0
  29. package/lib/modelSecurity.js +17 -0
  30. package/lib/modelStore.js +129 -0
  31. package/lib/nestMiddleware.js +12 -0
  32. package/lib/nextMiddleware.js +78 -0
  33. package/lib/pathManifest.js +533 -0
  34. package/lib/pathRules.js +184 -0
  35. package/lib/rateLimiter.js +153 -0
  36. package/lib/redisClient.js +35 -0
  37. package/lib/requestLogStore.js +167 -0
  38. package/lib/runtimeUtils.js +166 -0
  39. package/lib/settingsCompat.js +140 -0
  40. package/lib/sourceAst.js +294 -0
  41. package/lib/trainingLogic.js +87 -0
  42. package/lib/uuidDetector.js +46 -0
  43. package/lib/wafMiddleware.js +459 -0
  44. package/lib/wasmAdapter.js +480 -0
  45. package/lib/whois.js +38 -0
  46. package/package.json +85 -0
  47. package/resources/model.json +9536 -0
  48. package/train.js +595 -0
  49. package/utils/cache.js +3 -0
  50. package/utils/db.js +11 -0
package/README.md ADDED
@@ -0,0 +1,621 @@
1
+ # aiwaf
2
+
3
+ AIWAF-JS is a Node.js/Express Web Application Firewall that combines deterministic protections with anomaly detection and continuous learning. It ships as middleware, a CLI for ops workflows, and an offline trainer for IsolationForest models.
4
+ Supported frameworks: Express (native), Fastify, Hapi, Koa, NestJS (Express/Fastify wrappers), Next.js (API route wrapper), AdonisJS, and Sails.js.
5
+
6
+ ## What It Does
7
+
8
+ - Blocks known bad traffic with static keyword rules and IP blacklisting
9
+ - Enforces rate limits with flood detection
10
+ - Detects bot-like form abuse using honeypot field checks and timing gates
11
+ - Enforces optional method policies (405) and suspicious method usage
12
+ - Blocks suspicious UUID probing on route prefixes (with optional existence resolver)
13
+ - Learns high-frequency malicious segments as dynamic suspicious keywords
14
+ - Runs IsolationForest anomaly checks with recent-behavior analysis
15
+ - Supports Redis/custom cache backends with memory fallback
16
+ - Optional GeoIP blocking (MMDB) with allow/block lists and dynamic blocklist
17
+ - CSV fallback storage when DB is unavailable
18
+ - Operational CLI for blacklist, exemptions, geo, request logs, training and diagnostics
19
+
20
+ ## Repository Layout
21
+
22
+ - `index.js`: package entrypoint
23
+ - `lib/wafMiddleware.js`: main middleware orchestration
24
+ - `lib/rateLimiter.js`: rate-window and flood logic
25
+ - `lib/blacklistManager.js`: blocked IP persistence and operations
26
+ - `lib/keywordDetector.js`: static keyword checks
27
+ - `lib/dynamicKeyword.js`: in-memory dynamic keyword learning/checking
28
+ - `lib/uuidDetector.js`: UUID tamper detection
29
+ - `lib/honeypotDetector.js`: honeypot trap detection
30
+ - `lib/anomalyDetector.js`: pretrained model loading and anomaly scoring
31
+ - `lib/featureUtils.js`: request feature extraction and short-lived caching
32
+ - `lib/isolationForest.js`: IsolationForest implementation
33
+ - `lib/redisClient.js`: optional Redis client lifecycle
34
+ - `lib/headerValidation.js`: header caps, suspicious UA, and header quality scoring
35
+ - `lib/geoBlocker.js`: GeoIP allow/block checks + MMDB lookup + cache
36
+ - `lib/middlewareLogger.js`: JSONL/CSV/DB request logging
37
+ - `lib/*Store.js`: DB/CSV storage adapters (blacklist, exemptions, geo, logs, keywords, models)
38
+ - `train.js`: offline model training from access logs
39
+ - `resources/model.json`: pretrained anomaly model artifact
40
+ - `utils/db.js`: SQLite connection (memory DB in test)
41
+ - `test/`: Jest test suite
42
+
43
+ ## Request Processing Flow
44
+
45
+ 1. Initialize module options for rate limiter, keyword detectors, honeypot, UUID checks, and anomaly detector.
46
+ 2. Resolve client IP (`x-forwarded-for` first, then `req.ip`) and normalized path.
47
+ 3. Enforce optional method policy (405) if enabled.
48
+ 4. Block immediately if IP is already in blacklist.
49
+ 5. Header validation (required headers, suspicious UA, header caps, quality score).
50
+ 6. Geo checks (allow/block lists + DB-backed blocklist).
51
+ 7. Honeypot field + timing checks.
52
+ 8. Rate-limit + flood handling.
53
+ 9. Static keyword blocking.
54
+ 10. Dynamic keyword blocking.
55
+ 11. UUID tamper checks (optional existence resolver).
56
+ 12. Anomaly detection for unknown routes with recent-behavior analysis.
57
+ 13. Request logging (JSONL/CSV/DB) and optional dynamic keyword learning on 404s.
58
+ 14. Allow request through `next()` when no rule triggers.
59
+
60
+ ## Installation
61
+
62
+ ```bash
63
+ npm install aiwaf
64
+ ```
65
+
66
+ ### Optional WASM Acceleration
67
+
68
+ AIWAF can use the `aiwaf-wasm` optional dependency for faster IsolationForest scoring and deterministic feature validation.
69
+ If the WASM module fails to load, it automatically falls back to the JS implementation.
70
+
71
+ ```bash
72
+ npm install aiwaf-wasm
73
+ ```
74
+
75
+ ## Quick Start
76
+
77
+ ```js
78
+ const express = require('express');
79
+ const aiwaf = require('aiwaf');
80
+
81
+ const app = express();
82
+ app.use(express.json());
83
+
84
+ app.use(aiwaf({
85
+ staticKeywords: ['.php', '.env', '.git'],
86
+ dynamicTopN: 10,
87
+ WINDOW_SEC: 10,
88
+ MAX_REQ: 20,
89
+ FLOOD_REQ: 40,
90
+ HONEYPOT_FIELD: 'hp_field',
91
+ uuidRoutePrefix: '/user',
92
+ AIWAF_HEADER_VALIDATION: true,
93
+ AIWAF_METHOD_POLICY_ENABLED: true,
94
+ AIWAF_ALLOWED_METHODS: ['GET', 'POST', 'HEAD', 'OPTIONS']
95
+ }));
96
+
97
+ app.get('/', (req, res) => res.send('Protected'));
98
+ app.listen(3000);
99
+ ```
100
+
101
+ ## Path Rules and Auto Middleware
102
+
103
+ Use path rules to disable selected AIWAF checks or override rate limits for a route prefix:
104
+
105
+ ```js
106
+ app.use(aiwaf({
107
+ AIWAF_PATH_RULES: [
108
+ { PREFIX: '/health/', DISABLE: ['header_validation', 'rate_limit'] },
109
+ { PREFIX: '/api/public/', RATE_LIMIT: { WINDOW: 60, MAX: 300 } }
110
+ ]
111
+ }));
112
+ ```
113
+
114
+ `DISABLE` accepts canonical names such as `ip_keyword_block`, `rate_limit`, `honeypot`, `header_validation`, `geo_block`, `ai_anomaly`, `uuid_tamper`, and `logging`. Class-style names like `HeaderValidationMiddleware` are also accepted.
115
+
116
+ AIWAF can also read a generated route manifest from `.aiwaf/paths.json` and compile route protections into path rules. For Express apps, generate one after routes are registered. Route extraction uses a Babel-backed JavaScript AST parser, with a conservative string heuristic fallback, to infer API/form/auth signals from handlers:
117
+
118
+ ```js
119
+ const manifest = aiwaf.generateExpressManifest(app, '.aiwaf/paths.json');
120
+ ```
121
+
122
+ Other frameworks can use `generateFrameworkManifest(framework, app, output, { routes })`. Express/Sails can be introspected from the app, Hapi can be introspected from `server.table()`, and Fastify/Koa/Next/Nest can also accept explicit route lists:
123
+
124
+ ```js
125
+ aiwaf.generateFrameworkManifest('fastify', null, '.aiwaf/paths.json', {
126
+ routes: [
127
+ { method: 'GET', path: '/api/users', handler: usersHandler },
128
+ { method: 'POST', path: '/contact', handler: contactHandler }
129
+ ]
130
+ });
131
+ ```
132
+
133
+ The CLI can generate a manifest from a JSON route list:
134
+
135
+ ```bash
136
+ npm run aiwaf -- manifest --framework express --routes routes.json --output .aiwaf/paths.json
137
+ ```
138
+
139
+ The Rust/WASM helper surface is available under `aiwaf.wasm` for advanced integrations:
140
+
141
+ ```js
142
+ const aiwaf = require('aiwaf');
143
+
144
+ const model = await aiwaf.wasm.createIsolationForest({ nTrees: 100 });
145
+ const features = await aiwaf.wasm.extractWasmFeatures(records, ['.php', '.env']);
146
+ const recent = await aiwaf.wasm.analyzeRecentBehavior(entries, ['.php']);
147
+ ```
148
+
149
+ Python-parity helper modules are exposed for advanced integrations:
150
+
151
+ ```js
152
+ aiwaf.runtimeUtils.isStaticFile('/assets/app.css');
153
+ aiwaf.trainingLogic.isScanningPath('/wp-admin/install.php');
154
+ aiwaf.geoPolicy.evaluateGeoPolicy({ country: 'US', allowCountries: ['US'] });
155
+ aiwaf.blockResponses.blockedPayload('blocked by AIWAF');
156
+ ```
157
+
158
+ Use `auto`/`all` middleware selection to enable the canonical protection set while skipping middleware that is not useful for the current app signals:
159
+
160
+ ```js
161
+ app.use(aiwaf.auto({
162
+ AIWAF_DISABLE_MIDDLEWARES: ['geo_block']
163
+ }));
164
+ // Equivalent:
165
+ app.use(aiwaf({ AIWAF_MIDDLEWARES: ['auto'] }));
166
+ ```
167
+
168
+ ## Fastify Usage
169
+
170
+ ```js
171
+ const fastify = require('fastify')({ logger: true });
172
+ const aiwaf = require('aiwaf');
173
+
174
+ fastify.register(aiwaf.fastify, {
175
+ staticKeywords: ['.php', '.env', '.git'],
176
+ dynamicTopN: 10,
177
+ WINDOW_SEC: 10,
178
+ MAX_REQ: 20,
179
+ FLOOD_REQ: 40,
180
+ HONEYPOT_FIELD: 'hp_field'
181
+ });
182
+
183
+ fastify.get('/', async () => 'Protected');
184
+ fastify.listen({ port: 3000 });
185
+ ```
186
+
187
+ ## Hapi Usage
188
+
189
+ ```js
190
+ const Hapi = require('@hapi/hapi');
191
+ const aiwaf = require('aiwaf');
192
+
193
+ const server = Hapi.server({ port: 3000 });
194
+ await server.register({
195
+ plugin: aiwaf.hapi,
196
+ options: {
197
+ staticKeywords: ['.php', '.env', '.git'],
198
+ dynamicTopN: 10,
199
+ WINDOW_SEC: 10,
200
+ MAX_REQ: 20,
201
+ FLOOD_REQ: 40,
202
+ HONEYPOT_FIELD: 'hp_field'
203
+ }
204
+ });
205
+
206
+ server.route({ method: 'GET', path: '/', handler: () => 'Protected' });
207
+ await server.start();
208
+ ```
209
+
210
+ ## Koa Usage
211
+
212
+ ```js
213
+ const Koa = require('koa');
214
+ const bodyParser = require('koa-bodyparser');
215
+ const aiwaf = require('aiwaf');
216
+
217
+ const app = new Koa();
218
+ app.use(bodyParser());
219
+
220
+ app.use(aiwaf.koa({
221
+ staticKeywords: ['.php', '.env', '.git'],
222
+ dynamicTopN: 10,
223
+ WINDOW_SEC: 10,
224
+ MAX_REQ: 20,
225
+ FLOOD_REQ: 40,
226
+ HONEYPOT_FIELD: 'hp_field'
227
+ }));
228
+
229
+ app.use(ctx => {
230
+ ctx.body = 'Protected';
231
+ });
232
+
233
+ app.listen(3000);
234
+ ```
235
+
236
+ ## NestJS (Express) Usage
237
+
238
+ ```ts
239
+ import { Module, MiddlewareConsumer, NestModule } from '@nestjs/common';
240
+ import aiwaf from 'aiwaf';
241
+
242
+ @Module({})
243
+ export class AppModule implements NestModule {
244
+ configure(consumer: MiddlewareConsumer) {
245
+ consumer
246
+ .apply(aiwaf.nest({
247
+ staticKeywords: ['.php', '.env', '.git'],
248
+ dynamicTopN: 10,
249
+ WINDOW_SEC: 10,
250
+ MAX_REQ: 20,
251
+ FLOOD_REQ: 40,
252
+ HONEYPOT_FIELD: 'hp_field'
253
+ }))
254
+ .forRoutes('*');
255
+ }
256
+ }
257
+ ```
258
+
259
+ If you need to guarantee ordering before other middleware/proxies, you can also attach the Express middleware directly in `main.ts`:
260
+
261
+ ```ts
262
+ import { NestFactory } from '@nestjs/core';
263
+ import aiwaf from 'aiwaf';
264
+ import { AppModule } from './app.module';
265
+
266
+ async function bootstrap() {
267
+ const app = await NestFactory.create(AppModule);
268
+ app.use(aiwaf({
269
+ staticKeywords: ['.php', '.env', '.git'],
270
+ dynamicTopN: 10,
271
+ WINDOW_SEC: 10,
272
+ MAX_REQ: 20,
273
+ FLOOD_REQ: 40,
274
+ HONEYPOT_FIELD: 'hp_field'
275
+ }));
276
+ await app.listen(3000);
277
+ }
278
+ bootstrap();
279
+ ```
280
+
281
+ ## NestJS (Fastify) Usage
282
+
283
+ Use the Fastify plugin when running Nest with `FastifyAdapter`:
284
+
285
+ ```ts
286
+ import { NestFactory } from '@nestjs/core';
287
+ import { FastifyAdapter } from '@nestjs/platform-fastify';
288
+ import aiwaf from 'aiwaf';
289
+ import { AppModule } from './app.module';
290
+
291
+ async function bootstrap() {
292
+ const app = await NestFactory.create(AppModule, new FastifyAdapter());
293
+ await app.register(aiwaf.fastify, {
294
+ staticKeywords: ['.php', '.env', '.git'],
295
+ dynamicTopN: 10,
296
+ WINDOW_SEC: 10,
297
+ MAX_REQ: 20,
298
+ FLOOD_REQ: 40,
299
+ HONEYPOT_FIELD: 'hp_field'
300
+ });
301
+ await app.listen(3000, '0.0.0.0');
302
+ }
303
+ bootstrap();
304
+ ```
305
+
306
+ ## Next.js (API Routes) Usage
307
+
308
+ Use the `aiwaf.next` helper to wrap a Next.js API route handler.
309
+
310
+ ```ts
311
+ import aiwaf from 'aiwaf';
312
+
313
+ function handler(req, res) {
314
+ res.status(200).json({ ok: true });
315
+ }
316
+
317
+ export default aiwaf.next(handler, {
318
+ staticKeywords: ['.php', '.env', '.git'],
319
+ dynamicTopN: 10,
320
+ WINDOW_SEC: 10,
321
+ MAX_REQ: 20,
322
+ FLOOD_REQ: 40,
323
+ HONEYPOT_FIELD: 'hp_field'
324
+ });
325
+ ```
326
+
327
+ ## AdonisJS Usage
328
+
329
+ Register the middleware in your Adonis middleware stack:
330
+
331
+ ```ts
332
+ import aiwaf from 'aiwaf';
333
+
334
+ export const middleware = [
335
+ () => aiwaf.adonis({
336
+ staticKeywords: ['.php', '.env', '.git'],
337
+ dynamicTopN: 10,
338
+ WINDOW_SEC: 10,
339
+ MAX_REQ: 20,
340
+ FLOOD_REQ: 40,
341
+ HONEYPOT_FIELD: 'hp_field'
342
+ })
343
+ ];
344
+ ```
345
+
346
+ ## Sails.js Usage
347
+
348
+ Use the Express-compatible middleware in your Sails `config/http.js`:
349
+
350
+ ```js
351
+ const aiwaf = require('aiwaf');
352
+
353
+ module.exports.http = {
354
+ middleware: {
355
+ aiwaf: aiwaf.sails({
356
+ staticKeywords: ['.php', '.env', '.git'],
357
+ dynamicTopN: 10,
358
+ WINDOW_SEC: 10,
359
+ MAX_REQ: 20,
360
+ FLOOD_REQ: 40,
361
+ HONEYPOT_FIELD: 'hp_field'
362
+ })
363
+ }
364
+ };
365
+ ```
366
+
367
+ ## Configuration
368
+
369
+ ### Core Controls
370
+
371
+ | Option | Default | Description |
372
+ |---|---|---|
373
+ | `staticKeywords` | `[]` | Substrings that trigger immediate block + blacklist |
374
+ | `dynamicTopN` or `DYNAMIC_TOP_N` | `10` | Frequency threshold for dynamic segment blocking |
375
+ | `WINDOW_SEC` | `60` | Time window for rate limiting |
376
+ | `MAX_REQ` | `100` | Max allowed requests in window before rate block |
377
+ | `FLOOD_REQ` | `200` | Hard threshold that blacklists IP |
378
+ | `HONEYPOT_FIELD` | `undefined` | Body field name used as bot trap |
379
+ | `uuidRoutePrefix` | `"/user"` | Path prefix monitored for UUID tamper attempts |
380
+ | `uuidResolver` | `undefined` | Optional async resolver `(uuid, req) => boolean` for existence checks |
381
+ | `cache` | fallback memory cache | Custom cache backend used by limiter/features |
382
+ | `nTrees` | `100` | IsolationForest trees when model is initialized in-process |
383
+ | `sampleSize` | `256` | IsolationForest sample size |
384
+ | `AIWAF_WASM_VALIDATION` | `true` | Enable WASM validation when available (headers, URL, content, recent) |
385
+ | `AIWAF_WASM_VALIDATE_RECENT` | `false` | Run WASM recent-behavior validation on recent request logs |
386
+
387
+ ### Header Validation
388
+
389
+ | Option | Default | Description |
390
+ |---|---|---|
391
+ | `AIWAF_HEADER_VALIDATION` | `false` | Enable header validation pipeline |
392
+ | `AIWAF_REQUIRED_HEADERS` | `[]` | Required headers array, or `{ DEFAULT, GET, POST }` mapping |
393
+ | `AIWAF_HEADER_QUALITY_MIN_SCORE` | `3` | Minimum header quality score |
394
+ | `AIWAF_MAX_HEADER_BYTES` | `32768` | Max header bytes before blocking |
395
+ | `AIWAF_MAX_HEADER_COUNT` | `100` | Max header count before blocking |
396
+ | `AIWAF_MAX_USER_AGENT_LENGTH` | `500` | Max User-Agent length |
397
+ | `AIWAF_MAX_ACCEPT_LENGTH` | `4096` | Max Accept header length |
398
+ | `AIWAF_BLOCKED_USER_AGENTS` | list | Substring deny list |
399
+ | `AIWAF_SUSPICIOUS_USER_AGENTS` | regex list | Regex list for suspicious UA detection |
400
+ | `AIWAF_LEGITIMATE_BOTS` | regex list | Regex allow list for legitimate crawlers |
401
+
402
+ ### Method Policy
403
+
404
+ | Option | Default | Description |
405
+ |---|---|---|
406
+ | `AIWAF_METHOD_POLICY_ENABLED` | `false` | Enforce method allowlist (returns 405) |
407
+ | `AIWAF_ALLOWED_METHODS` | `['GET','POST','HEAD','OPTIONS']` | Allowed methods when policy enabled |
408
+ | `AIWAF_POST_ONLY_SUFFIXES` | `['/create/','/submit/','/upload/','/delete/','/process/']` | GET to these triggers 405 when policy enabled |
409
+ | `AIWAF_LOGIN_PATH_PREFIXES` | common login paths | Shorten min form time for login |
410
+
411
+ ### Middleware Selection / Path Rules
412
+
413
+ | Option | Default | Description |
414
+ |---|---|---|
415
+ | `AIWAF_MIDDLEWARES` | all compatible checks | Explicit middleware list, or `['auto']` / `['all']` |
416
+ | `AIWAF_DISABLE_MIDDLEWARES` | `[]` | Middleware names to disable after selection |
417
+ | `AIWAF_PATH_RULES` | `[]` | Prefix rules with `PREFIX`, `DISABLE`, and optional section overrides |
418
+ | `AIWAF_PATH_MANIFEST` | `.aiwaf/paths.json` | Route manifest compiled into additional path rules |
419
+ | `AIWAF_ROUTE_PLAN_VERSION` | `0` | User-controlled version marker for route policy changes |
420
+
421
+ ### Keyword Learning
422
+
423
+ | Option | Default | Description |
424
+ |---|---|---|
425
+ | `AIWAF_ENABLE_KEYWORD_LEARNING` | `true` | Enable dynamic keyword learning |
426
+ | `AIWAF_DYNAMIC_TOP_N` | `10` | Dynamic keyword learning threshold |
427
+ | `AIWAF_EXEMPT_KEYWORDS` | `[]` | Skip these keywords |
428
+ | `AIWAF_ALLOWED_PATH_KEYWORDS` | `[]` | Allowlist of path fragments |
429
+
430
+ ### Model / Training
431
+
432
+ | Option | Default | Description |
433
+ |---|---|---|
434
+ | `AIWAF_MIN_TRAIN_LOGS` | `50` | Minimum logs to run training |
435
+ | `AIWAF_MIN_AI_LOGS` | `10000` | Minimum logs to train AI model |
436
+ | `AIWAF_CLEAR_STATE_ON_START` | `false` | Clear blacklist, request logs, and dynamic keywords on startup |
437
+ | `AIWAF_FORCE_AI_TRAINING` | `false` | Force AI training below minimum logs |
438
+ | `AIWAF_MODEL_STORAGE` | `file` | `file`, `db`, or `cache` |
439
+ | `AIWAF_MODEL_PATH` | `resources/model.json` | Model file path (file backend) |
440
+ | `AIWAF_MODEL_STORAGE_FALLBACK` | `file` | Fallback model backend |
441
+ | `AIWAF_MODEL_CACHE_KEY` | `aiwaf:model` | Cache key when using cache backend |
442
+ | `AIWAF_MODEL_CACHE_TTL` | `0` | Cache TTL in seconds |
443
+
444
+ ### Geo Blocking
445
+
446
+ | Option | Default | Description |
447
+ |---|---|---|
448
+ | `AIWAF_GEO_BLOCK_ENABLED` | `false` | Enable geo blocking |
449
+ | `AIWAF_GEO_BLOCK_COUNTRIES` | `[]` | Block list (country codes) |
450
+ | `AIWAF_GEO_ALLOW_COUNTRIES` | `[]` | Allow list (country codes) |
451
+ | `AIWAF_GEO_MMDB_PATH` | `geolock/ipinfo_lite.mmdb` | MMDB path |
452
+ | `AIWAF_GEO_CACHE_SECONDS` | `3600` | Geo cache TTL |
453
+ | `AIWAF_GEO_CACHE_PREFIX` | `aiwaf:geo:` | Geo cache key prefix |
454
+
455
+ ### Logging / Storage
456
+
457
+ | Option | Default | Description |
458
+ |---|---|---|
459
+ | `AIWAF_MIDDLEWARE_LOGGING` | `false` | Enable JSONL logging |
460
+ | `AIWAF_MIDDLEWARE_LOG_PATH` | `logs/aiwaf-requests.jsonl` | JSONL log path |
461
+ | `AIWAF_MIDDLEWARE_LOG_DB` | `false` | Store logs in DB |
462
+ | `AIWAF_MIDDLEWARE_LOG_CSV` | `false` | Store logs in CSV |
463
+ | `AIWAF_MIDDLEWARE_LOG_CSV_PATH` | `logs/aiwaf-requests.csv` | CSV log path |
464
+ | `AIWAF_BLOCKED_IPS_CSV_PATH` | `logs/storage/blocked_ips.csv` | CSV fallback for blocked IPs |
465
+ | `AIWAF_IP_EXEMPTIONS_CSV_PATH` | `logs/storage/ip_exemptions.csv` | CSV fallback for IP exemptions |
466
+ | `AIWAF_PATH_EXEMPTIONS_CSV_PATH` | `logs/storage/path_exemptions.csv` | CSV fallback for path exemptions |
467
+ | `AIWAF_GEO_BLOCKED_COUNTRIES_CSV_PATH` | `logs/storage/geo_blocked_countries.csv` | CSV fallback for geo blocklist |
468
+ | `AIWAF_REQUEST_LOGS_CSV_PATH` | `logs/storage/request_logs.csv` | CSV fallback for request logs |
469
+ | `AIWAF_DYNAMIC_KEYWORDS_CSV_PATH` | `logs/storage/dynamic_keywords.csv` | CSV fallback for dynamic keywords |
470
+
471
+ ### Redis / Cache
472
+ ## Redis and Cache Behavior
473
+
474
+ - Set `REDIS_URL` (or `AIWAF_REDIS_URL`) to enable Redis connectivity (`lib/redisClient.js`).
475
+ - If Redis is unavailable, runtime falls back to in-memory behavior.
476
+ - You can inject a custom cache object.
477
+
478
+ Rate limiter custom cache must implement:
479
+
480
+ - `lPush(key, value)`
481
+ - `expire(key, ttl)`
482
+ - `lLen(key)`
483
+ - `lRange(key, start, end)`
484
+
485
+ Feature cache custom backend supports:
486
+
487
+ - `get(key)`
488
+ - `set(key, value, ttl)`
489
+
490
+ ## Geo Blocking (MMDB)
491
+
492
+ - Put your DB at `geolock/ipinfo_lite.mmdb` (default) or set `AIWAF_GEO_MMDB_PATH`.
493
+ - Enable with `AIWAF_GEO_BLOCK_ENABLED: true`.
494
+ - Configure `AIWAF_GEO_BLOCK_COUNTRIES` and/or `AIWAF_GEO_ALLOW_COUNTRIES`.
495
+ - Install MMDB reader dependency in your app:
496
+ - `npm install maxmind`
497
+ - If MMDB is unavailable, the middleware falls back to `x-country-code` header.
498
+
499
+ ## Offline Training
500
+
501
+ Train a model using access logs:
502
+
503
+ ```bash
504
+ AIWAF_ACCESS_LOG=/path/to/access.log npm run train
505
+ ```
506
+
507
+ Optional rotated/gz support:
508
+
509
+ ```bash
510
+ NODE_LOG_GLOB='/path/to/access.log.*' npm run train
511
+ ```
512
+
513
+ Training pipeline in `train.js`:
514
+
515
+ - Reads raw and rotated (including `.gz`) access logs
516
+ - Parses request fields (IP, URI, status, response time, timestamp)
517
+ - Builds feature vectors: `[pathLen, kwHits, statusIdx, responseTime, burst, total404]`
518
+ - Enforces `AIWAF_MIN_TRAIN_LOGS` and `AIWAF_MIN_AI_LOGS`
519
+ - Trains IsolationForest when log volume is sufficient
520
+ - Learns dynamic keywords from suspicious 4xx/5xx traffic
521
+ - Removes exempt keywords and unblocks exempt IPs
522
+ - Writes model artifact to `resources/model.json` with metadata
523
+ - Model storage backends:
524
+ - `AIWAF_MODEL_STORAGE`: `file` (default), `db`, `cache`
525
+ - `AIWAF_MODEL_PATH` (file backend)
526
+ - `AIWAF_MODEL_STORAGE_FALLBACK` (fallback backend)
527
+ - `AIWAF_MODEL_CACHE_KEY`, `AIWAF_MODEL_CACHE_TTL` (cache backend)
528
+
529
+ ## Testing
530
+
531
+ ```bash
532
+ npm test
533
+ ```
534
+
535
+ Current tests cover:
536
+
537
+ - Header validation (caps, suspicious UA, quality scoring)
538
+ - Method policy enforcement
539
+ - Geo blocking and MMDB lookup
540
+ - Honeypot timing policies
541
+ - UUID tamper detection (with resolver)
542
+ - Anomaly detection and recent-behavior analysis
543
+ - Dynamic keyword learning and trainer behaviors
544
+ - CSV/DB fallback storage
545
+ - CLI and settings compatibility
546
+
547
+ ## Data and Persistence
548
+
549
+ - Runtime blacklist storage uses SQLite through `utils/db.js`.
550
+ - Production DB file defaults to `./aiwaf.sqlite`.
551
+ - Test environment uses in-memory SQLite (`NODE_ENV=test`).
552
+ - Primary blocked IP table: `blocked_ips`.
553
+ - Middleware logging supports JSONL, optional SQLite, and CSV fallback.
554
+ - CSV settings:
555
+ - `AIWAF_MIDDLEWARE_LOG_CSV`
556
+ - `AIWAF_MIDDLEWARE_LOG_CSV_PATH`
557
+ - Table storage CSV fallbacks are enabled automatically when DB operations fail:
558
+ - `blocked_ips` -> `logs/storage/blocked_ips.csv` (`AIWAF_BLOCKED_IPS_CSV_PATH`)
559
+ - `ip_exemptions` -> `logs/storage/ip_exemptions.csv` (`AIWAF_IP_EXEMPTIONS_CSV_PATH`)
560
+ - `path_exemptions` -> `logs/storage/path_exemptions.csv` (`AIWAF_PATH_EXEMPTIONS_CSV_PATH`)
561
+ - `geo_blocked_countries` -> `logs/storage/geo_blocked_countries.csv` (`AIWAF_GEO_BLOCKED_COUNTRIES_CSV_PATH`)
562
+ - `request_logs` -> `logs/storage/request_logs.csv` (`AIWAF_REQUEST_LOGS_CSV_PATH`)
563
+ - `dynamic_keywords` -> `logs/storage/dynamic_keywords.csv` (`AIWAF_DYNAMIC_KEYWORDS_CSV_PATH`)
564
+
565
+ ## Operational Notes
566
+
567
+ - Middleware order matters; place AIWAF after body parsers if honeypot checks depend on parsed JSON/form body.
568
+ - If no trained model exists or loading fails, anomaly detector fails open.
569
+ - Dynamic keyword learning persists to DB/CSV via `dynamicKeywordStore`.
570
+ - Multi-instance deployments should use Redis/custom shared cache for limiter consistency.
571
+
572
+ ## Development
573
+
574
+ ```bash
575
+ npm install
576
+ npm test
577
+ npm run train
578
+ npm run aiwaf -- help
579
+ ```
580
+
581
+ ## Operations CLI
582
+
583
+ ```bash
584
+ npm run aiwaf -- list blacklist
585
+ npm run aiwaf -- list exemptions
586
+ npm run aiwaf -- add blacklist 203.0.113.9 "manual block"
587
+ npm run aiwaf -- remove blacklist 203.0.113.9
588
+ npm run aiwaf -- add ip-exemption 203.0.113.10 "trusted monitor"
589
+ npm run aiwaf -- add path-exemption /health "health probes"
590
+ npm run aiwaf -- add dynamic-keyword scanner 5
591
+ npm run aiwaf -- remove dynamic-keyword scanner
592
+ npm run aiwaf -- geo block CN "manual block"
593
+ npm run aiwaf -- geo summary
594
+ npm run aiwaf -- whois example.com
595
+ npm run aiwaf -- diagnose 203.0.113.10
596
+ npm run aiwaf -- reset --all --confirm
597
+ npm run aiwaf -- pathshell
598
+ ```
599
+
600
+ ## Sandbox (OWASP Juice Shop)
601
+
602
+ The repository includes a runnable sandbox that proxies OWASP Juice Shop behind AIWAF. It also includes an attack suite that generates comparable results for direct vs protected traffic.
603
+
604
+ Run sandbox:
605
+
606
+ ```bash
607
+ docker compose -f examples/sandbox/docker-compose.yml up --build
608
+ ```
609
+
610
+ Run the attack suite and compare:
611
+
612
+ ```bash
613
+ node examples/sandbox/run-and-compare.js http://localhost:3001 http://localhost:3000
614
+ ```
615
+
616
+ The comparison output includes per‑attack block rates and total blocked requests.
617
+ Fastify proxy is also available on `http://localhost:3002`.
618
+
619
+ ## License
620
+
621
+ MIT