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,184 @@
1
+ const MIDDLEWARE_NAME_MAP = {
2
+ ipandkeywordblockmiddleware: 'ip_keyword_block',
3
+ ratelimitmiddleware: 'rate_limit',
4
+ ratelimiting: 'rate_limit',
5
+ rate_limiting: 'rate_limit',
6
+ honeypottimingmiddleware: 'honeypot',
7
+ headervalidationmiddleware: 'header_validation',
8
+ geoblockmiddleware: 'geo_block',
9
+ aianomalymiddleware: 'ai_anomaly',
10
+ uuidtampermiddleware: 'uuid_tamper',
11
+ uuid: 'uuid_tamper',
12
+ aiwafloggingmiddleware: 'logging',
13
+ logging_middleware: 'logging'
14
+ };
15
+
16
+ const ALL_MIDDLEWARES = [
17
+ 'geo_block',
18
+ 'ip_keyword_block',
19
+ 'rate_limit',
20
+ 'ai_anomaly',
21
+ 'honeypot',
22
+ 'uuid_tamper',
23
+ 'header_validation',
24
+ 'logging'
25
+ ];
26
+
27
+ function normalizePath(value, trailingSlash = null) {
28
+ let cleaned = String(value || '').trim().replace(/\/{2,}/g, '/');
29
+ if (!cleaned) cleaned = '/';
30
+ if (!cleaned.startsWith('/')) cleaned = `/${cleaned}`;
31
+ if (trailingSlash === true && !cleaned.endsWith('/')) cleaned += '/';
32
+ if (trailingSlash === false && cleaned !== '/') cleaned = cleaned.replace(/\/+$/, '');
33
+ return cleaned.toLowerCase();
34
+ }
35
+
36
+ function normalizePaths(items = []) {
37
+ return (items || []).map(item => normalizePath(item, false));
38
+ }
39
+
40
+ function wildcardMatch(pathValue, pattern) {
41
+ const escaped = String(pattern)
42
+ .replace(/[.+?^${}()|[\]\\]/g, '\\$&')
43
+ .replace(/\*/g, '.*');
44
+ return new RegExp(`^${escaped}$`).test(pathValue);
45
+ }
46
+
47
+ function isPathExempt(pathValue, exemptPaths = [], { allowWildcards = true, allowPrefix = true } = {}) {
48
+ const normalizedPath = normalizePath(pathValue, false);
49
+ return (exemptPaths || []).some(entry => {
50
+ const normalizedEntry = normalizePath(entry, false);
51
+ if (normalizedPath === normalizedEntry) return true;
52
+ if (allowWildcards && normalizedEntry.includes('*') && wildcardMatch(normalizedPath, normalizedEntry)) return true;
53
+ if (allowPrefix && normalizedPath.startsWith(normalizedEntry.endsWith('/') ? normalizedEntry : `${normalizedEntry}/`)) return true;
54
+ return false;
55
+ });
56
+ }
57
+
58
+ function normalizeMiddlewareName(name) {
59
+ if (!name) return '';
60
+ let normalized = String(name).trim();
61
+ if (normalized.includes('.')) {
62
+ normalized = normalized.split('.').pop();
63
+ }
64
+ normalized = normalized.toLowerCase();
65
+ return MIDDLEWARE_NAME_MAP[normalized] || normalized;
66
+ }
67
+
68
+ function getPathRule(path, rules = []) {
69
+ if (!path || !Array.isArray(rules)) return null;
70
+ const normalizedPath = normalizePath(path, false);
71
+ let best = null;
72
+
73
+ rules.forEach((rule, position) => {
74
+ if (!rule || typeof rule !== 'object' || !rule.PREFIX) return;
75
+ const prefix = normalizePath(rule.PREFIX, true);
76
+ if (normalizedPath === prefix.replace(/\/+$/, '') || normalizedPath.startsWith(prefix)) {
77
+ if (!best || prefix.length > best.prefix.length) {
78
+ best = { prefix, rule, position };
79
+ }
80
+ }
81
+ });
82
+
83
+ return best ? best.rule : null;
84
+ }
85
+
86
+ function getPathRuleOverrides(path, rules, sectionKey) {
87
+ const rule = getPathRule(path, rules);
88
+ if (!rule || !sectionKey) return {};
89
+ const upperKey = String(sectionKey).toUpperCase();
90
+ const lowerKey = String(sectionKey).toLowerCase();
91
+ const value = rule[upperKey] || rule[lowerKey];
92
+ return value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};
93
+ }
94
+
95
+ function isMiddlewareDisabledForPath(path, rules, middlewareName) {
96
+ const rule = getPathRule(path, rules);
97
+ if (!rule) return false;
98
+ const disabled = rule.DISABLE || rule.disable || [];
99
+ if (!Array.isArray(disabled)) return false;
100
+ const target = normalizeMiddlewareName(middlewareName);
101
+ return disabled.some(entry => normalizeMiddlewareName(entry) === target);
102
+ }
103
+
104
+ function createRoutePlan(path, rules = [], context = {}) {
105
+ const required = new Set((context.requiredMiddlewares || []).map(normalizeMiddlewareName));
106
+ const exempt = new Set((context.exemptMiddlewares || []).map(normalizeMiddlewareName));
107
+ const fullyExempt = !!context.fullyExempt;
108
+ const enabled = new Set();
109
+
110
+ ALL_MIDDLEWARES.forEach(name => {
111
+ if (required.has(name)) {
112
+ enabled.add(name);
113
+ } else if (isMiddlewareDisabledForPath(path, rules, name) || fullyExempt || exempt.has(name)) {
114
+ return;
115
+ } else {
116
+ enabled.add(name);
117
+ }
118
+ });
119
+
120
+ return {
121
+ shouldApply(name) {
122
+ return enabled.has(normalizeMiddlewareName(name));
123
+ },
124
+ getOverrides(sectionKey) {
125
+ return getPathRuleOverrides(path, rules, sectionKey);
126
+ },
127
+ enabledMiddlewares: enabled
128
+ };
129
+ }
130
+
131
+ function markRequest(req, options = {}) {
132
+ req.aiwafRoute = {
133
+ ...(req.aiwafRoute || {}),
134
+ ...options,
135
+ exemptMiddlewares: [
136
+ ...((req.aiwafRoute && req.aiwafRoute.exemptMiddlewares) || []),
137
+ ...((options && options.exemptMiddlewares) || [])
138
+ ],
139
+ requiredMiddlewares: [
140
+ ...((req.aiwafRoute && req.aiwafRoute.requiredMiddlewares) || []),
141
+ ...((options && options.requiredMiddlewares) || [])
142
+ ]
143
+ };
144
+ }
145
+
146
+ function exempt(req, _res, next) {
147
+ markRequest(req, { fullyExempt: true });
148
+ next();
149
+ }
150
+
151
+ function exemptFrom(...middlewareNames) {
152
+ return (req, _res, next) => {
153
+ markRequest(req, { exemptMiddlewares: middlewareNames });
154
+ next();
155
+ };
156
+ }
157
+
158
+ function only(...middlewareNames) {
159
+ const selected = new Set(middlewareNames.map(normalizeMiddlewareName));
160
+ return exemptFrom(...ALL_MIDDLEWARES.filter(name => !selected.has(name)));
161
+ }
162
+
163
+ function requireProtection(...middlewareNames) {
164
+ return (req, _res, next) => {
165
+ markRequest(req, { requiredMiddlewares: middlewareNames });
166
+ next();
167
+ };
168
+ }
169
+
170
+ module.exports = {
171
+ ALL_MIDDLEWARES,
172
+ normalizePath,
173
+ normalizePaths,
174
+ isPathExempt,
175
+ normalizeMiddlewareName,
176
+ getPathRule,
177
+ getPathRuleOverrides,
178
+ isMiddlewareDisabledForPath,
179
+ createRoutePlan,
180
+ exempt,
181
+ exemptFrom,
182
+ only,
183
+ requireProtection
184
+ };
@@ -0,0 +1,153 @@
1
+ const NodeCache = require('node-cache');
2
+ const blacklistManager = require('./blacklistManager');
3
+
4
+ let cacheBackend;
5
+ let opts;
6
+ let cleanupInterval;
7
+
8
+ const defaultMemoryCache = new NodeCache({ stdTTL: 60, checkperiod: 120 }); // Auto cleanup every 2 minutes
9
+
10
+ const fallbackCache = {
11
+ get: (key) => Promise.resolve(defaultMemoryCache.get(key)),
12
+ set: (key, value, ttl) => Promise.resolve(defaultMemoryCache.set(key, value, ttl)),
13
+ lPush: async (key, value) => {
14
+ const arr = defaultMemoryCache.get(key) || [];
15
+ arr.unshift(value);
16
+ defaultMemoryCache.set(key, arr, opts.WINDOW_SEC * 2); // Keep for 2x window duration
17
+ },
18
+ expire: (key, ttl) => Promise.resolve(defaultMemoryCache.ttl(key, ttl)),
19
+ lLen: async (key) => {
20
+ const arr = defaultMemoryCache.get(key) || [];
21
+ return arr.length;
22
+ },
23
+ lRange: async (key, start, end) => {
24
+ const arr = defaultMemoryCache.get(key) || [];
25
+ const normalizedEnd = end < 0 ? arr.length - 1 : end;
26
+ return arr.slice(start, normalizedEnd + 1);
27
+ }
28
+ };
29
+
30
+ // Additional cleanup for old timestamps within arrays
31
+ function cleanupOldTimestamps() {
32
+ const now = Date.now();
33
+ const cutoff = now - (opts.WINDOW_SEC * 2 * 1000); // Keep 2x window worth
34
+
35
+ const keys = defaultMemoryCache.keys();
36
+ for (const key of keys) {
37
+ if (key.startsWith('ratelimit:')) {
38
+ const arr = defaultMemoryCache.get(key);
39
+ if (Array.isArray(arr)) {
40
+ const filtered = arr.filter(timestamp => timestamp > cutoff);
41
+ if (filtered.length !== arr.length) {
42
+ if (filtered.length > 0) {
43
+ defaultMemoryCache.set(key, filtered, opts.WINDOW_SEC * 2);
44
+ } else {
45
+ defaultMemoryCache.del(key);
46
+ }
47
+ }
48
+ }
49
+ }
50
+ }
51
+ }
52
+
53
+ function getEffectiveOpts(overrides = {}) {
54
+ const windowSec = Number(
55
+ overrides.WINDOW_SEC
56
+ ?? overrides.WINDOW
57
+ ?? overrides.window_seconds
58
+ ?? overrides.windowSeconds
59
+ ?? opts.WINDOW_SEC
60
+ );
61
+ const maxReq = Number(
62
+ overrides.MAX_REQ
63
+ ?? overrides.MAX
64
+ ?? overrides.max_requests
65
+ ?? overrides.maxRequests
66
+ ?? opts.MAX_REQ
67
+ );
68
+ const floodReq = Number(
69
+ overrides.FLOOD_REQ
70
+ ?? overrides.FLOOD
71
+ ?? overrides.flood_threshold
72
+ ?? overrides.floodThreshold
73
+ ?? opts.FLOOD_REQ
74
+ );
75
+
76
+ return {
77
+ WINDOW_SEC: Number.isFinite(windowSec) ? windowSec : opts.WINDOW_SEC,
78
+ MAX_REQ: Number.isFinite(maxReq) ? maxReq : opts.MAX_REQ,
79
+ FLOOD_REQ: Number.isFinite(floodReq) ? floodReq : opts.FLOOD_REQ
80
+ };
81
+ }
82
+
83
+ module.exports = {
84
+ async init(o) {
85
+ opts = {
86
+ WINDOW_SEC: o?.WINDOW_SEC ?? 60,
87
+ MAX_REQ: o?.MAX_REQ ?? 100,
88
+ FLOOD_REQ: o?.FLOOD_REQ ?? 200,
89
+ cache: o?.cache
90
+ };
91
+ const requiredOps = ['lPush', 'expire', 'lLen', 'lRange'];
92
+ const externalCache = opts.cache;
93
+ const hasRequiredOps = externalCache && requiredOps.every(op => typeof externalCache[op] === 'function');
94
+ cacheBackend = hasRequiredOps ? externalCache : fallbackCache;
95
+
96
+ // Start cleanup interval for fallback cache
97
+ if (cacheBackend === fallbackCache && !cleanupInterval) {
98
+ cleanupInterval = setInterval(cleanupOldTimestamps, 60000); // Cleanup every minute
99
+ if (typeof cleanupInterval.unref === 'function') {
100
+ cleanupInterval.unref();
101
+ }
102
+ console.log('Rate limiter memory cleanup enabled');
103
+ }
104
+ },
105
+
106
+ async record(ip, overrides = {}) {
107
+ const now = Date.now().toString();
108
+ const effective = getEffectiveOpts(overrides);
109
+
110
+ try {
111
+ const key = `ratelimit:${ip}`;
112
+ await cacheBackend.lPush(key, now);
113
+ await cacheBackend.expire(key, effective.WINDOW_SEC * 2); // Extended TTL
114
+ const count = await cacheBackend.lLen(key);
115
+ if (count > effective.FLOOD_REQ) {
116
+ await blacklistManager.block(ip, 'flood');
117
+ }
118
+ } catch (err) {
119
+ console.warn('⚠️ Cache error in record().', err.message);
120
+ }
121
+ },
122
+
123
+ async isBlocked(ip, overrides = {}) {
124
+ const effective = getEffectiveOpts(overrides);
125
+ try {
126
+ if (await blacklistManager.isBlocked(ip)) return true;
127
+ } catch (err) {
128
+ console.warn('⚠️ Blacklist check error:', err.message);
129
+ }
130
+
131
+ try {
132
+ const key = `ratelimit:${ip}`;
133
+ const now = Date.now();
134
+ const timestamps = (await cacheBackend.lRange(key, 0, -1)).map(Number);
135
+ const within = timestamps.filter(t => now - t < effective.WINDOW_SEC * 1000);
136
+ return within.length > effective.MAX_REQ;
137
+ } catch (err) {
138
+ console.warn('⚠️ Cache error in isBlocked().', err.message);
139
+ return false; // Fail open
140
+ }
141
+ },
142
+
143
+ // Cleanup method for graceful shutdown
144
+ cleanup() {
145
+ if (cleanupInterval) {
146
+ clearInterval(cleanupInterval);
147
+ cleanupInterval = null;
148
+ }
149
+ if (defaultMemoryCache && typeof defaultMemoryCache.close === 'function') {
150
+ defaultMemoryCache.close();
151
+ }
152
+ }
153
+ };
@@ -0,0 +1,35 @@
1
+ // lib/redisManager.js
2
+ const { createClient } = require('redis');
3
+
4
+ let client = null;
5
+ let isReady = false;
6
+
7
+ function getRedisUrl() {
8
+ return process.env.REDIS_URL || process.env.AIWAF_REDIS_URL;
9
+ }
10
+
11
+ async function connect() {
12
+ const redisUrl = getRedisUrl();
13
+ if (!redisUrl) {
14
+ console.warn('⚠️ No REDIS_URL set. Redis disabled.');
15
+ return;
16
+ }
17
+
18
+ try {
19
+ client = createClient({ url: redisUrl });
20
+ client.on('error', err => console.warn('⚠️ Redis error:', err));
21
+ await client.connect();
22
+ isReady = true;
23
+ console.log('Redis connected.');
24
+ } catch (err) {
25
+ console.warn('Redis connection failed. Falling back.');
26
+ client = null;
27
+ isReady = false;
28
+ }
29
+ }
30
+
31
+ function getClient() {
32
+ return isReady && client?.isOpen ? client : null;
33
+ }
34
+
35
+ module.exports = { connect, getClient, isReady: () => isReady };
@@ -0,0 +1,167 @@
1
+ const path = require('path');
2
+ const db = require('../utils/db');
3
+ const csvStore = require('./csvStore');
4
+
5
+ const headers = [
6
+ 'id',
7
+ 'created_at',
8
+ 'ip_address',
9
+ 'method',
10
+ 'path',
11
+ 'status',
12
+ 'response_time_ms',
13
+ 'blocked',
14
+ 'reason',
15
+ 'country',
16
+ 'user_agent'
17
+ ];
18
+ const csvPath = process.env.AIWAF_REQUEST_LOGS_CSV_PATH || path.join('logs', 'storage', 'request_logs.csv');
19
+
20
+ let initialized = false;
21
+ let dbAvailable = true;
22
+
23
+ async function initialize() {
24
+ if (initialized) return dbAvailable;
25
+
26
+ try {
27
+ const hasLogs = await db.schema.hasTable('request_logs');
28
+ if (!hasLogs) {
29
+ await db.schema.createTable('request_logs', table => {
30
+ table.increments('id').primary();
31
+ table.timestamp('created_at').defaultTo(db.fn.now());
32
+ table.string('ip_address');
33
+ table.string('method');
34
+ table.string('path');
35
+ table.integer('status');
36
+ table.integer('response_time_ms');
37
+ table.boolean('blocked').defaultTo(false);
38
+ table.string('reason');
39
+ table.string('country', 2);
40
+ table.string('user_agent');
41
+ });
42
+ }
43
+ dbAvailable = true;
44
+ } catch (err) {
45
+ dbAvailable = false;
46
+ }
47
+
48
+ if (!dbAvailable) {
49
+ csvStore.writeRows(csvPath, headers, csvStore.readRows(csvPath, headers));
50
+ }
51
+
52
+ initialized = true;
53
+ return dbAvailable;
54
+ }
55
+
56
+ function rows() {
57
+ return csvStore.readRows(csvPath, headers);
58
+ }
59
+
60
+ module.exports = {
61
+ async initialize() {
62
+ await initialize();
63
+ },
64
+
65
+ async insert(event) {
66
+ const payload = {
67
+ created_at: event.timestamp || new Date().toISOString(),
68
+ ip_address: event.ip || '',
69
+ method: event.method || '',
70
+ path: event.path || '',
71
+ status: Number(event.status || 0),
72
+ response_time_ms: Number(event.responseTime || 0),
73
+ blocked: event.blocked ? 1 : 0,
74
+ reason: event.reason || '',
75
+ country: event.country || '',
76
+ user_agent: event.userAgent || ''
77
+ };
78
+
79
+ if (await initialize()) {
80
+ try {
81
+ await db('request_logs').insert({
82
+ created_at: payload.created_at,
83
+ ip_address: payload.ip_address,
84
+ method: payload.method,
85
+ path: payload.path,
86
+ status: payload.status,
87
+ response_time_ms: payload.response_time_ms,
88
+ blocked: !!payload.blocked,
89
+ reason: payload.reason,
90
+ country: payload.country,
91
+ user_agent: payload.user_agent
92
+ });
93
+ return;
94
+ } catch (err) {
95
+ dbAvailable = false;
96
+ }
97
+ }
98
+
99
+ const current = rows();
100
+ csvStore.appendRow(csvPath, headers, { id: csvStore.nextId(current), ...payload });
101
+ },
102
+
103
+ async recent(limit = 5000) {
104
+ const normalizedLimit = Number(limit) > 0 ? Number(limit) : 5000;
105
+
106
+ if (await initialize()) {
107
+ try {
108
+ return db('request_logs').select('*').orderBy('created_at', 'desc').limit(normalizedLimit);
109
+ } catch (err) {
110
+ dbAvailable = false;
111
+ }
112
+ }
113
+
114
+ return rows()
115
+ .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
116
+ .slice(0, normalizedLimit);
117
+ },
118
+
119
+ async geoSummary(limit = 25) {
120
+ const normalizedLimit = Number(limit) > 0 ? Number(limit) : 25;
121
+
122
+ if (await initialize()) {
123
+ try {
124
+ return db('request_logs')
125
+ .select('country')
126
+ .count({ requests: '*' })
127
+ .sum({ blocked_count: db.raw('CASE WHEN blocked THEN 1 ELSE 0 END') })
128
+ .whereNotNull('country')
129
+ .groupBy('country')
130
+ .orderBy('requests', 'desc')
131
+ .limit(normalizedLimit);
132
+ } catch (err) {
133
+ dbAvailable = false;
134
+ }
135
+ }
136
+
137
+ const map = new Map();
138
+ for (const row of rows()) {
139
+ const country = String(row.country || '').trim();
140
+ if (!country) continue;
141
+ const current = map.get(country) || { country, requests: 0, blocked_count: 0 };
142
+ current.requests += 1;
143
+ if (String(row.blocked) === '1' || String(row.blocked).toLowerCase() === 'true') {
144
+ current.blocked_count += 1;
145
+ }
146
+ map.set(country, current);
147
+ }
148
+
149
+ return Array.from(map.values())
150
+ .sort((a, b) => b.requests - a.requests)
151
+ .slice(0, normalizedLimit);
152
+ },
153
+
154
+ async clear() {
155
+ if (await initialize()) {
156
+ try {
157
+ return await db('request_logs').del();
158
+ } catch (err) {
159
+ dbAvailable = false;
160
+ }
161
+ }
162
+
163
+ const current = rows();
164
+ csvStore.writeRows(csvPath, headers, []);
165
+ return current.length;
166
+ }
167
+ };
@@ -0,0 +1,166 @@
1
+ const crypto = require('crypto');
2
+ const net = require('net');
3
+
4
+ const STATIC_EXTENSIONS = new Set([
5
+ '.css', '.js', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg',
6
+ '.woff', '.woff2', '.ttf', '.eot', '.otf', '.map', '.json',
7
+ '.xml', '.txt', '.pdf', '.zip', '.tar', '.gz', '.webp', '.avif'
8
+ ]);
9
+
10
+ function getRequestIp(req = {}) {
11
+ const forwarded = req.headers?.['x-forwarded-for'];
12
+ const raw = forwarded
13
+ ? String(forwarded).split(',')[0].trim()
14
+ : (req.ip || req.connection?.remoteAddress || req.socket?.remoteAddress || '');
15
+ return String(raw).replace(/^::ffff:/, '');
16
+ }
17
+
18
+ function isPrivateIp(ip) {
19
+ const normalized = String(ip || '').trim().replace(/^::ffff:/, '');
20
+ if (!normalized) return false;
21
+
22
+ if (normalized === '::1' || normalized.toLowerCase().startsWith('fc') || normalized.toLowerCase().startsWith('fd')) {
23
+ return true;
24
+ }
25
+
26
+ if (net.isIP(normalized) !== 4) return false;
27
+ const parts = normalized.split('.').map(part => Number(part));
28
+ if (parts.length !== 4 || parts.some(part => Number.isNaN(part))) return false;
29
+
30
+ return parts[0] === 10
31
+ || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31)
32
+ || (parts[0] === 192 && parts[1] === 168)
33
+ || parts[0] === 127;
34
+ }
35
+
36
+ function isStaticFile(requestPath) {
37
+ const pathLower = String(requestPath || '').toLowerCase();
38
+ return [...STATIC_EXTENSIONS].some(ext => pathLower.endsWith(ext));
39
+ }
40
+
41
+ function sanitizeHeaderValue(value, maxLength = 500) {
42
+ if (!value) return '';
43
+ let sanitized = String(value);
44
+ if (sanitized.length > maxLength) sanitized = `${sanitized.slice(0, maxLength)}...`;
45
+ return sanitized
46
+ .split('')
47
+ .filter(char => {
48
+ const code = char.charCodeAt(0);
49
+ return code >= 32 || char === '\t' || char === '\n' || char === '\r';
50
+ })
51
+ .join('');
52
+ }
53
+
54
+ function parseUserAgent(userAgent) {
55
+ if (!userAgent) return { browser: 'unknown', version: 'unknown', os: 'unknown' };
56
+
57
+ const uaLower = String(userAgent).toLowerCase();
58
+ const result = { browser: 'unknown', version: 'unknown', os: 'unknown' };
59
+
60
+ if (uaLower.includes('chrome') && !uaLower.includes('edg')) result.browser = 'chrome';
61
+ else if (uaLower.includes('firefox')) result.browser = 'firefox';
62
+ else if (uaLower.includes('safari') && !uaLower.includes('chrome')) result.browser = 'safari';
63
+ else if (uaLower.includes('edg')) result.browser = 'edge';
64
+ else if (uaLower.includes('opera') || uaLower.includes('opr')) result.browser = 'opera';
65
+
66
+ if (uaLower.includes('windows')) result.os = 'windows';
67
+ else if (uaLower.includes('mac') || uaLower.includes('darwin')) result.os = 'macos';
68
+ else if (uaLower.includes('linux')) result.os = 'linux';
69
+ else if (uaLower.includes('android')) result.os = 'android';
70
+ else if (uaLower.includes('iphone') || uaLower.includes('ipad')) result.os = 'ios';
71
+
72
+ return result;
73
+ }
74
+
75
+ function getRequestFingerprint(req = {}) {
76
+ const headers = req.headers || {};
77
+ const keyHeaders = ['user-agent', 'accept', 'accept-language', 'accept-encoding', 'connection'];
78
+ const parts = keyHeaders.map(header => `${header}:${headers[header] || ''}`);
79
+ parts.push(`method:${req.method || ''}`);
80
+ return crypto.createHash('md5').update(parts.join('|')).digest('hex').slice(0, 16);
81
+ }
82
+
83
+ function ipInAllowlist(ip, allowlist = []) {
84
+ const normalizedIp = String(ip || '').trim();
85
+ if (!normalizedIp) return false;
86
+ return (allowlist || []).some(entry => {
87
+ const normalizedEntry = String(entry || '').trim();
88
+ if (!normalizedEntry) return false;
89
+ if (normalizedEntry === normalizedIp) return true;
90
+ if (normalizedEntry.endsWith('*')) return normalizedIp.startsWith(normalizedEntry.slice(0, -1));
91
+ return false;
92
+ });
93
+ }
94
+
95
+ function extractExtendedRequestInfo(req = {}, options = {}) {
96
+ if (!options.enabled) return null;
97
+ const headers = req.headers || {};
98
+ const maxHeaders = Number(options.maxHeaders || 50);
99
+ const maxValueLength = Number(options.maxValueLength || 512);
100
+ const redact = new Set((options.redactHeaders || ['authorization', 'cookie', 'set-cookie']).map(item => String(item).toLowerCase()));
101
+ const capturedHeaders = {};
102
+
103
+ Object.keys(headers).slice(0, maxHeaders).forEach(name => {
104
+ capturedHeaders[name] = redact.has(name.toLowerCase())
105
+ ? '[redacted]'
106
+ : sanitizeHeaderValue(headers[name], maxValueLength);
107
+ });
108
+
109
+ return {
110
+ method: req.method || '',
111
+ path: req.originalUrl || req.url || '',
112
+ ip: getRequestIp(req),
113
+ headers: capturedHeaders,
114
+ fingerprint: getRequestFingerprint(req)
115
+ };
116
+ }
117
+
118
+ class RateLimiter {
119
+ constructor() {
120
+ this.requests = new Map();
121
+ this.cleanupIntervalMs = 300000;
122
+ this.lastCleanup = 0;
123
+ }
124
+
125
+ isRateLimited(ip, requestPath, maxRequests = 100, windowSeconds = 300) {
126
+ const now = Date.now();
127
+ if (now - this.lastCleanup > this.cleanupIntervalMs) {
128
+ this.cleanupOldEntries(now, windowSeconds * 2000);
129
+ this.lastCleanup = now;
130
+ }
131
+
132
+ const key = String(ip || '');
133
+ const cutoff = now - Number(windowSeconds) * 1000;
134
+ const entries = (this.requests.get(key) || []).filter(entry => entry.timestamp > cutoff);
135
+ if (entries.length >= Number(maxRequests)) {
136
+ this.requests.set(key, entries);
137
+ return true;
138
+ }
139
+
140
+ entries.push({ timestamp: now, path: requestPath });
141
+ this.requests.set(key, entries);
142
+ return false;
143
+ }
144
+
145
+ cleanupOldEntries(now = Date.now(), maxAgeMs = 600000) {
146
+ const cutoff = now - maxAgeMs;
147
+ for (const [ip, entries] of this.requests.entries()) {
148
+ const kept = entries.filter(entry => entry.timestamp > cutoff);
149
+ if (kept.length) this.requests.set(ip, kept);
150
+ else this.requests.delete(ip);
151
+ }
152
+ }
153
+ }
154
+
155
+ module.exports = {
156
+ STATIC_EXTENSIONS,
157
+ getRequestIp,
158
+ isPrivateIp,
159
+ isStaticFile,
160
+ sanitizeHeaderValue,
161
+ parseUserAgent,
162
+ getRequestFingerprint,
163
+ ipInAllowlist,
164
+ extractExtendedRequestInfo,
165
+ RateLimiter
166
+ };