aiwaf 1.0.0 → 1.0.1

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,13 +1,87 @@
1
1
  const path = require('path');
2
2
  const db = require('../utils/db');
3
3
  const csvStore = require('./csvStore');
4
+ const {
5
+ FIRST_BLOCK_SECONDS,
6
+ evaluateReputation,
7
+ formatBlockReason,
8
+ normalizeReason
9
+ } = require('./reputation');
4
10
 
5
- const headers = ['id', 'ip_address', 'reason', 'blocked_at'];
11
+ const headers = [
12
+ 'id', 'ip_address', 'reason', 'reputation_reason', 'reasons', 'score', 'offenses',
13
+ 'blocked_at', 'expires_at', 'duration', 'permanent', 'extended_request_info'
14
+ ];
6
15
  const csvPath = process.env.AIWAF_BLOCKED_IPS_CSV_PATH || path.join('logs', 'storage', 'blocked_ips.csv');
7
16
 
8
17
  let initialized = false;
9
18
  let dbAvailable = true;
10
19
 
20
+ const schemaColumns = {
21
+ reputation_reason: table => table.string('reputation_reason').defaultTo(''),
22
+ reasons: table => table.text('reasons').defaultTo('[]'),
23
+ score: table => table.integer('score').defaultTo(0),
24
+ offenses: table => table.integer('offenses').defaultTo(0),
25
+ expires_at: table => table.float('expires_at').nullable(),
26
+ duration: table => table.integer('duration').nullable(),
27
+ permanent: table => table.boolean('permanent').defaultTo(false),
28
+ extended_request_info: table => table.text('extended_request_info').defaultTo('{}')
29
+ };
30
+
31
+ function parseJson(value, fallback) {
32
+ if (value && typeof value === 'object') return value;
33
+ try { return value ? JSON.parse(value) : fallback; } catch (err) { return fallback; }
34
+ }
35
+
36
+ function toTimestamp(value) {
37
+ if (value === null || value === undefined || value === '') return null;
38
+ const numeric = Number(value);
39
+ if (Number.isFinite(numeric)) return numeric;
40
+ const parsed = new Date(value).getTime();
41
+ return Number.isFinite(parsed) ? parsed / 1000 : null;
42
+ }
43
+
44
+ function normalizeRow(row = {}) {
45
+ const reason = normalizeReason(row.reason || 'legacy block');
46
+ const legacy = !row.reputation_reason;
47
+ return {
48
+ ...row,
49
+ ip_address: String(row.ip_address || row.ip || '').trim(),
50
+ reason,
51
+ reputation_reason: row.reputation_reason || (legacy ? 'legacy_blacklist' : ''),
52
+ reasons: parseJson(row.reasons, legacy ? ['legacy_blacklist', reason] : [reason]),
53
+ score: Number(row.score || (legacy ? 100 : 0)),
54
+ offenses: Number(row.offenses || (legacy ? 1 : 0)),
55
+ blocked_at: toTimestamp(row.blocked_at) || Date.now() / 1000,
56
+ expires_at: toTimestamp(row.expires_at),
57
+ duration: row.duration === '' || row.duration === null || row.duration === undefined ? null : Number(row.duration),
58
+ permanent: row.permanent === true || row.permanent === 1 || String(row.permanent) === '1' || String(row.permanent).toLowerCase() === 'true' || legacy,
59
+ extended_request_info: parseJson(row.extended_request_info, {})
60
+ };
61
+ }
62
+
63
+ function serializeRow(row) {
64
+ return {
65
+ ...row,
66
+ reasons: JSON.stringify(row.reasons || []),
67
+ extended_request_info: JSON.stringify(row.extended_request_info || {}),
68
+ permanent: row.permanent ? 1 : 0
69
+ };
70
+ }
71
+
72
+ function isActive(row, now = Date.now() / 1000) {
73
+ return !!row && (row.permanent || !row.expires_at || Number(row.expires_at) > now);
74
+ }
75
+
76
+ async function ensureDbColumns() {
77
+ if (typeof db.schema.hasColumn !== 'function' || typeof db.schema.table !== 'function') return;
78
+ for (const [name, addColumn] of Object.entries(schemaColumns)) {
79
+ if (!await db.schema.hasColumn('blocked_ips', name)) {
80
+ await db.schema.table('blocked_ips', addColumn);
81
+ }
82
+ }
83
+ }
84
+
11
85
  async function initialize() {
12
86
  if (initialized) return dbAvailable;
13
87
 
@@ -19,7 +93,10 @@ async function initialize() {
19
93
  table.string('ip_address').unique().notNullable();
20
94
  table.string('reason').defaultTo('WAF blocked');
21
95
  table.timestamp('blocked_at').defaultTo(db.fn.now());
96
+ Object.values(schemaColumns).forEach(addColumn => addColumn(table));
22
97
  });
98
+ } else {
99
+ await ensureDbColumns();
23
100
  }
24
101
  dbAvailable = true;
25
102
  } catch (err) {
@@ -36,52 +113,93 @@ async function initialize() {
36
113
  }
37
114
 
38
115
  function csvRows() {
39
- return csvStore.readRows(csvPath, headers);
116
+ return csvStore.readRows(csvPath, headers).map(normalizeRow);
117
+ }
118
+
119
+ async function rawRow(ip) {
120
+ const normalizedIp = String(ip || '').trim();
121
+ if (await initialize()) {
122
+ try {
123
+ const row = await db('blocked_ips').where('ip_address', normalizedIp).first();
124
+ return row ? normalizeRow(row) : null;
125
+ } catch (err) {
126
+ dbAvailable = false;
127
+ }
128
+ }
129
+ return csvRows().find(row => row.ip_address === normalizedIp) || null;
130
+ }
131
+
132
+ async function saveRow(row) {
133
+ if (dbAvailable) {
134
+ try {
135
+ const payload = serializeRow(row);
136
+ delete payload.id;
137
+ await db('blocked_ips').insert(payload).onConflict('ip_address').merge();
138
+ return;
139
+ } catch (err) {
140
+ dbAvailable = false;
141
+ }
142
+ }
143
+ const rows = csvRows();
144
+ const index = rows.findIndex(item => item.ip_address === row.ip_address);
145
+ const stored = { ...row, id: index >= 0 ? rows[index].id : csvStore.nextId(rows) };
146
+ if (index >= 0) rows[index] = stored;
147
+ else rows.push(stored);
148
+ csvStore.writeRows(csvPath, headers, rows.map(serializeRow));
40
149
  }
41
150
 
42
151
  module.exports = {
43
152
  async isBlocked(ip) {
44
- const normalizedIp = String(ip || '').trim();
45
- const useDb = await initialize();
46
- if (useDb) {
47
- try {
48
- const row = await db('blocked_ips').where('ip_address', normalizedIp).first();
49
- return !!row;
50
- } catch (err) {
51
- dbAvailable = false;
52
- }
153
+ const row = await rawRow(ip);
154
+ if (!isActive(row)) {
155
+ if (row) await this.unblock(ip);
156
+ return false;
53
157
  }
54
-
55
- return csvRows().some(row => String(row.ip_address) === normalizedIp);
158
+ return true;
56
159
  },
57
160
 
58
- async block(ip, reason = 'WAF blocked') {
161
+ async block(ip, reason = 'WAF blocked', options = {}) {
59
162
  const normalizedIp = String(ip || '').trim();
60
163
  if (!normalizedIp) return false;
61
-
62
- const useDb = await initialize();
63
- if (useDb) {
164
+ if (options.checkExemptions !== false) {
64
165
  try {
65
- await db('blocked_ips').insert({ ip_address: normalizedIp, reason }).onConflict('ip_address').ignore();
66
- return true;
166
+ const exemptionStore = require('./exemptionStore');
167
+ if (await exemptionStore.isIpExempt(normalizedIp)) return false;
67
168
  } catch (err) {
68
- dbAvailable = false;
169
+ // Storage failures must not disable blocking.
69
170
  }
70
171
  }
71
-
72
- const rows = csvRows();
73
- if (rows.some(row => String(row.ip_address) === normalizedIp)) return true;
74
-
75
- rows.push({
76
- id: csvStore.nextId(rows),
172
+ const now = Number(options.now ?? Date.now() / 1000);
173
+ const existing = await rawRow(normalizedIp);
174
+ const decision = evaluateReputation({ existing: existing || {}, reason, now });
175
+ const explicitDuration = options.duration === undefined ? null : Number(options.duration);
176
+ const permanent = options.permanent === true || explicitDuration === 0;
177
+ const duration = permanent ? null : (explicitDuration || decision.duration || FIRST_BLOCK_SECONDS);
178
+ await saveRow({
179
+ ...(existing || {}),
77
180
  ip_address: normalizedIp,
78
- reason,
79
- blocked_at: new Date().toISOString()
181
+ reason: normalizeReason(reason),
182
+ reputation_reason: formatBlockReason(decision),
183
+ reasons: decision.reasons,
184
+ score: decision.score,
185
+ offenses: decision.offenses,
186
+ blocked_at: now,
187
+ expires_at: permanent ? null : now + duration,
188
+ duration,
189
+ permanent,
190
+ extended_request_info: options.extendedRequestInfo || existing?.extended_request_info || {}
80
191
  });
81
- csvStore.writeRows(csvPath, headers, rows);
82
192
  return true;
83
193
  },
84
194
 
195
+ blockTemporary(ip, reason, minutes = 60, extendedRequestInfo = {}) {
196
+ return this.block(ip, reason, { duration: Number(minutes) * 60, extendedRequestInfo });
197
+ },
198
+
199
+ blockPermanent(ip, reason, extendedRequestInfo = {}) {
200
+ return this.block(ip, reason, { permanent: true, extendedRequestInfo });
201
+ },
202
+
85
203
  async unblock(ip) {
86
204
  const normalizedIp = String(ip || '').trim();
87
205
  const useDb = await initialize();
@@ -96,21 +214,123 @@ module.exports = {
96
214
 
97
215
  const rows = csvRows();
98
216
  const filtered = rows.filter(row => String(row.ip_address) !== normalizedIp);
99
- csvStore.writeRows(csvPath, headers, filtered);
217
+ csvStore.writeRows(csvPath, headers, filtered.map(serializeRow));
100
218
  return filtered.length !== rows.length;
101
219
  },
102
220
 
103
- async getBlockedIPs() {
221
+ async getBlockedIPs({ activeOnly = true } = {}) {
222
+ let rows;
104
223
  const useDb = await initialize();
105
224
  if (useDb) {
106
225
  try {
107
- return await db('blocked_ips').select('*').orderBy('blocked_at', 'desc');
226
+ rows = (await db('blocked_ips').select('*').orderBy('blocked_at', 'desc')).map(normalizeRow);
108
227
  } catch (err) {
109
228
  dbAvailable = false;
110
229
  }
111
230
  }
231
+ rows = rows || csvRows().sort((a, b) => b.blocked_at - a.blocked_at);
232
+ return activeOnly ? rows.filter(row => isActive(row)) : rows;
233
+ },
234
+
235
+ async getBlockInfo(ip) {
236
+ return rawRow(ip);
237
+ },
112
238
 
113
- return csvRows().sort((a, b) => String(b.blocked_at).localeCompare(String(a.blocked_at)));
239
+ async cleanupExpired(now = Date.now() / 1000) {
240
+ const rows = await this.getBlockedIPs({ activeOnly: false });
241
+ const expired = rows.filter(row => !row.permanent && row.expires_at && row.expires_at <= now);
242
+ for (const row of expired) await this.unblock(row.ip_address);
243
+ return expired.length;
244
+ },
245
+
246
+ async getStatistics() {
247
+ const all = await this.getBlockedIPs({ activeOnly: false });
248
+ const active = all.filter(row => isActive(row));
249
+ const reasonCounts = {};
250
+ active.forEach(row => { reasonCounts[row.reason] = (reasonCounts[row.reason] || 0) + 1; });
251
+ return {
252
+ total: all.length,
253
+ active: active.length,
254
+ expired: all.length - active.length,
255
+ permanent: active.filter(row => row.permanent).length,
256
+ temporary: active.filter(row => !row.permanent).length,
257
+ average_score: active.length ? active.reduce((sum, row) => sum + row.score, 0) / active.length : 0,
258
+ reason_counts: reasonCounts
259
+ };
260
+ },
261
+
262
+ async getRecentBlocks(hours = 24) {
263
+ const cutoff = Date.now() / 1000 - Number(hours) * 3600;
264
+ return (await this.getBlockedIPs()).filter(row => row.blocked_at >= cutoff);
265
+ },
266
+
267
+ async getTopBlockedReasons(limit = 10) {
268
+ const stats = await this.getStatistics();
269
+ return Object.entries(stats.reason_counts)
270
+ .sort((a, b) => b[1] - a[1])
271
+ .slice(0, Number(limit))
272
+ .map(([reason, count]) => ({ reason, count }));
273
+ },
274
+
275
+ async bulkBlock(ips, reason, options = {}) {
276
+ const pairs = await Promise.all((ips || []).map(async ip => [ip, await this.block(ip, reason, options)]));
277
+ return Object.fromEntries(pairs);
278
+ },
279
+
280
+ async bulkUnblock(ips) {
281
+ const pairs = await Promise.all((ips || []).map(async ip => [ip, await this.unblock(ip)]));
282
+ return Object.fromEntries(pairs);
283
+ },
284
+
285
+ async addToWhitelist(ip, reason = 'Manual whitelist') {
286
+ const exemptionStore = require('./exemptionStore');
287
+ await exemptionStore.addIp(ip, reason);
288
+ await this.unblock(ip);
289
+ return true;
290
+ },
291
+
292
+ async removeFromWhitelist(ip) {
293
+ return require('./exemptionStore').removeIp(ip);
294
+ },
295
+
296
+ async isWhitelisted(ip) {
297
+ return require('./exemptionStore').isIpExempt(ip);
298
+ },
299
+
300
+ async getWhitelist() {
301
+ const exemptionStore = require('./exemptionStore');
302
+ return { ips: await exemptionStore.listIps(), paths: await exemptionStore.listPaths() };
303
+ },
304
+
305
+ async migrateLegacy({ duration = null, now = Date.now() / 1000 } = {}) {
306
+ const rows = await this.getBlockedIPs({ activeOnly: false });
307
+ let changed = 0;
308
+ for (const original of rows) {
309
+ if (original.reputation_reason && original.reputation_reason !== 'legacy_blacklist') continue;
310
+ const row = normalizeRow(original);
311
+ row.reputation_reason = duration ? 'legacy_blacklist_converted' : 'legacy_blacklist';
312
+ row.permanent = !duration;
313
+ row.duration = duration || null;
314
+ row.expires_at = duration ? Number(now) + Number(duration) : null;
315
+ await saveRow(row);
316
+ changed += 1;
317
+ }
318
+ return { total: rows.length, changed };
319
+ },
320
+
321
+ async exportRecords() {
322
+ return this.getBlockedIPs({ activeOnly: false });
323
+ },
324
+
325
+ async importRecords(rows = []) {
326
+ let imported = 0;
327
+ for (const raw of rows) {
328
+ const row = normalizeRow(raw);
329
+ if (!row.ip_address) continue;
330
+ await saveRow(row);
331
+ imported += 1;
332
+ }
333
+ return imported;
114
334
  },
115
335
 
116
336
  async clear() {