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/bin/aiwaf.js ADDED
@@ -0,0 +1,349 @@
1
+ #!/usr/bin/env node
2
+
3
+ const path = require('path');
4
+ const { spawn } = require('child_process');
5
+ const pathManifest = require('../lib/pathManifest');
6
+
7
+ function print(obj) {
8
+ process.stdout.write(`${JSON.stringify(obj, null, 2)}\n`);
9
+ }
10
+
11
+ async function clearBlacklist() {
12
+ const blacklistManager = require('../lib/blacklistManager');
13
+ const deleted = await blacklistManager.clear();
14
+ print({ ok: true, cleared: deleted });
15
+ }
16
+
17
+ async function clearRequestLogs() {
18
+ const requestLogStore = require('../lib/requestLogStore');
19
+ const deleted = await requestLogStore.clear();
20
+ print({ ok: true, cleared: deleted });
21
+ }
22
+
23
+ function runTrain() {
24
+ const child = spawn(process.execPath, [path.join(__dirname, '..', 'train.js')], {
25
+ stdio: 'inherit',
26
+ env: process.env
27
+ });
28
+ child.on('exit', code => process.exit(code || 0));
29
+ }
30
+
31
+ function readJsonFile(filePath) {
32
+ const fs = require('fs');
33
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
34
+ }
35
+
36
+ function parseManifestArgs(args = []) {
37
+ const options = {
38
+ framework: 'express',
39
+ output: process.env.AIWAF_PATH_MANIFEST || '.aiwaf/paths.json',
40
+ routes: []
41
+ };
42
+ for (let index = 0; index < args.length; index += 1) {
43
+ const arg = args[index];
44
+ if (arg === '--framework' || arg === '-f') {
45
+ options.framework = args[++index] || options.framework;
46
+ } else if (arg === '--output' || arg === '-o') {
47
+ options.output = args[++index] || options.output;
48
+ } else if (arg === '--routes' || arg === '-r') {
49
+ const routeFile = args[++index];
50
+ options.routes = routeFile ? readJsonFile(routeFile) : [];
51
+ }
52
+ }
53
+ return options;
54
+ }
55
+
56
+ async function diagnoseIp(ip) {
57
+ const blacklistManager = require('../lib/blacklistManager');
58
+ const exemptionStore = require('../lib/exemptionStore');
59
+ const blocked = await blacklistManager.isBlocked(ip);
60
+ const exempt = await exemptionStore.isIpExempt(ip);
61
+ print({ ip, blocked, exempt });
62
+ }
63
+
64
+ function runPathShell() {
65
+ const readline = require('readline');
66
+ const fs = require('fs');
67
+ const manifestPath = process.env.AIWAF_PATH_MANIFEST || '.aiwaf/paths.json';
68
+ if (!fs.existsSync(manifestPath)) {
69
+ console.error(`Manifest not found at ${manifestPath}. Run 'aiwaf manifest' first.`);
70
+ return process.exit(1);
71
+ }
72
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
73
+ const routes = Object.keys(manifest.routes || {});
74
+
75
+ const rl = readline.createInterface({
76
+ input: process.stdin,
77
+ output: process.stdout,
78
+ prompt: 'aiwaf> '
79
+ });
80
+
81
+ console.log(`Loaded ${routes.length} routes from ${manifestPath}`);
82
+ rl.prompt();
83
+
84
+ rl.on('line', async (line) => {
85
+ const args = line.trim().split(' ').filter(Boolean);
86
+ if (!args.length) { rl.prompt(); return; }
87
+ const cmd = args[0];
88
+
89
+ if (cmd === 'exit' || cmd === 'quit') {
90
+ rl.close();
91
+ } else if (cmd === 'ls') {
92
+ routes.forEach((r, i) => console.log(`[${i}] ${r}`));
93
+ } else if (cmd === 'exempt') {
94
+ const idx = Number(args[1]);
95
+ const pathPrefix = !isNaN(idx) && routes[idx] ? routes[idx] : args[1];
96
+ if (!pathPrefix) {
97
+ console.log('Usage: exempt <index|path>');
98
+ } else {
99
+ const exemptionStore = require('../lib/exemptionStore');
100
+ await exemptionStore.addPath(pathPrefix, 'manual via shell');
101
+ console.log(`Exempted path: ${pathPrefix}`);
102
+ }
103
+ } else {
104
+ console.log(`Unknown command: ${cmd}`);
105
+ console.log(`Available commands: ls, exempt <index|path>, exit`);
106
+ }
107
+ rl.prompt();
108
+ }).on('close', () => {
109
+ console.log('Exiting shell.');
110
+ process.exit(0);
111
+ });
112
+ }
113
+
114
+ async function runReset(args) {
115
+ const flags = { blacklist: false, keywords: false, exemptions: false, confirm: false };
116
+ for (const arg of args) {
117
+ if (arg === '--blacklist') flags.blacklist = true;
118
+ if (arg === '--keywords') flags.keywords = true;
119
+ if (arg === '--exemptions') flags.exemptions = true;
120
+ if (arg === '--all') { flags.blacklist = true; flags.keywords = true; flags.exemptions = true; }
121
+ if (arg === '--confirm') flags.confirm = true;
122
+ }
123
+ if (!flags.blacklist && !flags.keywords && !flags.exemptions) {
124
+ return print({ error: 'Specify what to reset: --blacklist, --keywords, --exemptions, or --all' });
125
+ }
126
+ if (!flags.confirm) {
127
+ return print({ error: 'Must pass --confirm to execute reset' });
128
+ }
129
+
130
+ const results = {};
131
+ if (flags.blacklist) {
132
+ const blacklistManager = require('../lib/blacklistManager');
133
+ results.blacklist = await blacklistManager.clear();
134
+ }
135
+ if (flags.keywords) {
136
+ const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
137
+ results.keywords = await dynamicKeywordStore.clear();
138
+ }
139
+ if (flags.exemptions) {
140
+ const exemptionStore = require('../lib/exemptionStore');
141
+ results.exemptions = await exemptionStore.clear();
142
+ }
143
+ return print({ ok: true, reset: results });
144
+ }
145
+
146
+ async function main() {
147
+ const [, , cmd, subcmd, ...args] = process.argv;
148
+
149
+ if (!cmd || ['help', '--help', '-h'].includes(cmd)) {
150
+ print({
151
+ usage: 'aiwaf <command> [subcommand] [args]',
152
+ commands: [
153
+ 'list blacklist|exemptions|geo|request-logs',
154
+ 'list dynamic-keywords',
155
+ 'list model-info',
156
+ 'add blacklist <ip> [reason]',
157
+ 'add ip-exemption <ip> [reason]',
158
+ 'add path-exemption <pathPrefix> [reason]',
159
+ 'add dynamic-keyword <keyword> [count]',
160
+ 'remove blacklist <ip>',
161
+ 'remove ip-exemption <ip>',
162
+ 'remove path-exemption <pathPrefix>',
163
+ 'remove dynamic-keyword <keyword>',
164
+ 'geo block <CC> [reason]',
165
+ 'geo unblock <CC>',
166
+ 'geo summary',
167
+ 'clear blacklist|request-logs',
168
+ 'clear dynamic-keywords',
169
+ 'train',
170
+ 'manifest --framework <name> --routes <routes.json> [--output .aiwaf/paths.json]',
171
+ 'whois <domain|ip>',
172
+ 'diagnose <ip>',
173
+ 'reset [--blacklist] [--keywords] [--exemptions] [--all] --confirm',
174
+ 'pathshell'
175
+ ]
176
+ });
177
+ return;
178
+ }
179
+
180
+ if (cmd === 'train') return runTrain();
181
+ if (cmd === 'pathshell') return runPathShell();
182
+ if (cmd === 'reset') return runReset([subcmd, ...args].filter(Boolean));
183
+
184
+ if (cmd === 'manifest') {
185
+ const options = parseManifestArgs([subcmd, ...args].filter(Boolean));
186
+ const manifest = pathManifest.generateFrameworkManifest(
187
+ options.framework,
188
+ null,
189
+ options.output,
190
+ { routes: options.routes }
191
+ );
192
+ return print({ ok: true, output: options.output, framework: options.framework, routes: Object.keys(manifest.routes || {}).length });
193
+ }
194
+
195
+ if (cmd === 'list' && subcmd === 'blacklist') {
196
+ const blacklistManager = require('../lib/blacklistManager');
197
+ const rows = await blacklistManager.getBlockedIPs();
198
+ return print(rows);
199
+ }
200
+
201
+ if (cmd === 'list' && subcmd === 'exemptions') {
202
+ const exemptionStore = require('../lib/exemptionStore');
203
+ const ips = await exemptionStore.listIps();
204
+ const paths = await exemptionStore.listPaths();
205
+ return print({ ip_exemptions: ips, path_exemptions: paths });
206
+ }
207
+
208
+ if (cmd === 'list' && subcmd === 'geo') {
209
+ const geoStore = require('../lib/geoStore');
210
+ const rows = await geoStore.listBlockedCountries();
211
+ return print(rows);
212
+ }
213
+
214
+ if (cmd === 'list' && subcmd === 'request-logs') {
215
+ const requestLogStore = require('../lib/requestLogStore');
216
+ const limit = Number(args[0] || 100);
217
+ const rows = await requestLogStore.recent(limit);
218
+ return print(rows);
219
+ }
220
+
221
+ if (cmd === 'list' && subcmd === 'dynamic-keywords') {
222
+ const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
223
+ const limit = Number(args[0] || 100);
224
+ const rows = await dynamicKeywordStore.list(limit);
225
+ return print(rows);
226
+ }
227
+
228
+ if (cmd === 'list' && subcmd === 'model-info') {
229
+ const modelStore = require('../lib/modelStore');
230
+ const model = await modelStore.load(process.env);
231
+ if (!model) return print({ loaded: false });
232
+ return print({ loaded: true, metadata: model.metadata || null });
233
+ }
234
+
235
+ if (cmd === 'add' && subcmd === 'ip-exemption') {
236
+ const exemptionStore = require('../lib/exemptionStore');
237
+ const [ip, ...reasonParts] = args;
238
+ await exemptionStore.addIp(ip, reasonParts.join(' ') || 'manual');
239
+ return print({ ok: true, ip });
240
+ }
241
+
242
+ if (cmd === 'add' && subcmd === 'blacklist') {
243
+ const blacklistManager = require('../lib/blacklistManager');
244
+ const [ip, ...reasonParts] = args;
245
+ await blacklistManager.block(ip, reasonParts.join(' ') || 'manual');
246
+ return print({ ok: true, ip });
247
+ }
248
+
249
+ if (cmd === 'add' && subcmd === 'path-exemption') {
250
+ const exemptionStore = require('../lib/exemptionStore');
251
+ const [pathPrefix, ...reasonParts] = args;
252
+ await exemptionStore.addPath(pathPrefix, reasonParts.join(' ') || 'manual');
253
+ return print({ ok: true, pathPrefix });
254
+ }
255
+
256
+ if (cmd === 'add' && subcmd === 'dynamic-keyword') {
257
+ const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
258
+ const [keyword, count] = args;
259
+ await dynamicKeywordStore.add(keyword, Number(count || 1));
260
+ return print({ ok: true, keyword });
261
+ }
262
+
263
+ if (cmd === 'remove' && subcmd === 'blacklist') {
264
+ const blacklistManager = require('../lib/blacklistManager');
265
+ const [ip] = args;
266
+ const deleted = await blacklistManager.unblock(ip);
267
+ return print({ ok: true, deleted });
268
+ }
269
+
270
+ if (cmd === 'remove' && subcmd === 'ip-exemption') {
271
+ const exemptionStore = require('../lib/exemptionStore');
272
+ const [ip] = args;
273
+ const deleted = await exemptionStore.removeIp(ip);
274
+ return print({ ok: true, deleted });
275
+ }
276
+
277
+ if (cmd === 'remove' && subcmd === 'dynamic-keyword') {
278
+ const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
279
+ const [keyword] = args;
280
+ await dynamicKeywordStore.remove(keyword);
281
+ return print({ ok: true, keyword });
282
+ }
283
+
284
+ if (cmd === 'remove' && subcmd === 'path-exemption') {
285
+ const exemptionStore = require('../lib/exemptionStore');
286
+ const [pathPrefix] = args;
287
+ const deleted = await exemptionStore.removePath(pathPrefix);
288
+ return print({ ok: true, deleted });
289
+ }
290
+
291
+ if (cmd === 'geo' && subcmd === 'block') {
292
+ const geoStore = require('../lib/geoStore');
293
+ const [countryCode, ...reasonParts] = args;
294
+ await geoStore.addBlockedCountry(countryCode, reasonParts.join(' ') || 'manual');
295
+ return print({ ok: true, countryCode });
296
+ }
297
+
298
+ if (cmd === 'geo' && subcmd === 'unblock') {
299
+ const geoStore = require('../lib/geoStore');
300
+ const [countryCode] = args;
301
+ const deleted = await geoStore.removeBlockedCountry(countryCode);
302
+ return print({ ok: true, deleted });
303
+ }
304
+
305
+ if (cmd === 'geo' && subcmd === 'summary') {
306
+ const requestLogStore = require('../lib/requestLogStore');
307
+ const rows = await requestLogStore.geoSummary(50);
308
+ return print(rows);
309
+ }
310
+
311
+ if (cmd === 'clear' && subcmd === 'blacklist') {
312
+ return clearBlacklist();
313
+ }
314
+
315
+ if (cmd === 'clear' && subcmd === 'request-logs') {
316
+ return clearRequestLogs();
317
+ }
318
+
319
+ if (cmd === 'clear' && subcmd === 'dynamic-keywords') {
320
+ const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
321
+ const cleared = await dynamicKeywordStore.clear();
322
+ return print({ ok: true, cleared });
323
+ }
324
+
325
+ if (cmd === 'diagnose') {
326
+ const [ip] = [subcmd, ...args];
327
+ return diagnoseIp(ip);
328
+ }
329
+
330
+ if (cmd === 'whois') {
331
+ const whois = require('../lib/whois');
332
+ const [target] = [subcmd, ...args];
333
+ const result = await whois.runWhoisLookup(target);
334
+ process.stdout.write(`${result}\n`);
335
+ return;
336
+ }
337
+
338
+ print({ error: 'unknown command', command: [cmd, subcmd, ...args].join(' ') });
339
+ process.exitCode = 1;
340
+ }
341
+
342
+ main()
343
+ .catch(err => {
344
+ process.stderr.write(`${err.stack || err.message}\n`);
345
+ process.exit(1);
346
+ })
347
+ .finally(async () => {
348
+ // no-op
349
+ });
package/index.js ADDED
@@ -0,0 +1,62 @@
1
+ // aiwaf‑js/index.js
2
+ const createExpressMiddleware = require('./lib/wafMiddleware');
3
+ const createFastifyPlugin = require('./lib/fastifyPlugin');
4
+ const createHapiPlugin = require('./lib/hapiPlugin');
5
+ const createKoaMiddleware = require('./lib/koaMiddleware');
6
+ const createNestMiddleware = require('./lib/nestMiddleware');
7
+ const createNextHandler = require('./lib/nextMiddleware');
8
+ const createAdonisMiddleware = require('./lib/adonisMiddleware');
9
+ const pathRules = require('./lib/pathRules');
10
+ const pathManifest = require('./lib/pathManifest');
11
+ const sourceAst = require('./lib/sourceAst');
12
+ const wasm = require('./lib/wasmAdapter');
13
+ const runtimeUtils = require('./lib/runtimeUtils');
14
+ const geoPolicy = require('./lib/geoPolicy');
15
+ const trainingLogic = require('./lib/trainingLogic');
16
+ const modelSecurity = require('./lib/modelSecurity');
17
+ const blockResponses = require('./lib/blockResponses');
18
+ const KeywordFallbackStore = require('./lib/keywordFallbackStore');
19
+ const whois = require('./lib/whois');
20
+
21
+ function withMiddlewares(selection) {
22
+ return (opts = {}) => createExpressMiddleware({
23
+ ...opts,
24
+ AIWAF_MIDDLEWARES: opts.AIWAF_MIDDLEWARES || opts.middlewares || [selection]
25
+ });
26
+ }
27
+
28
+ module.exports = createExpressMiddleware;
29
+ module.exports.fastify = createFastifyPlugin;
30
+ module.exports.hapi = createHapiPlugin;
31
+ module.exports.koa = createKoaMiddleware;
32
+ module.exports.nest = createNestMiddleware;
33
+ module.exports.next = createNextHandler;
34
+ module.exports.adonis = createAdonisMiddleware;
35
+ module.exports.sails = createExpressMiddleware;
36
+ module.exports.auto = withMiddlewares('auto');
37
+ module.exports.all = withMiddlewares('all');
38
+ module.exports.exempt = pathRules.exempt;
39
+ module.exports.exemptFrom = pathRules.exemptFrom;
40
+ module.exports.only = pathRules.only;
41
+ module.exports.requireProtection = pathRules.requireProtection;
42
+ module.exports.shouldApplyMiddleware = (path, middlewareName, rules = []) =>
43
+ pathRules.createRoutePlan(path, rules).shouldApply(middlewareName);
44
+ module.exports.getPathRuleOverrides = pathRules.getPathRuleOverrides;
45
+ module.exports.pathManifest = pathManifest;
46
+ module.exports.sourceAst = sourceAst;
47
+ module.exports.wasm = wasm;
48
+ module.exports.runtimeUtils = runtimeUtils;
49
+ module.exports.geoPolicy = geoPolicy;
50
+ module.exports.trainingLogic = trainingLogic;
51
+ module.exports.modelSecurity = modelSecurity;
52
+ module.exports.blockResponses = blockResponses;
53
+ module.exports.KeywordFallbackStore = KeywordFallbackStore;
54
+ module.exports.whois = whois;
55
+ module.exports.extractExpressRoutes = pathManifest.extractExpressRoutes;
56
+ module.exports.extractFastifyRoutes = pathManifest.extractFastifyRoutes;
57
+ module.exports.extractHapiRoutes = pathManifest.extractHapiRoutes;
58
+ module.exports.extractKoaRoutes = pathManifest.extractKoaRoutes;
59
+ module.exports.extractNextRoutes = pathManifest.extractNextRoutes;
60
+ module.exports.extractNestRoutes = pathManifest.extractNestRoutes;
61
+ module.exports.generateExpressManifest = pathManifest.generateExpressManifest;
62
+ module.exports.generateFrameworkManifest = pathManifest.generateFrameworkManifest;
@@ -0,0 +1,82 @@
1
+ const createExpressMiddleware = require('./wafMiddleware');
2
+
3
+ function createExpressLikeResponse(ctx) {
4
+ const rawRes = ctx.response?.response;
5
+ const res = {
6
+ locals: {},
7
+ on: (...args) => rawRes?.on?.(...args),
8
+ get statusCode() {
9
+ return rawRes?.statusCode ?? ctx.response?.statusCode ?? 200;
10
+ },
11
+ set statusCode(code) {
12
+ if (rawRes) rawRes.statusCode = code;
13
+ if (ctx.response) ctx.response.statusCode = code;
14
+ },
15
+ status(code) {
16
+ if (ctx.response?.status) {
17
+ ctx.response.status(code);
18
+ } else {
19
+ res.statusCode = code;
20
+ }
21
+ res._handled = true;
22
+ return res;
23
+ },
24
+ json(payload) {
25
+ if (ctx.response?.json) {
26
+ ctx.response.json(payload);
27
+ } else if (ctx.response?.send) {
28
+ ctx.response.send(payload);
29
+ }
30
+ res._handled = true;
31
+ return res;
32
+ },
33
+ send(payload) {
34
+ if (ctx.response?.send) {
35
+ ctx.response.send(payload);
36
+ } else if (rawRes?.end) {
37
+ rawRes.end(payload);
38
+ }
39
+ res._handled = true;
40
+ return res;
41
+ }
42
+ };
43
+
44
+ return res;
45
+ }
46
+
47
+ module.exports = function createAdonisMiddleware(opts = {}) {
48
+ const middleware = createExpressMiddleware(opts);
49
+
50
+ return async (ctx, next) => {
51
+ const req = ctx.request?.request || ctx.request || {};
52
+ const res = createExpressLikeResponse(ctx);
53
+
54
+ // Only set path/url/ip if not already available
55
+ if (!req.path) req.path = ctx.request?.url?.() || ctx.request?.url || req.url;
56
+ if (!req.url) req.url = req.path;
57
+ if (!req.ip) req.ip = ctx.request?.ip?.() || ctx.request?.ip;
58
+
59
+ // Don't override headers - the raw request already has them from the HTTP server
60
+
61
+ await new Promise(resolve => {
62
+ let resolved = false;
63
+ const finish = () => {
64
+ if (resolved) return;
65
+ resolved = true;
66
+ resolve();
67
+ };
68
+ const maybePromise = middleware(req, res, finish);
69
+ if (res._handled) {
70
+ finish();
71
+ return;
72
+ }
73
+ Promise.resolve(maybePromise).then(finish).catch(finish);
74
+ });
75
+
76
+ if (res._handled || ctx.response?.response?.writableEnded || ctx.response?.response?.headersSent) {
77
+ return;
78
+ }
79
+
80
+ await next();
81
+ };
82
+ };