aiwaf 1.0.0 → 1.0.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.
package/bin/aiwaf.js CHANGED
@@ -3,6 +3,7 @@
3
3
  const path = require('path');
4
4
  const { spawn } = require('child_process');
5
5
  const pathManifest = require('../lib/pathManifest');
6
+ const fs = require('fs');
6
7
 
7
8
  function print(obj) {
8
9
  process.stdout.write(`${JSON.stringify(obj, null, 2)}\n`);
@@ -29,10 +30,127 @@ function runTrain() {
29
30
  }
30
31
 
31
32
  function readJsonFile(filePath) {
32
- const fs = require('fs');
33
33
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
34
34
  }
35
35
 
36
+ function writeJsonFile(filePath, payload) {
37
+ const resolved = path.resolve(filePath);
38
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
39
+ const temporary = `${resolved}.tmp`;
40
+ fs.writeFileSync(temporary, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
41
+ fs.renameSync(temporary, resolved);
42
+ return resolved;
43
+ }
44
+
45
+ function parseDuration(value) {
46
+ if (value === undefined || value === null || value === '') return null;
47
+ const match = String(value).trim().toLowerCase().match(/^(\d+)(s|m|h|d)?$/);
48
+ if (!match) throw new Error('Duration must be like 900s, 15m, 24h, or 1d');
49
+ const units = { s: 1, m: 60, h: 3600, d: 86400 };
50
+ return Number(match[1]) * units[match[2] || 's'];
51
+ }
52
+
53
+ async function collectOperationalState() {
54
+ const blacklistManager = require('../lib/blacklistManager');
55
+ const exemptionStore = require('../lib/exemptionStore');
56
+ const geoStore = require('../lib/geoStore');
57
+ const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
58
+ const modelStore = require('../lib/modelStore');
59
+ const [blacklist, ipExemptions, pathExemptions, geo, dynamicKeywords, model] = await Promise.all([
60
+ blacklistManager.exportRecords(),
61
+ exemptionStore.listIps(),
62
+ exemptionStore.listPaths(),
63
+ geoStore.listBlockedCountries(),
64
+ dynamicKeywordStore.list(100000),
65
+ modelStore.load(process.env)
66
+ ]);
67
+ return {
68
+ schema_version: '1.0',
69
+ exported_at: new Date().toISOString(),
70
+ blacklist,
71
+ ip_exemptions: ipExemptions,
72
+ path_exemptions: pathExemptions,
73
+ geo_blocked_countries: geo,
74
+ dynamic_keywords: dynamicKeywords,
75
+ model
76
+ };
77
+ }
78
+
79
+ async function exportOperationalState(filePath = 'aiwaf-export.json') {
80
+ const state = await collectOperationalState();
81
+ return print({ ok: true, output: writeJsonFile(filePath, state), counts: {
82
+ blacklist: state.blacklist.length,
83
+ ip_exemptions: state.ip_exemptions.length,
84
+ path_exemptions: state.path_exemptions.length,
85
+ geo: state.geo_blocked_countries.length,
86
+ dynamic_keywords: state.dynamic_keywords.length
87
+ } });
88
+ }
89
+
90
+ async function importOperationalState(filePath) {
91
+ if (!filePath) throw new Error('Import file is required');
92
+ const state = readJsonFile(filePath);
93
+ const blacklistManager = require('../lib/blacklistManager');
94
+ const exemptionStore = require('../lib/exemptionStore');
95
+ const geoStore = require('../lib/geoStore');
96
+ const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
97
+ const modelStore = require('../lib/modelStore');
98
+ const imported = { blacklist: await blacklistManager.importRecords(state.blacklist || []) };
99
+ for (const row of state.ip_exemptions || []) await exemptionStore.addIp(row.ip_address || row.ip, row.reason);
100
+ for (const row of state.path_exemptions || []) await exemptionStore.addPath(row.path_prefix || row.path, row.reason);
101
+ for (const row of state.geo_blocked_countries || []) await geoStore.addBlockedCountry(row.country_code || row.country, row.reason);
102
+ for (const row of state.dynamic_keywords || []) await dynamicKeywordStore.add(row.keyword, row.count);
103
+ if (state.model) await modelStore.save(process.env, state.model, state.model.metadata || {});
104
+ imported.ip_exemptions = (state.ip_exemptions || []).length;
105
+ imported.path_exemptions = (state.path_exemptions || []).length;
106
+ imported.geo = (state.geo_blocked_countries || []).length;
107
+ imported.dynamic_keywords = (state.dynamic_keywords || []).length;
108
+ return print({ ok: true, imported });
109
+ }
110
+
111
+ async function operationalStatus() {
112
+ const blacklistManager = require('../lib/blacklistManager');
113
+ const exemptionStore = require('../lib/exemptionStore');
114
+ const geoStore = require('../lib/geoStore');
115
+ const dynamicKeywordStore = require('../lib/dynamicKeywordStore');
116
+ const requestLogStore = require('../lib/requestLogStore');
117
+ const modelStore = require('../lib/modelStore');
118
+ const [blacklist, ips, paths, geo, keywords, logs, model] = await Promise.all([
119
+ blacklistManager.getStatistics(), exemptionStore.listIps(), exemptionStore.listPaths(),
120
+ geoStore.listBlockedCountries(), dynamicKeywordStore.list(100000), requestLogStore.recent(1),
121
+ modelStore.load(process.env)
122
+ ]);
123
+ return print({
124
+ status: 'enabled',
125
+ blacklist,
126
+ exemptions: { ips: ips.length, paths: paths.length },
127
+ geo_blocked_countries: geo.length,
128
+ dynamic_keywords: keywords.length,
129
+ request_logging: { has_records: logs.length > 0 },
130
+ model: { loaded: !!model, metadata: model?.metadata || null },
131
+ wasm: require('../lib/wasmAdapter').getWasmStatus()
132
+ });
133
+ }
134
+
135
+ async function operationalStats(limit = 5000) {
136
+ const blacklistManager = require('../lib/blacklistManager');
137
+ const requestLogStore = require('../lib/requestLogStore');
138
+ const [blacklist, logs] = await Promise.all([blacklistManager.getStatistics(), requestLogStore.recent(limit)]);
139
+ const statuses = {};
140
+ const paths = {};
141
+ let blocked = 0;
142
+ logs.forEach(row => {
143
+ statuses[String(row.status || 0)] = (statuses[String(row.status || 0)] || 0) + 1;
144
+ paths[row.path || '/'] = (paths[row.path || '/'] || 0) + 1;
145
+ if (row.blocked === true || row.blocked === 1 || String(row.blocked).toLowerCase() === 'true') blocked += 1;
146
+ });
147
+ return print({
148
+ blacklist,
149
+ requests: { total: logs.length, blocked, statuses },
150
+ top_paths: Object.entries(paths).sort((a, b) => b[1] - a[1]).slice(0, 10).map(([requestPath, count]) => ({ path: requestPath, count }))
151
+ });
152
+ }
153
+
36
154
  function parseManifestArgs(args = []) {
37
155
  const options = {
38
156
  framework: 'express',
@@ -57,8 +175,9 @@ async function diagnoseIp(ip) {
57
175
  const blacklistManager = require('../lib/blacklistManager');
58
176
  const exemptionStore = require('../lib/exemptionStore');
59
177
  const blocked = await blacklistManager.isBlocked(ip);
178
+ const blockInfo = await blacklistManager.getBlockInfo(ip);
60
179
  const exempt = await exemptionStore.isIpExempt(ip);
61
- print({ ip, blocked, exempt });
180
+ print({ ip, blocked, exempt, block_info: blockInfo });
62
181
  }
63
182
 
64
183
  function runPathShell() {
@@ -153,7 +272,9 @@ async function main() {
153
272
  'list blacklist|exemptions|geo|request-logs',
154
273
  'list dynamic-keywords',
155
274
  'list model-info',
156
- 'add blacklist <ip> [reason]',
275
+ 'list recent-blocks [hours]',
276
+ 'list top-reasons [limit]',
277
+ 'add blacklist <ip> [reason] [--duration 24h|--permanent]',
157
278
  'add ip-exemption <ip> [reason]',
158
279
  'add path-exemption <pathPrefix> [reason]',
159
280
  'add dynamic-keyword <keyword> [count]',
@@ -166,6 +287,14 @@ async function main() {
166
287
  'geo summary',
167
288
  'clear blacklist|request-logs',
168
289
  'clear dynamic-keywords',
290
+ 'status',
291
+ 'stats [request-limit]',
292
+ 'logs analyze [limit]',
293
+ 'blacklist migrate [--duration 24h]',
294
+ 'blacklist cleanup',
295
+ 'export [output.json]',
296
+ 'import <input.json>',
297
+ 'model info|export|import|clear [file]',
169
298
  'train',
170
299
  'manifest --framework <name> --routes <routes.json> [--output .aiwaf/paths.json]',
171
300
  'whois <domain|ip>',
@@ -180,6 +309,47 @@ async function main() {
180
309
  if (cmd === 'train') return runTrain();
181
310
  if (cmd === 'pathshell') return runPathShell();
182
311
  if (cmd === 'reset') return runReset([subcmd, ...args].filter(Boolean));
312
+ if (cmd === 'status') return operationalStatus();
313
+ if (cmd === 'stats') return operationalStats(Number(subcmd || 5000));
314
+ if (cmd === 'export') return exportOperationalState(subcmd || 'aiwaf-export.json');
315
+ if (cmd === 'import') return importOperationalState(subcmd);
316
+
317
+ if (cmd === 'logs' && subcmd === 'analyze') {
318
+ return operationalStats(Number(args[0] || 5000));
319
+ }
320
+
321
+ if (cmd === 'blacklist' && subcmd === 'cleanup') {
322
+ const blacklistManager = require('../lib/blacklistManager');
323
+ return print({ ok: true, cleaned: await blacklistManager.cleanupExpired() });
324
+ }
325
+
326
+ if (cmd === 'blacklist' && subcmd === 'migrate') {
327
+ const durationIndex = args.indexOf('--duration');
328
+ const duration = durationIndex >= 0 ? parseDuration(args[durationIndex + 1]) : null;
329
+ const blacklistManager = require('../lib/blacklistManager');
330
+ return print({ ok: true, ...(await blacklistManager.migrateLegacy({ duration })) });
331
+ }
332
+
333
+ if (cmd === 'model') {
334
+ const modelStore = require('../lib/modelStore');
335
+ if (subcmd === 'info') {
336
+ const model = await modelStore.load(process.env);
337
+ return print({ loaded: !!model, metadata: model?.metadata || null });
338
+ }
339
+ if (subcmd === 'export') {
340
+ const model = await modelStore.load(process.env);
341
+ if (!model) return print({ ok: false, error: 'model not found' });
342
+ return print({ ok: true, output: writeJsonFile(args[0] || 'aiwaf-model.json', model) });
343
+ }
344
+ if (subcmd === 'import') {
345
+ const model = readJsonFile(args[0]);
346
+ await modelStore.save(process.env, model, model.metadata || {});
347
+ return print({ ok: true, imported: true });
348
+ }
349
+ if (subcmd === 'clear') {
350
+ return print({ ok: true, removed: await modelStore.remove(process.env) });
351
+ }
352
+ }
183
353
 
184
354
  if (cmd === 'manifest') {
185
355
  const options = parseManifestArgs([subcmd, ...args].filter(Boolean));
@@ -232,6 +402,16 @@ async function main() {
232
402
  return print({ loaded: true, metadata: model.metadata || null });
233
403
  }
234
404
 
405
+ if (cmd === 'list' && subcmd === 'recent-blocks') {
406
+ const blacklistManager = require('../lib/blacklistManager');
407
+ return print(await blacklistManager.getRecentBlocks(Number(args[0] || 24)));
408
+ }
409
+
410
+ if (cmd === 'list' && subcmd === 'top-reasons') {
411
+ const blacklistManager = require('../lib/blacklistManager');
412
+ return print(await blacklistManager.getTopBlockedReasons(Number(args[0] || 10)));
413
+ }
414
+
235
415
  if (cmd === 'add' && subcmd === 'ip-exemption') {
236
416
  const exemptionStore = require('../lib/exemptionStore');
237
417
  const [ip, ...reasonParts] = args;
@@ -241,8 +421,13 @@ async function main() {
241
421
 
242
422
  if (cmd === 'add' && subcmd === 'blacklist') {
243
423
  const blacklistManager = require('../lib/blacklistManager');
244
- const [ip, ...reasonParts] = args;
245
- await blacklistManager.block(ip, reasonParts.join(' ') || 'manual');
424
+ const [ip, ...values] = args;
425
+ const durationIndex = values.indexOf('--duration');
426
+ const permanent = values.includes('--permanent');
427
+ const duration = durationIndex >= 0 ? parseDuration(values[durationIndex + 1]) : undefined;
428
+ const reasonParts = values.filter((value, index) => value !== '--permanent'
429
+ && value !== '--duration' && index !== durationIndex + 1);
430
+ await blacklistManager.block(ip, reasonParts.join(' ') || 'manual', { duration, permanent });
246
431
  return print({ ok: true, ip });
247
432
  }
248
433
 
@@ -345,5 +530,12 @@ main()
345
530
  process.exit(1);
346
531
  })
347
532
  .finally(async () => {
348
- // no-op
533
+ const command = process.argv[2];
534
+ if (!['pathshell', 'train'].includes(command)) {
535
+ try {
536
+ await require('../utils/db').destroy();
537
+ } catch (err) {
538
+ // The requested operation has already completed; cleanup is best effort.
539
+ }
540
+ }
349
541
  });
Binary file
package/index.js CHANGED
@@ -17,6 +17,7 @@ const modelSecurity = require('./lib/modelSecurity');
17
17
  const blockResponses = require('./lib/blockResponses');
18
18
  const KeywordFallbackStore = require('./lib/keywordFallbackStore');
19
19
  const whois = require('./lib/whois');
20
+ const reputation = require('./lib/reputation');
20
21
 
21
22
  function withMiddlewares(selection) {
22
23
  return (opts = {}) => createExpressMiddleware({
@@ -52,6 +53,7 @@ module.exports.modelSecurity = modelSecurity;
52
53
  module.exports.blockResponses = blockResponses;
53
54
  module.exports.KeywordFallbackStore = KeywordFallbackStore;
54
55
  module.exports.whois = whois;
56
+ module.exports.reputation = reputation;
55
57
  module.exports.extractExpressRoutes = pathManifest.extractExpressRoutes;
56
58
  module.exports.extractFastifyRoutes = pathManifest.extractFastifyRoutes;
57
59
  module.exports.extractHapiRoutes = pathManifest.extractHapiRoutes;
@@ -13,10 +13,9 @@ function createExpressLikeResponse(ctx) {
13
13
  if (ctx.response) ctx.response.statusCode = code;
14
14
  },
15
15
  status(code) {
16
+ res.statusCode = code;
16
17
  if (ctx.response?.status) {
17
18
  ctx.response.status(code);
18
- } else {
19
- res.statusCode = code;
20
19
  }
21
20
  res._handled = true;
22
21
  return res;
@@ -1,5 +1,10 @@
1
1
  const { IsolationForest } = require('./isolationForest');
2
- const { createIsolationForest, getWasmStatus } = require('./wasmAdapter');
2
+ const {
3
+ createIsolationForest,
4
+ createIsolationForestFromJSON,
5
+ getWasmStatus,
6
+ analyzeRecentBehavior: analyzeRecentBehaviorWasm
7
+ } = require('./wasmAdapter');
3
8
  const modelStore = require('./modelStore');
4
9
  const requestLogStore = require('./requestLogStore');
5
10
  const { STATIC_KW } = require('./featureUtils');
@@ -23,6 +28,15 @@ async function loadModel(opts = {}) {
23
28
  const modelData = await modelStore.load(opts);
24
29
  if (!modelData) return;
25
30
 
31
+ if (modelData.model_type === 'aiwaf_wasm.IsolationForest' && modelData.model_state) {
32
+ const restored = await createIsolationForestFromJSON(modelData.model_state);
33
+ if (!restored.__aiwafWasm) throw new Error('WASM model cannot be restored without aiwaf-wasm');
34
+ model = restored;
35
+ modelMetadata = modelData.metadata || null;
36
+ trained = true;
37
+ return;
38
+ }
39
+
26
40
  if (modelData.metadata) {
27
41
  modelMetadata = modelData.metadata;
28
42
  model = IsolationForest.fromJSON(modelData);
@@ -70,6 +84,28 @@ function analyzeRecentBehavior(recentData = []) {
70
84
  const recentKwHits = [];
71
85
  let recent404s = 0;
72
86
  const recentBurstCounts = [];
87
+ const timestamps = recentData.map(entry => Number(entry.timestamp || 0)).sort((a, b) => a - b);
88
+
89
+ const lowerBound = target => {
90
+ let left = 0;
91
+ let right = timestamps.length;
92
+ while (left < right) {
93
+ const mid = (left + right) >>> 1;
94
+ if (timestamps[mid] < target) left = mid + 1;
95
+ else right = mid;
96
+ }
97
+ return left;
98
+ };
99
+ const upperBound = target => {
100
+ let left = 0;
101
+ let right = timestamps.length;
102
+ while (left < right) {
103
+ const mid = (left + right) >>> 1;
104
+ if (timestamps[mid] <= target) left = mid + 1;
105
+ else right = mid;
106
+ }
107
+ return left;
108
+ };
73
109
 
74
110
  for (const entry of recentData) {
75
111
  const entryTime = entry.timestamp || 0;
@@ -89,7 +125,7 @@ function analyzeRecentBehavior(recentData = []) {
89
125
  recent404s += 1;
90
126
  }
91
127
 
92
- const entryBurst = recentData.filter(item => Math.abs(entryTime - (item.timestamp || 0)) <= 10000).length;
128
+ const entryBurst = upperBound(entryTime + 10000) - lowerBound(entryTime - 10000);
93
129
  recentBurstCounts.push(entryBurst);
94
130
  }
95
131
 
@@ -128,6 +164,28 @@ function analyzeRecentBehavior(recentData = []) {
128
164
  };
129
165
  }
130
166
 
167
+ async function analyzeRecentBehaviorAccelerated(recentData = []) {
168
+ // Older aiwaf-wasm releases classify these ordinary discovery paths as scans.
169
+ // Also keep the JS semantics for malformed timestamps or non-numeric statuses.
170
+ const safeForWasm = recentData.every(entry =>
171
+ typeof entry.status === 'number'
172
+ && Number.isFinite(entry.timestamp)
173
+ && !/robots\.txt|sitemap\.xml/.test(String(entry.path || '').toLowerCase())
174
+ );
175
+ if (recentData.length > 0 && safeForWasm) {
176
+ const entries = recentData.map(entry => ({
177
+ ...entry,
178
+ timestamp_ms: Number(entry.timestamp || 0),
179
+ kw_check: !exemptions.shouldSkipKeyword('', String(entry.path || ''))
180
+ }));
181
+ const stats = await analyzeRecentBehaviorWasm(entries, STATIC_KW);
182
+ if (stats && typeof stats.should_block === 'boolean' && Number.isFinite(Number(stats.avg_burst))) {
183
+ return stats;
184
+ }
185
+ }
186
+ return analyzeRecentBehavior(recentData);
187
+ }
188
+
131
189
  module.exports = {
132
190
  async init(opts = {}) {
133
191
  minAiLogs = Number.isFinite(Number(opts.AIWAF_MIN_AI_LOGS))
@@ -184,6 +242,7 @@ module.exports = {
184
242
  },
185
243
 
186
244
  analyzeRecentBehavior,
245
+ analyzeRecentBehaviorAccelerated,
187
246
  isScanningPath,
188
247
 
189
248
  maybeLearnKeyword(path, statusCode, opts = {}) {