aiwaf 1.1.4 → 1.1.6

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.
@@ -0,0 +1,364 @@
1
+ const path = require('path');
2
+ const db = require('../utils/db');
3
+ const csvStore = require('./csvStore');
4
+ const {
5
+ FIRST_BLOCK_SECONDS,
6
+ evaluateReputation,
7
+ formatBlockReason,
8
+ normalizeReason
9
+ } = require('./reputation');
10
+
11
+ const headers = [
12
+ 'id', 'ip_address', 'reason', 'reputation_reason', 'reasons', 'score', 'offenses',
13
+ 'blocked_at', 'expires_at', 'duration', 'permanent', 'extended_request_info'
14
+ ];
15
+ const csvPath = process.env.AIWAF_BLOCKED_IPS_CSV_PATH || path.join('logs', 'storage', 'blocked_ips.csv');
16
+
17
+ let initialized = false;
18
+ let dbAvailable = true;
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
+
85
+ async function initialize() {
86
+ if (initialized) return dbAvailable;
87
+
88
+ try {
89
+ const exists = await db.schema.hasTable('blocked_ips');
90
+ if (!exists) {
91
+ await db.schema.createTable('blocked_ips', table => {
92
+ table.increments('id').primary();
93
+ table.string('ip_address').unique().notNullable();
94
+ table.string('reason').defaultTo('WAF blocked');
95
+ table.timestamp('blocked_at').defaultTo(db.fn.now());
96
+ Object.values(schemaColumns).forEach(addColumn => addColumn(table));
97
+ });
98
+ } else {
99
+ await ensureDbColumns();
100
+ }
101
+ dbAvailable = true;
102
+ } catch (err) {
103
+ dbAvailable = false;
104
+ }
105
+
106
+ initialized = true;
107
+ return dbAvailable;
108
+ }
109
+
110
+ function csvRows() {
111
+ return csvStore.readRows(csvPath, headers).map(normalizeRow);
112
+ }
113
+
114
+ async function rawRow(ip) {
115
+ const normalizedIp = String(ip || '').trim();
116
+ if (await initialize()) {
117
+ try {
118
+ const row = await db('blocked_ips').where('ip_address', normalizedIp).first();
119
+ return row ? normalizeRow(row) : null;
120
+ } catch (err) {
121
+ dbAvailable = false;
122
+ }
123
+ }
124
+ return csvRows().find(row => row.ip_address === normalizedIp) || null;
125
+ }
126
+
127
+ async function saveRow(row) {
128
+ if (dbAvailable) {
129
+ try {
130
+ const payload = serializeRow(row);
131
+ delete payload.id;
132
+ await db('blocked_ips').insert(payload).onConflict('ip_address').merge();
133
+ return;
134
+ } catch (err) {
135
+ dbAvailable = false;
136
+ }
137
+ }
138
+ await csvStore.updateRows(csvPath, headers, current => {
139
+ const rows = current.map(normalizeRow);
140
+ const index = rows.findIndex(item => item.ip_address === row.ip_address);
141
+ const stored = { ...row, id: index >= 0 ? rows[index].id : csvStore.nextId(rows) };
142
+ if (index >= 0) rows[index] = stored;
143
+ else rows.push(stored);
144
+ return { rows: rows.map(serializeRow) };
145
+ });
146
+ }
147
+
148
+ module.exports = {
149
+ async isBlocked(ip) {
150
+ const row = await rawRow(ip);
151
+ // An expired snapshot is not authority to delete a concurrent refresh.
152
+ return isActive(row);
153
+ },
154
+
155
+ async block(ip, reason = 'WAF blocked', options = {}) {
156
+ const normalizedIp = String(ip || '').trim();
157
+ if (!normalizedIp) return false;
158
+ if (options.checkExemptions !== false) {
159
+ try {
160
+ const exemptionStore = require('./exemptionStore');
161
+ if (await exemptionStore.isIpExempt(normalizedIp)) return false;
162
+ } catch (err) {
163
+ // Storage failures must not disable blocking.
164
+ }
165
+ }
166
+ const now = Number(options.now ?? Date.now() / 1000);
167
+ const existing = await rawRow(normalizedIp);
168
+ const decision = evaluateReputation({ existing: existing || {}, reason, now });
169
+ const explicitDuration = options.duration === undefined ? null : Number(options.duration);
170
+ const permanent = options.permanent === true || explicitDuration === 0;
171
+ const duration = permanent ? null : (explicitDuration || decision.duration || FIRST_BLOCK_SECONDS);
172
+ await saveRow({
173
+ ...(existing || {}),
174
+ ip_address: normalizedIp,
175
+ reason: normalizeReason(reason),
176
+ reputation_reason: formatBlockReason(decision),
177
+ reasons: decision.reasons,
178
+ score: decision.score,
179
+ offenses: decision.offenses,
180
+ blocked_at: now,
181
+ expires_at: permanent ? null : now + duration,
182
+ duration,
183
+ permanent,
184
+ extended_request_info: options.extendedRequestInfo || existing?.extended_request_info || {}
185
+ });
186
+ return true;
187
+ },
188
+
189
+ blockTemporary(ip, reason, minutes = 60, extendedRequestInfo = {}) {
190
+ return this.block(ip, reason, { duration: Number(minutes) * 60, extendedRequestInfo });
191
+ },
192
+
193
+ blockPermanent(ip, reason, extendedRequestInfo = {}) {
194
+ return this.block(ip, reason, { permanent: true, extendedRequestInfo });
195
+ },
196
+
197
+ async unblock(ip) {
198
+ const normalizedIp = String(ip || '').trim();
199
+ const useDb = await initialize();
200
+ if (useDb) {
201
+ try {
202
+ const deleted = await db('blocked_ips').where('ip_address', normalizedIp).del();
203
+ return deleted > 0;
204
+ } catch (err) {
205
+ dbAvailable = false;
206
+ }
207
+ }
208
+
209
+ return csvStore.updateRows(csvPath, headers, current => {
210
+ const rows = current.map(normalizeRow);
211
+ const filtered = rows.filter(row => row.ip_address !== normalizedIp);
212
+ return { rows: filtered.map(serializeRow), result: filtered.length !== rows.length };
213
+ });
214
+ },
215
+
216
+ async getBlockedIPs({ activeOnly = true } = {}) {
217
+ let rows;
218
+ const useDb = await initialize();
219
+ if (useDb) {
220
+ try {
221
+ rows = (await db('blocked_ips').select('*').orderBy('blocked_at', 'desc')).map(normalizeRow);
222
+ } catch (err) {
223
+ dbAvailable = false;
224
+ }
225
+ }
226
+ rows = rows || csvRows().sort((a, b) => b.blocked_at - a.blocked_at);
227
+ return activeOnly ? rows.filter(row => isActive(row)) : rows;
228
+ },
229
+
230
+ async getBlockInfo(ip) {
231
+ return rawRow(ip);
232
+ },
233
+
234
+ async cleanupExpired(now = Date.now() / 1000) {
235
+ if (await initialize()) {
236
+ try {
237
+ // Evaluate expiry in the DELETE itself, against the current row.
238
+ return await db('blocked_ips').where('permanent', false)
239
+ .whereNotNull('reputation_reason').whereNot('reputation_reason', '')
240
+ .where('expires_at', '>', 0).where('expires_at', '<=', now).del();
241
+ } catch (err) {
242
+ dbAvailable = false;
243
+ }
244
+ }
245
+ return csvStore.updateRows(csvPath, headers, current => {
246
+ const rows = current.map(normalizeRow);
247
+ const active = rows.filter(row => isActive(row, now));
248
+ return { rows: active.map(serializeRow), result: rows.length - active.length };
249
+ });
250
+ },
251
+
252
+ async getStatistics() {
253
+ const all = await this.getBlockedIPs({ activeOnly: false });
254
+ const active = all.filter(row => isActive(row));
255
+ const reasonCounts = {};
256
+ active.forEach(row => { reasonCounts[row.reason] = (reasonCounts[row.reason] || 0) + 1; });
257
+ return {
258
+ total: all.length,
259
+ active: active.length,
260
+ expired: all.length - active.length,
261
+ permanent: active.filter(row => row.permanent).length,
262
+ temporary: active.filter(row => !row.permanent).length,
263
+ average_score: active.length ? active.reduce((sum, row) => sum + row.score, 0) / active.length : 0,
264
+ reason_counts: reasonCounts
265
+ };
266
+ },
267
+
268
+ async getRecentBlocks(hours = 24) {
269
+ const cutoff = Date.now() / 1000 - Number(hours) * 3600;
270
+ return (await this.getBlockedIPs()).filter(row => row.blocked_at >= cutoff);
271
+ },
272
+
273
+ async getTopBlockedReasons(limit = 10) {
274
+ const stats = await this.getStatistics();
275
+ return Object.entries(stats.reason_counts)
276
+ .sort((a, b) => b[1] - a[1])
277
+ .slice(0, Number(limit))
278
+ .map(([reason, count]) => ({ reason, count }));
279
+ },
280
+
281
+ async bulkBlock(ips, reason, options = {}) {
282
+ const pairs = await Promise.all((ips || []).map(async ip => [ip, await this.block(ip, reason, options)]));
283
+ return Object.fromEntries(pairs);
284
+ },
285
+
286
+ async bulkUnblock(ips) {
287
+ const pairs = await Promise.all((ips || []).map(async ip => [ip, await this.unblock(ip)]));
288
+ return Object.fromEntries(pairs);
289
+ },
290
+
291
+ async addToAllowlist(ip, reason = 'Manual allowlist') {
292
+ const exemptionStore = require('./exemptionStore');
293
+ await exemptionStore.addIp(ip, reason);
294
+ await this.unblock(ip);
295
+ return true;
296
+ },
297
+
298
+ async removeFromAllowlist(ip) {
299
+ return require('./exemptionStore').removeIp(ip);
300
+ },
301
+
302
+ async isAllowlisted(ip) {
303
+ return require('./exemptionStore').isIpExempt(ip);
304
+ },
305
+
306
+ async getAllowlist() {
307
+ const exemptionStore = require('./exemptionStore');
308
+ return { ips: await exemptionStore.listIps(), paths: await exemptionStore.listPaths() };
309
+ },
310
+
311
+ async migrateLegacy({ duration = null, now = Date.now() / 1000 } = {}) {
312
+ const rows = await this.getBlockedIPs({ activeOnly: false });
313
+ let changed = 0;
314
+ for (const original of rows) {
315
+ if (original.reputation_reason && original.reputation_reason !== 'legacy_blacklist') continue;
316
+ const row = normalizeRow(original);
317
+ row.reputation_reason = duration ? 'legacy_blacklist_converted' : 'legacy_blacklist';
318
+ row.permanent = !duration;
319
+ row.duration = duration || null;
320
+ row.expires_at = duration ? Number(now) + Number(duration) : null;
321
+ await saveRow(row);
322
+ changed += 1;
323
+ }
324
+ return { total: rows.length, changed };
325
+ },
326
+
327
+ async exportRecords() {
328
+ return this.getBlockedIPs({ activeOnly: false });
329
+ },
330
+
331
+ async importRecords(rows = []) {
332
+ let imported = 0;
333
+ for (const raw of rows) {
334
+ const row = normalizeRow(raw);
335
+ if (!row.ip_address) continue;
336
+ await saveRow(row);
337
+ imported += 1;
338
+ }
339
+ return imported;
340
+ },
341
+
342
+ async clear() {
343
+ const useDb = await initialize();
344
+ if (useDb) {
345
+ try {
346
+ return await db('blocked_ips').del();
347
+ } catch (err) {
348
+ dbAvailable = false;
349
+ }
350
+ }
351
+
352
+ return csvStore.updateRows(csvPath, headers, rows => ({ rows: [], result: rows.length }));
353
+ },
354
+
355
+ async initialize() {
356
+ return initialize();
357
+ }
358
+ };
359
+
360
+ // Compatibility method aliases; new applications should use allowlist names.
361
+ module.exports.addToWhitelist = module.exports.addToAllowlist;
362
+ module.exports.removeFromWhitelist = module.exports.removeFromAllowlist;
363
+ module.exports.isWhitelisted = module.exports.isAllowlisted;
364
+ module.exports.getWhitelist = module.exports.getAllowlist;
package/lib/csvStore.js CHANGED
@@ -81,7 +81,7 @@ function writeRows(filePath, headers, rows) {
81
81
  }
82
82
  }
83
83
 
84
- // All blacklist mutations use this lock and read the current file inside it.
84
+ // All blocklist mutations use this lock and read the current file inside it.
85
85
  // A crash leaves the lock in place; recovery must first stop the owning writer.
86
86
  async function updateRows(filePath, headers, update, timeoutMs = 60000) {
87
87
  filePath = path.resolve(filePath);
package/lib/geoBlocker.js CHANGED
@@ -2,6 +2,7 @@ const fs = require('fs');
2
2
  const path = require('path');
3
3
  const geoStore = require('./geoStore');
4
4
  const { evaluateGeoPolicy } = require('./geoPolicy');
5
+ const { getRequestIp } = require('./runtimeUtils');
5
6
 
6
7
  let config = {
7
8
  enabled: false,
@@ -19,13 +20,6 @@ function normalizeCountry(value) {
19
20
  return String(value || '').trim().toUpperCase();
20
21
  }
21
22
 
22
- function getRequestIp(req) {
23
- const rawIp = req.headers?.['x-forwarded-for']
24
- ? String(req.headers['x-forwarded-for']).split(',')[0].trim()
25
- : (req.ip || req.connection?.remoteAddress || req.socket?.remoteAddress || '');
26
- return String(rawIp).replace(/^::ffff:/, '');
27
- }
28
-
29
23
  function getCachedCountry(ip) {
30
24
  if (!ip || config.cacheSeconds <= 0) return '';
31
25
  const key = `${config.cachePrefix}${ip}`;