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
@@ -0,0 +1,204 @@
1
+ const path = require('path');
2
+ const db = require('../utils/db');
3
+ const csvStore = require('./csvStore');
4
+
5
+ const ipHeaders = ['id', 'ip_address', 'reason', 'created_at'];
6
+ const pathHeaders = ['id', 'path_prefix', 'reason', 'created_at'];
7
+
8
+ const ipCsvPath = process.env.AIWAF_IP_EXEMPTIONS_CSV_PATH || path.join('logs', 'storage', 'ip_exemptions.csv');
9
+ const pathCsvPath = process.env.AIWAF_PATH_EXEMPTIONS_CSV_PATH || path.join('logs', 'storage', 'path_exemptions.csv');
10
+
11
+ let initialized = false;
12
+ let dbAvailable = true;
13
+
14
+ async function initialize() {
15
+ if (initialized) return dbAvailable;
16
+
17
+ try {
18
+ const hasIp = await db.schema.hasTable('ip_exemptions');
19
+ if (!hasIp) {
20
+ await db.schema.createTable('ip_exemptions', table => {
21
+ table.increments('id').primary();
22
+ table.string('ip_address').notNullable().unique();
23
+ table.string('reason').defaultTo('manual');
24
+ table.timestamp('created_at').defaultTo(db.fn.now());
25
+ });
26
+ }
27
+
28
+ const hasPath = await db.schema.hasTable('path_exemptions');
29
+ if (!hasPath) {
30
+ await db.schema.createTable('path_exemptions', table => {
31
+ table.increments('id').primary();
32
+ table.string('path_prefix').notNullable().unique();
33
+ table.string('reason').defaultTo('manual');
34
+ table.timestamp('created_at').defaultTo(db.fn.now());
35
+ });
36
+ }
37
+
38
+ dbAvailable = true;
39
+ } catch (err) {
40
+ dbAvailable = false;
41
+ }
42
+
43
+ if (!dbAvailable) {
44
+ csvStore.writeRows(ipCsvPath, ipHeaders, csvStore.readRows(ipCsvPath, ipHeaders));
45
+ csvStore.writeRows(pathCsvPath, pathHeaders, csvStore.readRows(pathCsvPath, pathHeaders));
46
+ }
47
+
48
+ initialized = true;
49
+ return dbAvailable;
50
+ }
51
+
52
+ function ipRows() {
53
+ return csvStore.readRows(ipCsvPath, ipHeaders);
54
+ }
55
+
56
+ function pathRows() {
57
+ return csvStore.readRows(pathCsvPath, pathHeaders);
58
+ }
59
+
60
+ module.exports = {
61
+ async initialize() {
62
+ await initialize();
63
+ },
64
+
65
+ async addIp(ip, reason = 'manual') {
66
+ const normalized = String(ip || '').trim();
67
+ if (!normalized) return;
68
+
69
+ if (await initialize()) {
70
+ try {
71
+ await db('ip_exemptions').insert({ ip_address: normalized, reason }).onConflict('ip_address').ignore();
72
+ return;
73
+ } catch (err) {
74
+ dbAvailable = false;
75
+ }
76
+ }
77
+
78
+ const rows = ipRows();
79
+ if (rows.some(row => String(row.ip_address) === normalized)) return;
80
+ rows.push({ id: csvStore.nextId(rows), ip_address: normalized, reason, created_at: new Date().toISOString() });
81
+ csvStore.writeRows(ipCsvPath, ipHeaders, rows);
82
+ },
83
+
84
+ async removeIp(ip) {
85
+ const normalized = String(ip || '').trim();
86
+ if (await initialize()) {
87
+ try {
88
+ return db('ip_exemptions').where('ip_address', normalized).del();
89
+ } catch (err) {
90
+ dbAvailable = false;
91
+ }
92
+ }
93
+
94
+ const rows = ipRows();
95
+ const filtered = rows.filter(row => String(row.ip_address) !== normalized);
96
+ csvStore.writeRows(ipCsvPath, ipHeaders, filtered);
97
+ return rows.length - filtered.length;
98
+ },
99
+
100
+ async listIps() {
101
+ if (await initialize()) {
102
+ try {
103
+ return db('ip_exemptions').select('*').orderBy('created_at', 'desc');
104
+ } catch (err) {
105
+ dbAvailable = false;
106
+ }
107
+ }
108
+
109
+ return ipRows().sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
110
+ },
111
+
112
+ async isIpExempt(ip) {
113
+ const normalized = String(ip || '').trim();
114
+ if (await initialize()) {
115
+ try {
116
+ const row = await db('ip_exemptions').where('ip_address', normalized).first();
117
+ return !!row;
118
+ } catch (err) {
119
+ dbAvailable = false;
120
+ }
121
+ }
122
+
123
+ return ipRows().some(row => String(row.ip_address) === normalized);
124
+ },
125
+
126
+ async addPath(pathPrefix, reason = 'manual') {
127
+ const normalized = String(pathPrefix || '').trim();
128
+ if (!normalized) return;
129
+
130
+ if (await initialize()) {
131
+ try {
132
+ await db('path_exemptions').insert({ path_prefix: normalized, reason }).onConflict('path_prefix').ignore();
133
+ return;
134
+ } catch (err) {
135
+ dbAvailable = false;
136
+ }
137
+ }
138
+
139
+ const rows = pathRows();
140
+ if (rows.some(row => String(row.path_prefix) === normalized)) return;
141
+ rows.push({ id: csvStore.nextId(rows), path_prefix: normalized, reason, created_at: new Date().toISOString() });
142
+ csvStore.writeRows(pathCsvPath, pathHeaders, rows);
143
+ },
144
+
145
+ async removePath(pathPrefix) {
146
+ const normalized = String(pathPrefix || '').trim();
147
+ if (await initialize()) {
148
+ try {
149
+ return db('path_exemptions').where('path_prefix', normalized).del();
150
+ } catch (err) {
151
+ dbAvailable = false;
152
+ }
153
+ }
154
+
155
+ const rows = pathRows();
156
+ const filtered = rows.filter(row => String(row.path_prefix) !== normalized);
157
+ csvStore.writeRows(pathCsvPath, pathHeaders, filtered);
158
+ return rows.length - filtered.length;
159
+ },
160
+
161
+ async listPaths() {
162
+ if (await initialize()) {
163
+ try {
164
+ return db('path_exemptions').select('*').orderBy('created_at', 'desc');
165
+ } catch (err) {
166
+ dbAvailable = false;
167
+ }
168
+ }
169
+
170
+ return pathRows().sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
171
+ },
172
+
173
+ async isPathExempt(pathValue) {
174
+ const normalizedPath = String(pathValue || '').toLowerCase();
175
+ if (await initialize()) {
176
+ try {
177
+ const rows = await db('path_exemptions').select('path_prefix');
178
+ return rows.some(row => normalizedPath.startsWith(String(row.path_prefix || '').toLowerCase()));
179
+ } catch (err) {
180
+ dbAvailable = false;
181
+ }
182
+ }
183
+
184
+ return pathRows().some(row => normalizedPath.startsWith(String(row.path_prefix || '').toLowerCase()));
185
+ },
186
+
187
+ async clear() {
188
+ let deleted = 0;
189
+ if (await initialize()) {
190
+ try {
191
+ deleted += await db('ip_exemptions').del();
192
+ deleted += await db('path_exemptions').del();
193
+ } catch (err) {
194
+ dbAvailable = false;
195
+ }
196
+ }
197
+ if (!dbAvailable || !initialized) {
198
+ csvStore.writeRows(ipCsvPath, ipHeaders, []);
199
+ csvStore.writeRows(pathCsvPath, pathHeaders, []);
200
+ deleted = -1; // Unknown count for CSV
201
+ }
202
+ return deleted;
203
+ }
204
+ };
@@ -0,0 +1,56 @@
1
+ const exemptionStore = require('./exemptionStore');
2
+
3
+ let config = {
4
+ exemptPaths: [],
5
+ exemptIps: [],
6
+ allowedPathKeywords: [],
7
+ exemptKeywords: [],
8
+ useDb: true
9
+ };
10
+
11
+ function normalize(items) {
12
+ return (items || []).map(value => String(value).toLowerCase());
13
+ }
14
+
15
+ module.exports = {
16
+ init(opts = {}) {
17
+ config = {
18
+ exemptPaths: normalize(opts.AIWAF_EXEMPT_PATHS),
19
+ exemptIps: normalize(opts.AIWAF_EXEMPT_IPS),
20
+ allowedPathKeywords: normalize(opts.AIWAF_ALLOWED_PATH_KEYWORDS),
21
+ exemptKeywords: normalize(opts.AIWAF_EXEMPT_KEYWORDS),
22
+ useDb: opts.AIWAF_EXEMPTIONS_DB !== false
23
+ };
24
+ if (config.useDb) {
25
+ exemptionStore.initialize().catch(() => {});
26
+ }
27
+ },
28
+
29
+ async isExemptRequest(ip, path) {
30
+ const ipLower = String(ip || '').toLowerCase();
31
+ const pathLower = String(path || '').toLowerCase();
32
+
33
+ if (config.exemptIps.includes(ipLower)) return true;
34
+ if (config.exemptPaths.some(prefix => pathLower.startsWith(prefix))) return true;
35
+
36
+ if (config.useDb) {
37
+ try {
38
+ if (await exemptionStore.isIpExempt(ipLower)) return true;
39
+ if (await exemptionStore.isPathExempt(pathLower)) return true;
40
+ } catch (err) {
41
+ // Exemption storage failure should fail open.
42
+ }
43
+ }
44
+
45
+ return false;
46
+ },
47
+
48
+ shouldSkipKeyword(keyword, path) {
49
+ const normalizedKeyword = String(keyword || '').toLowerCase();
50
+ const pathLower = String(path || '').toLowerCase();
51
+
52
+ if (config.exemptKeywords.includes(normalizedKeyword)) return true;
53
+ if (config.allowedPathKeywords.some(fragment => pathLower.includes(fragment))) return true;
54
+ return false;
55
+ }
56
+ };
@@ -0,0 +1,49 @@
1
+ const createExpressMiddleware = require('./wafMiddleware');
2
+
3
+ function createExpressLikeResponse(reply) {
4
+ const raw = reply.raw;
5
+ const res = {
6
+ locals: {},
7
+ on: (...args) => raw.on(...args),
8
+ get statusCode() {
9
+ return raw.statusCode;
10
+ },
11
+ set statusCode(code) {
12
+ raw.statusCode = code;
13
+ },
14
+ status(code) {
15
+ reply.code(code);
16
+ return res;
17
+ },
18
+ json(payload) {
19
+ reply.type('application/json').send(payload);
20
+ return res;
21
+ },
22
+ send(payload) {
23
+ reply.send(payload);
24
+ return res;
25
+ }
26
+ };
27
+ return res;
28
+ }
29
+
30
+ function fastifyPlugin(fastify, opts = {}, done) {
31
+ const middleware = createExpressMiddleware(opts);
32
+
33
+ fastify.addHook('onRequest', async (request, reply) => {
34
+ await new Promise(resolve => {
35
+ const res = createExpressLikeResponse(reply);
36
+ middleware(request.raw, res, resolve);
37
+ });
38
+
39
+ if (reply.sent) {
40
+ return reply;
41
+ }
42
+ });
43
+
44
+ done();
45
+ }
46
+
47
+ fastifyPlugin[Symbol.for('skip-override')] = true;
48
+
49
+ module.exports = fastifyPlugin;
@@ -0,0 +1,183 @@
1
+ const STATIC_KW = ['.php', '.xmlrpc', 'wp-', '.env', '.git', '.bak', 'shell'];
2
+ const STATUS_IDX = ['200', '403', '404', '500'];
3
+ const defaultCache = new Map();
4
+ const { getClient } = require('./redisClient');
5
+
6
+ let customCache = null;
7
+ let cleanupInterval = null;
8
+
9
+ // In-memory tracking for burst and 404 calculations
10
+ const ipRequestHistory = new Map(); // IP -> array of timestamps
11
+ const ip404Counts = new Map(); // IP -> count of 404s
12
+
13
+ function init(opts = {}) {
14
+ customCache = opts.cache || null;
15
+
16
+ if (cleanupInterval) return;
17
+
18
+ // Clean up old entries every 5 minutes
19
+ cleanupInterval = setInterval(() => {
20
+ const fiveMinutesAgo = Date.now() - 5 * 60 * 1000;
21
+
22
+ for (const [ip, timestamps] of ipRequestHistory.entries()) {
23
+ const recentTimestamps = timestamps.filter(t => t > fiveMinutesAgo);
24
+ if (recentTimestamps.length > 0) {
25
+ ipRequestHistory.set(ip, recentTimestamps);
26
+ } else {
27
+ ipRequestHistory.delete(ip);
28
+ }
29
+ }
30
+ }, 5 * 60 * 1000);
31
+ if (typeof cleanupInterval.unref === 'function') {
32
+ cleanupInterval.unref();
33
+ }
34
+ }
35
+
36
+ function cleanup() {
37
+ if (cleanupInterval) {
38
+ clearInterval(cleanupInterval);
39
+ cleanupInterval = null;
40
+ }
41
+ ipRequestHistory.clear();
42
+ ip404Counts.clear();
43
+ }
44
+
45
+ function recordRequest(ip, statusCode) {
46
+ const now = Date.now();
47
+
48
+ // Record timestamp for burst calculation
49
+ if (!ipRequestHistory.has(ip)) {
50
+ ipRequestHistory.set(ip, []);
51
+ }
52
+ ipRequestHistory.get(ip).push(now);
53
+
54
+ // Keep only last 100 requests per IP to prevent memory bloat
55
+ const history = ipRequestHistory.get(ip);
56
+ if (history.length > 100) {
57
+ history.splice(0, history.length - 100);
58
+ }
59
+
60
+ // Track 404 counts
61
+ if (statusCode === 404) {
62
+ ip404Counts.set(ip, (ip404Counts.get(ip) || 0) + 1);
63
+ }
64
+ }
65
+
66
+ function calculateBurstCount(ip) {
67
+ if (!ipRequestHistory.has(ip)) return 0;
68
+
69
+ const now = Date.now();
70
+ const tenSecondsAgo = now - 10000; // 10 seconds
71
+ const recentRequests = ipRequestHistory.get(ip).filter(t => t > tenSecondsAgo);
72
+
73
+ return recentRequests.length;
74
+ }
75
+
76
+ function get404Count(ip) {
77
+ return ip404Counts.get(ip) || 0;
78
+ }
79
+
80
+ // Helper to mark request start time for response time calculation
81
+ function markRequestStart(req) {
82
+ req._startTime = Date.now();
83
+ }
84
+
85
+ // Helper to calculate response time from marked start
86
+ function getResponseTime(req) {
87
+ if (req._startTime) {
88
+ return Date.now() - req._startTime;
89
+ }
90
+ return 0;
91
+ }
92
+
93
+ async function extractFeatures(req, res = null) {
94
+ const uri = req.path || req.url;
95
+ const ip = req.ip || req.socket?.remoteAddress || req.connection?.remoteAddress || 'unknown';
96
+
97
+ // Get status code from response if available, otherwise default to 200
98
+ let statusCode = 200;
99
+ if (res && res.statusCode) {
100
+ statusCode = res.statusCode;
101
+ } else if (req.res && req.res.statusCode) {
102
+ statusCode = req.res.statusCode;
103
+ }
104
+
105
+ // Record this request for burst/404 tracking
106
+ recordRequest(ip, statusCode);
107
+
108
+ const redis = getClient();
109
+ const cacheKey = `features:${uri.toLowerCase()}:${ip}`;
110
+
111
+ // Custom cache logic
112
+ if (customCache?.get && customCache?.set) {
113
+ try {
114
+ const cached = await customCache.get(cacheKey);
115
+ if (cached) return cached;
116
+ } catch (err) {
117
+ console.warn('Custom cache read failed:', err.message);
118
+ }
119
+ }
120
+
121
+ // Redis check
122
+ if (redis) {
123
+ try {
124
+ const cached = await redis.get(cacheKey);
125
+ if (cached) return JSON.parse(cached);
126
+ } catch (err) {
127
+ console.warn('⚠️ Redis read failed. Falling back.', err.message);
128
+ }
129
+ }
130
+
131
+ // Compute features
132
+ const pathLen = uri.length;
133
+ const kwHits = STATIC_KW.reduce((count, kw) => count + (uri.toLowerCase().includes(kw) ? 1 : 0), 0);
134
+ const statusIdx = STATUS_IDX.indexOf(String(statusCode));
135
+
136
+ // Response time - try multiple sources
137
+ let responseTime = 0;
138
+ if (req.headers && req.headers['x-response-time']) {
139
+ responseTime = parseFloat(req.headers['x-response-time']);
140
+ } else if (req.responseTime) {
141
+ responseTime = req.responseTime;
142
+ } else if (req._startTime) {
143
+ responseTime = Date.now() - req._startTime;
144
+ }
145
+
146
+ // Calculate real burst and 404 counts
147
+ const burst = calculateBurstCount(ip);
148
+ const total404 = get404Count(ip);
149
+
150
+ const features = [pathLen, kwHits, statusIdx, responseTime, burst, total404];
151
+
152
+ // Write back to cache with shorter TTL for dynamic features
153
+ const ttl = 30; // 30 seconds TTL
154
+
155
+ if (customCache?.set) {
156
+ try {
157
+ await customCache.set(cacheKey, features, ttl);
158
+ } catch (err) {
159
+ console.warn('Custom cache write failed:', err.message);
160
+ }
161
+ } else if (redis) {
162
+ try {
163
+ await redis.set(cacheKey, JSON.stringify(features), { EX: ttl });
164
+ } catch (err) {
165
+ console.warn('⚠️ Redis write failed. Ignoring.', err.message);
166
+ }
167
+ }
168
+
169
+ return features;
170
+ }
171
+
172
+ module.exports = {
173
+ extractFeatures,
174
+ init,
175
+ recordRequest,
176
+ calculateBurstCount,
177
+ get404Count,
178
+ markRequestStart,
179
+ getResponseTime,
180
+ cleanup,
181
+ STATIC_KW,
182
+ STATUS_IDX
183
+ };
@@ -0,0 +1,159 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const geoStore = require('./geoStore');
4
+ const { evaluateGeoPolicy } = require('./geoPolicy');
5
+
6
+ let config = {
7
+ enabled: false,
8
+ blocked: [],
9
+ allowed: [],
10
+ resolver: null,
11
+ mmdbPath: '',
12
+ mmdbReader: null,
13
+ cacheSeconds: 3600,
14
+ cachePrefix: 'aiwaf:geo:',
15
+ cache: new Map()
16
+ };
17
+
18
+ function normalizeCountry(value) {
19
+ return String(value || '').trim().toUpperCase();
20
+ }
21
+
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
+ function getCachedCountry(ip) {
30
+ if (!ip || config.cacheSeconds <= 0) return '';
31
+ const key = `${config.cachePrefix}${ip}`;
32
+ const entry = config.cache.get(key);
33
+ if (!entry) return '';
34
+ if (Date.now() > entry.expiresAt) {
35
+ config.cache.delete(key);
36
+ return '';
37
+ }
38
+ return entry.country || '';
39
+ }
40
+
41
+ function setCachedCountry(ip, country) {
42
+ if (!ip || config.cacheSeconds <= 0) return;
43
+ const key = `${config.cachePrefix}${ip}`;
44
+ config.cache.set(key, {
45
+ country,
46
+ expiresAt: Date.now() + config.cacheSeconds * 1000
47
+ });
48
+ }
49
+
50
+ async function resolveCountry(req) {
51
+ const ip = getRequestIp(req);
52
+ const cached = getCachedCountry(ip);
53
+ if (cached) {
54
+ return { country: cached, ip };
55
+ }
56
+
57
+ if (typeof config.resolver === 'function') {
58
+ try {
59
+ const result = normalizeCountry(await config.resolver(req));
60
+ if (result) setCachedCountry(ip, result);
61
+ return { country: result, ip };
62
+ } catch (err) {
63
+ return { country: '', ip };
64
+ }
65
+ }
66
+
67
+ if (config.mmdbReader) {
68
+ try {
69
+ if (ip) {
70
+ const result = config.mmdbReader.get(ip);
71
+ const iso = result?.country?.iso_code || result?.registered_country?.iso_code;
72
+ if (iso) {
73
+ const normalized = normalizeCountry(iso);
74
+ if (normalized) setCachedCountry(ip, normalized);
75
+ return { country: normalized, ip };
76
+ }
77
+ }
78
+ } catch (err) {
79
+ // Fall through to header fallback.
80
+ }
81
+ }
82
+
83
+ // Fallback when no MMDB reader is available.
84
+ const fallback = normalizeCountry(req.headers?.['x-country-code']);
85
+ if (fallback) setCachedCountry(ip, fallback);
86
+ return { country: fallback, ip };
87
+ }
88
+
89
+ function tryLoadMmdbReader(mmdbPath) {
90
+ if (!mmdbPath || !fs.existsSync(mmdbPath)) return null;
91
+ try {
92
+ // Optional dependency by design.
93
+ // eslint-disable-next-line global-require, import/no-extraneous-dependencies
94
+ const maxmind = require('maxmind');
95
+ return maxmind.openSync(mmdbPath);
96
+ } catch (err) {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ module.exports = {
102
+ init(opts = {}) {
103
+ const resolvedPath = opts.AIWAF_GEO_MMDB_PATH
104
+ ? path.resolve(opts.AIWAF_GEO_MMDB_PATH)
105
+ : path.resolve(__dirname, '..', 'geolock', 'ipinfo_lite.mmdb');
106
+ config = {
107
+ enabled: !!opts.AIWAF_GEO_BLOCK_ENABLED,
108
+ blocked: (opts.AIWAF_GEO_BLOCK_COUNTRIES || []).map(normalizeCountry),
109
+ allowed: (opts.AIWAF_GEO_ALLOW_COUNTRIES || []).map(normalizeCountry),
110
+ resolver: opts.geoResolver || null,
111
+ mmdbPath: resolvedPath,
112
+ mmdbReader: tryLoadMmdbReader(resolvedPath),
113
+ cacheSeconds: Number.isFinite(Number(opts.AIWAF_GEO_CACHE_SECONDS))
114
+ ? Number(opts.AIWAF_GEO_CACHE_SECONDS)
115
+ : 3600,
116
+ cachePrefix: opts.AIWAF_GEO_CACHE_PREFIX || 'aiwaf:geo:',
117
+ cache: new Map()
118
+ };
119
+ geoStore.initialize().catch(() => {});
120
+ },
121
+
122
+ async check(req) {
123
+ if (!config.enabled) {
124
+ return { blocked: false, country: '' };
125
+ }
126
+
127
+ // If both allow and block lists are empty, then geo-blocking is effectively disabled
128
+ // for static rules. Return no blocking and no country.
129
+ if (config.allowed.length === 0 && config.blocked.length === 0) {
130
+ return { blocked: false, country: '' };
131
+ }
132
+
133
+ const result = await resolveCountry(req);
134
+ const country = result.country;
135
+ if (!country) {
136
+ return { blocked: false, country: '' };
137
+ }
138
+
139
+ let dynamicBlocked = [];
140
+ try {
141
+ dynamicBlocked = await geoStore.isBlockedCountry(country) ? [country] : [];
142
+ } catch (err) {
143
+ dynamicBlocked = [];
144
+ }
145
+
146
+ const decision = evaluateGeoPolicy({
147
+ country,
148
+ allowCountries: config.allowed,
149
+ blockCountries: config.blocked,
150
+ dynamicBlocked
151
+ });
152
+
153
+ if (decision.shouldBlock) {
154
+ return { blocked: true, country: decision.country, reason: decision.reason };
155
+ }
156
+
157
+ return { blocked: false, country: decision.country };
158
+ }
159
+ };
@@ -0,0 +1,42 @@
1
+ function normalizeCountryList(value) {
2
+ if (!value) return new Set();
3
+ const values = typeof value === 'string' ? [value] : Array.from(value);
4
+ return new Set(values
5
+ .map(item => String(item || '').trim().toUpperCase())
6
+ .filter(Boolean));
7
+ }
8
+
9
+ function evaluateGeoPolicy({
10
+ country,
11
+ allowCountries = [],
12
+ blockCountries = [],
13
+ dynamicBlocked = []
14
+ } = {}) {
15
+ const normalizedCountry = String(country || '').trim().toUpperCase();
16
+ if (!normalizedCountry) {
17
+ return { shouldBlock: false, country: '', reason: '' };
18
+ }
19
+
20
+ const allow = normalizeCountryList(allowCountries);
21
+ const block = normalizeCountryList(blockCountries);
22
+ const dynamic = normalizeCountryList(dynamicBlocked);
23
+ let shouldBlock;
24
+ if (allow.size > 0) {
25
+ shouldBlock = !allow.has(normalizedCountry);
26
+ } else if (block.size > 0 || dynamic.size > 0) {
27
+ shouldBlock = block.has(normalizedCountry) || dynamic.has(normalizedCountry);
28
+ } else {
29
+ shouldBlock = false;
30
+ }
31
+
32
+ return {
33
+ shouldBlock,
34
+ country: normalizedCountry,
35
+ reason: shouldBlock ? `Geo blocked: ${normalizedCountry}` : ''
36
+ };
37
+ }
38
+
39
+ module.exports = {
40
+ normalizeCountryList,
41
+ evaluateGeoPolicy
42
+ };