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.
@@ -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() {
package/lib/csvStore.js CHANGED
@@ -17,13 +17,27 @@ function escapeCsv(value) {
17
17
  }
18
18
 
19
19
  function parseCsvLine(line) {
20
- return (line.match(/("([^"]|"")*"|[^,]+)/g) || []).map(part => {
21
- const trimmed = String(part || '').trim();
22
- if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
23
- return trimmed.slice(1, -1).replace(/""/g, '"');
20
+ const cells = [];
21
+ let value = '';
22
+ let quoted = false;
23
+ for (let index = 0; index < String(line).length; index += 1) {
24
+ const char = String(line)[index];
25
+ if (char === '"') {
26
+ if (quoted && String(line)[index + 1] === '"') {
27
+ value += '"';
28
+ index += 1;
29
+ } else {
30
+ quoted = !quoted;
31
+ }
32
+ } else if (char === ',' && !quoted) {
33
+ cells.push(value.trim());
34
+ value = '';
35
+ } else {
36
+ value += char;
24
37
  }
25
- return trimmed;
26
- });
38
+ }
39
+ cells.push(value.trim());
40
+ return cells;
27
41
  }
28
42
 
29
43
  function readRows(filePath, headers) {
@@ -33,15 +47,18 @@ function readRows(filePath, headers) {
33
47
  if (raw.length === 0) return [];
34
48
 
35
49
  const fileHeader = parseCsvLine(raw[0]);
36
- const startIndex = fileHeader.join(',') === headers.join(',') ? 1 : 0;
50
+ const hasHeader = fileHeader.some(header => headers.includes(header));
51
+ const sourceHeaders = hasHeader ? fileHeader : headers;
52
+ const startIndex = hasHeader ? 1 : 0;
37
53
  const rows = [];
38
54
 
39
55
  for (let i = startIndex; i < raw.length; i += 1) {
40
56
  const cells = parseCsvLine(raw[i]);
41
57
  if (cells.length === 0) continue;
42
58
  const row = {};
43
- headers.forEach((header, index) => {
44
- row[header] = cells[index] ?? '';
59
+ headers.forEach(header => {
60
+ const index = sourceHeaders.indexOf(header);
61
+ row[header] = index >= 0 ? (cells[index] ?? '') : '';
45
62
  });
46
63
  rows.push(row);
47
64
  }
@@ -1,7 +1,17 @@
1
1
  // lib/dynamicKeyword.js
2
2
  const dynamicKeywordStore = require('./dynamicKeywordStore');
3
+ const { createKeywordMatcher } = require('./wasmAdapter');
3
4
 
4
5
  let opts, counts;
6
+ let activeKeywords = [];
7
+ let matcherPromise = null;
8
+
9
+ function refreshActiveKeywords() {
10
+ activeKeywords = Object.entries(counts)
11
+ .filter(([, count]) => count > opts.dynamicTopN)
12
+ .map(([keyword]) => keyword);
13
+ matcherPromise = null;
14
+ }
5
15
 
6
16
  module.exports = {
7
17
  init(o = {}) {
@@ -9,11 +19,13 @@ module.exports = {
9
19
  const topN = o.dynamicTopN ?? o.DYNAMIC_TOP_N ?? 10;
10
20
  opts = { dynamicTopN: topN };
11
21
  counts = {};
22
+ refreshActiveKeywords();
12
23
  dynamicKeywordStore.initialize().catch(() => {});
13
24
  dynamicKeywordStore.list(2000).then(rows => {
14
25
  rows.forEach(row => {
15
26
  counts[row.keyword] = Number(row.count || 0);
16
27
  });
28
+ refreshActiveKeywords();
17
29
  }).catch(() => {});
18
30
  },
19
31
 
@@ -21,7 +33,9 @@ module.exports = {
21
33
  segments.forEach(s => {
22
34
  const key = String(s).toLowerCase();
23
35
  if (!key) return;
36
+ const prior = counts[key] || 0;
24
37
  counts[key] = (counts[key] || 0) + 1;
38
+ if (prior <= opts.dynamicTopN && counts[key] > opts.dynamicTopN) refreshActiveKeywords();
25
39
  dynamicKeywordStore.increment(key).catch(() => {});
26
40
  });
27
41
  },
@@ -30,13 +44,20 @@ module.exports = {
30
44
  const segments = String(path || '').split('/').filter(s => s.length > 3);
31
45
  module.exports.learnSegments(segments);
32
46
  },
33
-
34
- check(path) {
35
- // only block segments whose count exceeds the threshold
47
+
48
+ check(path) {
49
+ // only block segments whose count exceeds the threshold
50
+ const pathLower = String(path || '').toLowerCase();
51
+ return activeKeywords.find(keyword => pathLower.includes(keyword)) || null;
52
+ },
53
+
54
+ async checkAccelerated(path) {
55
+ if (!activeKeywords.length) return null;
36
56
  const pathLower = String(path || '').toLowerCase();
37
- return Object.entries(counts)
38
- .find(([seg, cnt]) => cnt > opts.dynamicTopN && pathLower.includes(seg))
39
- ?. [0] // return the segment string
40
- || null;
57
+ if (!matcherPromise) matcherPromise = createKeywordMatcher(activeKeywords);
58
+ const pending = matcherPromise;
59
+ const matcher = await pending;
60
+ if (pending !== matcherPromise) return module.exports.check(path);
61
+ return matcher ? matcher.firstMatch(pathLower) : module.exports.check(path);
41
62
  }
42
63
  };
@@ -12,6 +12,7 @@ function createExpressLikeResponse(reply) {
12
12
  raw.statusCode = code;
13
13
  },
14
14
  status(code) {
15
+ res.statusCode = code;
15
16
  reply.code(code);
16
17
  return res;
17
18
  },