aiwaf 1.1.5 → 1.2.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.
@@ -3,7 +3,29 @@ const fs = require('fs');
3
3
  const path = require('path');
4
4
  const { performance } = require('perf_hooks');
5
5
  const { createRequestPipeline } = require('./wasmAdapter');
6
- const { ALL_MIDDLEWARES, normalizeMiddlewareName } = require('./pathRules');
6
+ const wasmChecks = require('./wasmChecks');
7
+ const routeRisks = require('./routeRisks');
8
+ const { ALL_MIDDLEWARES, createRoutePlan } = require('./pathRules');
9
+ const { getEffectivePathRules } = require('./pathManifest');
10
+ const { getRequestIp } = require('./runtimeUtils');
11
+
12
+ // RATE_LIMIT names accepted in path rules, as in the regular rate limiter.
13
+ const RATE_KEYS = {
14
+ window: ['WINDOW_SEC', 'WINDOW', 'window_seconds', 'windowSeconds'],
15
+ max: ['MAX_REQ', 'MAX', 'max_requests', 'maxRequests'],
16
+ flood: ['FLOOD_REQ', 'FLOOD', 'flood_threshold', 'floodThreshold']
17
+ };
18
+ function rateOverrides(rule = {}) {
19
+ const limits = {};
20
+ for (const [name, keys] of Object.entries(RATE_KEYS)) {
21
+ const key = keys.find(k => rule[k] !== undefined && rule[k] !== null);
22
+ if (key === undefined) continue;
23
+ const value = Number(rule[key]);
24
+ if (!Number.isFinite(value) || (name !== 'window' && !Number.isInteger(value))) throw new Error(`RATE_LIMIT ${key} must be a number`);
25
+ limits[name] = value;
26
+ }
27
+ return limits;
28
+ }
7
29
 
8
30
  const LOG_HEADER = 'timestamp,ip,method,path,status,response_time_ms,blocked,reason,country,user_agent\n';
9
31
  const BLOCK_HEADER = 'ip,expires_at,reason\n';
@@ -54,13 +76,69 @@ function readRows(file, expected) {
54
76
  return Object.fromEntries(expected.map((key, index) => [key, cells[index]]));
55
77
  });
56
78
  }
79
+ // The content types whose bodies are inspected, as in Python. Uploads and other bodies
80
+ // (multipart, binary) pass through unread, as in the regular middleware.
81
+ function inspectable(req) {
82
+ const media = String(req.headers?.['content-type'] || '').split(';', 1)[0].trim().toLowerCase();
83
+ return ['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'].includes(media)
84
+ || media.endsWith('+json') || media.endsWith('+xml');
85
+ }
86
+ function declaredBody(req) {
87
+ return Number(req.headers?.['content-length'] || 0) > 0 || !!req.headers?.['transfer-encoding'];
88
+ }
89
+ // An unparsed inspectable body this adapter can read itself: identity-encoded and unread.
90
+ function readable(req) {
91
+ const encoding = String(req.headers?.['content-encoding'] || 'identity').trim().toLowerCase();
92
+ return req.body === undefined && declaredBody(req) && inspectable(req) && encoding === 'identity'
93
+ && typeof req.read === 'function' && typeof req.unshift === 'function' && !req.readableEnded;
94
+ }
95
+ const PEEKED = Symbol('aiwaf.native.peeked-body');
96
+ // Reads at most limit + 1 bytes of the body, then puts them back on the stream, so body
97
+ // parsers after this adapter still read the whole body. Python's adapters do the same.
98
+ function peekBody(req, limit) {
99
+ return new Promise((resolve, reject) => {
100
+ const chunks = [];
101
+ let size = 0;
102
+ const expected = Number(req.headers?.['content-length']) || null;
103
+ const finish = () => {
104
+ req.removeListener('readable', onReadable);
105
+ req.removeListener('error', onError);
106
+ const prefix = Buffer.concat(chunks);
107
+ if (prefix.length) req.unshift(prefix);
108
+ resolve(prefix);
109
+ };
110
+ const onError = error => { req.removeListener('readable', onReadable); reject(error); };
111
+ function onReadable() {
112
+ let chunk;
113
+ while ((chunk = req.read()) !== null) {
114
+ chunks.push(chunk);
115
+ size += chunk.length;
116
+ if (size > limit || size === expected) return finish();
117
+ }
118
+ // The whole body is buffered: put it back before the stream emits 'end'.
119
+ if (req._readableState?.ended) finish();
120
+ }
121
+ req.on('error', onError);
122
+ req.on('readable', onReadable);
123
+ });
124
+ }
57
125
  function safeBody(req, limit) {
126
+ const peeked = req[PEEKED];
127
+ if (peeked) {
128
+ if (peeked.length > limit) return { body: null, exhausted: true };
129
+ const text = peeked.toString('utf8');
130
+ // JSON is parsed here, as a body parser would, so it's checked exactly like a parsed body.
131
+ if (/json/.test(String(req.headers?.['content-type']))) {
132
+ try { return { body: JSON.parse(text), exhausted: false }; } catch (_) { /* checked as text */ }
133
+ }
134
+ return { body: text, exhausted: false };
135
+ }
58
136
  const body = req.body;
59
- if (body === undefined) {
60
- // Require a bounded parser before this adapter when a body is present.
61
- return { body: null, exhausted: Number(req.headers?.['content-length'] || 0) > 0 || !!req.headers?.['transfer-encoding'] };
137
+ if (body === undefined || (body && typeof body.pipe === 'function')) {
138
+ // An upload or other body that isn't inspected passes unread. An inspectable one this
139
+ // adapter couldn't read (compressed, or already consumed) can't be checked.
140
+ return { body: null, exhausted: declaredBody(req) && inspectable(req) };
62
141
  }
63
- if (body && typeof body.pipe === 'function') return { body: null, exhausted: true };
64
142
  try {
65
143
  const value = Buffer.isBuffer(body) ? body.toString('utf8') : body;
66
144
  const encoded = JSON.stringify(value);
@@ -68,12 +146,77 @@ function safeBody(req, limit) {
68
146
  return { body: value, exhausted: false };
69
147
  } catch (_) { return { body: null, exhausted: true }; }
70
148
  }
149
+ // Express trust proxy controls forwarded-IP handling. Never trust XFF directly.
150
+ function peerIp(req) {
151
+ return String(req.ip || req.socket?.remoteAddress || 'unknown').replace(/^::ffff:/, '');
152
+ }
153
+ // A model saved by `aiwaf train`, as the regular middleware's file storage keeps it.
154
+ async function readModelFile(file) {
155
+ const data = JSON.parse(await fs.promises.readFile(file, 'utf8'));
156
+ if (data?.model_type !== 'aiwaf_wasm.IsolationForest' || !data.model_state) {
157
+ throw new Error(`${file} isn't a model the native pipeline can use. Retrain with: aiwaf train`);
158
+ }
159
+ return require('./wasmAdapter').createIsolationForestFromJSON(data.model_state);
160
+ }
71
161
  function headers(raw = {}) {
72
162
  return Object.fromEntries(Object.entries(raw).map(([key, value]) => [
73
163
  ['content-type', 'content-length'].includes(key.toLowerCase()) ? key.toUpperCase().replace(/-/g, '_') : `HTTP_${key.toUpperCase().replace(/-/g, '_')}`,
74
164
  Array.isArray(value) ? value.join(', ') : String(value ?? '')
75
165
  ]));
76
166
  }
167
+ const STAGE_NAMES = ['geo_block', 'ip_keyword_block', 'rate_limit', 'ai_anomaly', 'honeypot', 'uuid_tamper', 'header_validation', 'logging'];
168
+ // Recent true/false answers per key, for `seconds`, keeping at most `limit` keys. A failed
169
+ // read isn't kept.
170
+ function recentAnswers(seconds, limit = 10000) {
171
+ const items = new Map();
172
+ const set = (key, value) => {
173
+ if (!(seconds > 0)) return;
174
+ items.delete(key);
175
+ items.set(key, { until: performance.now() + seconds * 1000, value: !!value });
176
+ while (items.size > limit) items.delete(items.keys().next().value);
177
+ };
178
+ return {
179
+ items,
180
+ set,
181
+ async get(key, load) {
182
+ const hit = items.get(key);
183
+ if (hit && hit.until > performance.now()) {
184
+ items.delete(key); items.set(key, hit);
185
+ return hit.value;
186
+ }
187
+ const value = !!(await load());
188
+ set(key, value);
189
+ return value;
190
+ }
191
+ };
192
+ }
193
+ // The store methods a stores option provides. Each may return a promise.
194
+ const STORE_METHODS = ['isBlocked', 'isExempted', 'topKeywords', 'blockedCountries', 'block', 'learn'];
195
+ // Node's own blocklist, exemption, keyword and geo stores: a database when one is configured,
196
+ // otherwise their CSV files, as the regular middleware uses them.
197
+ function regularStores({ dynamicTopN = 10, exemptionsDb = true } = {}) {
198
+ const blocklistManager = require('./blocklistManager');
199
+ const exemptionStore = require('./exemptionStore');
200
+ const dynamicKeywordStore = require('./dynamicKeywordStore');
201
+ const geoStore = require('./geoStore');
202
+ return {
203
+ isBlocked: ip => blocklistManager.isBlocked(ip),
204
+ async isExempted(ip, requestPath) {
205
+ if (!exemptionsDb) return false;
206
+ // Exemption storage failures fail open, as in the regular middleware.
207
+ try {
208
+ return !!(await exemptionStore.isIpExempt(String(ip).toLowerCase())
209
+ || await exemptionStore.isPathExempt(String(requestPath).toLowerCase()));
210
+ } catch (_) { return false; }
211
+ },
212
+ // A learned keyword applies once its count passes dynamicTopN, as in the regular middleware.
213
+ topKeywords: async limit => (await dynamicKeywordStore.list(limit))
214
+ .filter(row => Number(row.count || 0) > dynamicTopN).map(row => String(row.keyword)),
215
+ blockedCountries: async () => (await geoStore.listBlockedCountries()).map(row => String(row.country_code)),
216
+ block: (ip, reason) => blocklistManager.block(ip, reason),
217
+ learn: keyword => dynamicKeywordStore.increment(keyword)
218
+ };
219
+ }
77
220
  function synchronous(callback, req, fallback) {
78
221
  const result = callback ? callback(req) : fallback;
79
222
  if (result && typeof result.then === 'function') throw new TypeError('Native fact callbacks must return synchronous values');
@@ -83,19 +226,81 @@ function synchronous(callback, req, fallback) {
83
226
  module.exports = async function createNativeMiddleware(options = {}) {
84
227
  if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Native adapter options must be an object');
85
228
  if (options.profile !== undefined && (!options.profile || typeof options.profile !== 'object' || Array.isArray(options.profile))) throw new TypeError('Native profile must be an object');
86
- const allowed = new Set(['profile', 'dataDir', 'logPath', 'logFsync', 'persistBlocks', 'model', 'countryLookup', 'authenticated', 'routeExists', 'onError']);
229
+ const allowed = new Set(['profile', 'dataDir', 'logPath', 'logFsync', 'persistBlocks', 'model', 'countryLookup', 'authenticated', 'routeExists', 'onError', 'pathRules', 'manifestPath', 'injectionRiskMode', 'logger', 'uuidResolver', 'stores', 'storeCacheSeconds', 'storesFallback',
230
+ 'rateCounter', 'rateCounterFallback', 'rateFailureMode', 'trustedProxies', 'modelFile']);
87
231
  for (const key of Object.keys(options)) if (!allowed.has(key)) throw new Error(`Unknown native adapter option: ${key}`);
232
+ if (options.uuidResolver != null && typeof options.uuidResolver !== 'function') throw new TypeError('uuidResolver must be a function');
88
233
  for (const key of ['countryLookup','authenticated','routeExists','onError']) {
89
234
  if (options[key] != null && (typeof options[key] !== 'function' || options[key].constructor.name === 'AsyncFunction')) throw new TypeError(`${key} must be synchronous`);
90
235
  }
236
+ if (options.pathRules != null && !Array.isArray(options.pathRules)) throw new TypeError('pathRules must be an array of rules');
237
+ let stores = null;
238
+ if (options.stores === 'regular') stores = regularStores();
239
+ else if (options.stores != null) {
240
+ if (typeof options.stores !== 'object') throw new TypeError('stores must be "regular" or an object with the store methods');
241
+ const missing = STORE_METHODS.filter(name => typeof options.stores[name] !== 'function');
242
+ if (missing.length) throw new TypeError(`stores is missing ${missing.join(', ')}`);
243
+ stores = options.stores;
244
+ }
245
+ if (options.storesFallback != null && options.storesFallback !== 'csv') throw new TypeError('storesFallback must be "csv"');
246
+ let rateCounter = options.rateCounter ?? null;
247
+ if (rateCounter !== null && typeof rateCounter?.count !== 'function') throw new TypeError('rateCounter must have a count(key, now, windowSeconds) method');
248
+ if (options.rateCounterFallback != null && options.rateCounterFallback !== 'memory') throw new TypeError('rateCounterFallback must be "memory"');
249
+ const rateFailureMode = options.rateFailureMode ?? 'closed';
250
+ if (!['closed', 'open'].includes(rateFailureMode)) throw new TypeError('rateFailureMode must be "closed" or "open"');
251
+ // With trustedProxies, the client address is resolved as the regular middleware resolves
252
+ // it (AIWAF_TRUSTED_PROXIES); without it, from req.ip, which Express trust proxy controls.
253
+ const clientIp = options.trustedProxies === undefined ? peerIp
254
+ : req => getRequestIp(req, options.trustedProxies).replace(/^::ffff:/, '');
255
+ if (options.modelFile != null && (options.model != null || typeof options.modelFile !== 'string')) {
256
+ throw new TypeError('modelFile must be a path, and can\'t be combined with model');
257
+ }
258
+ const storeCacheSeconds = Number(options.storeCacheSeconds ?? 5);
259
+ if (!(storeCacheSeconds >= 0)) throw new TypeError('storeCacheSeconds must be a non-negative number');
91
260
  const profile = JSON.parse(JSON.stringify(options.profile || {}));
261
+ const manifestPath = options.manifestPath ?? process.env.AIWAF_PATH_MANIFEST;
262
+ const rules = getEffectivePathRules(options.pathRules || [], manifestPath ? { manifestPath } : undefined);
263
+ // Checked once, so a bad rule fails at startup rather than on a request.
264
+ const profileRate = { window: profile.rate_window ?? 10, max: profile.rate_max ?? 20, flood: profile.rate_flood ?? 40 };
265
+ for (const rule of rules) {
266
+ const limits = { ...profileRate, ...rateOverrides(rule.RATE_LIMIT || rule.rate_limit || {}) };
267
+ if (!(limits.window > 0) || !(limits.max > 0) || limits.flood < limits.max || limits.flood > 100000) {
268
+ throw new Error(`Invalid RATE_LIMIT for path rule ${JSON.stringify(rule.PREFIX ?? rule.prefix)}`);
269
+ }
270
+ }
271
+ const routePlan = req => {
272
+ const meta = req.aiwafRoute || {};
273
+ const plan = createRoutePlan(String(req.path || req.url || '/').split('?')[0], rules, meta);
274
+ return { plan, disabled: ALL_MIDDLEWARES.filter(name => !plan.shouldApply(name)), rate: rateOverrides(plan.getOverrides('RATE_LIMIT')) };
275
+ };
92
276
  if (!Object.hasOwn(profile, 'blocklist') && Object.hasOwn(profile, 'blacklist')) profile.blocklist = profile.blacklist;
93
277
  delete profile.blacklist;
94
278
  const dataDir = path.resolve(options.dataDir || 'aiwaf_native_data');
95
279
  // State files are dedicated to this adapter. Legacy ORM/CSV schemas are not mixed.
96
280
  const blockPath = path.join(dataDir, 'native_blocks.csv');
97
281
  const keywordPath = path.join(dataDir, 'native_keywords.csv');
98
- const persist = options.persistBlocks !== false;
282
+ if (rateCounter) {
283
+ const probe = await createRequestPipeline({});
284
+ const supported = typeof probe.native.supports === 'function' && probe.native.supports('rate_count');
285
+ probe.native.free();
286
+ if (!supported && options.rateCounterFallback === 'memory') {
287
+ (options.logger || console).warn?.('AIWAF native: this aiwaf-wasm can\'t use a shared rate counter, so rate limits are counted in each worker. Run: npm install aiwaf-wasm@latest');
288
+ rateCounter = null;
289
+ } else if (!supported) throw new Error('rateCounter needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
290
+ }
291
+ if (stores) {
292
+ // Checked before the profile is built, since older engines reject policy_store.
293
+ const probe = await createRequestPipeline({});
294
+ const supported = typeof probe.native.supports === 'function' && probe.native.supports('host_store');
295
+ probe.native.free();
296
+ if (!supported && options.storesFallback === 'csv') {
297
+ (options.logger || console).warn?.('AIWAF native: this aiwaf-wasm can\'t use stores, so blocks and learned keywords are kept in dataDir. Run: npm install aiwaf-wasm@latest');
298
+ stores = null;
299
+ } else if (!supported) throw new Error('stores needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
300
+ }
301
+ // With stores, blocks and learned keywords live in the stores instead of dataDir.
302
+ const persist = !stores && options.persistBlocks !== false;
303
+ if (stores) profile.policy_store = 'host';
99
304
  const opened = [];
100
305
  let log, blocks, keywords, engine;
101
306
  try {
@@ -110,46 +315,172 @@ module.exports = async function createNativeMiddleware(options = {}) {
110
315
  profile.blocklist = blocklist;
111
316
  profile.dynamic_keywords = [...new Set([...(profile.dynamic_keywords || []), ...readRows(keywordPath, ['keyword']).map(r => r.keyword)])];
112
317
  }
113
- engine = await createRequestPipeline(profile, options.model);
318
+ let model = options.model;
319
+ if (options.modelFile != null) model = await readModelFile(options.modelFile);
320
+ try {
321
+ engine = await createRequestPipeline(profile, model);
322
+ } catch (error) {
323
+ // Older aiwaf-wasm builds reject monitor mode as an unsupported policy.
324
+ if (profile.sql_mode === 'monitor' && /Unsupported native policy/.test(String(error?.message ?? error))) {
325
+ throw new Error('sql_mode "monitor" needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
326
+ }
327
+ throw error;
328
+ }
114
329
  if (!profile.enabled || profile.enabled.includes('logging')) {
115
330
  log = writer(path.resolve(options.logPath || path.join(dataDir, 'native_requests.csv')), LOG_HEADER, !!options.logFsync); opened.push(log);
116
331
  }
117
332
  } catch (error) { if (engine) engine.native.free(); for (const entry of opened) entry.close(); throw error; }
118
333
  const { native, setModel } = engine;
334
+ const logger = options.logger || console;
335
+ // Monitored SQL findings are logged as the regular middleware logs them, and never block.
336
+ const monitored = finding => {
337
+ if (finding?.mode !== 'monitor') return finding;
338
+ logger.warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: 'monitor' });
339
+ return null;
340
+ };
341
+ if (options.uuidResolver && !(typeof native.supports === 'function' && native.supports('uuid_resolver'))) {
342
+ native.free(); for (const entry of opened) entry.close();
343
+ throw new Error('uuidResolver needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
344
+ }
345
+ const uuidPrefix = String(profile.uuid_prefix ?? '/user/').toLowerCase();
346
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
347
+ // The UUID the engine checks, as it finds it: one path segment under uuid_prefix.
348
+ const pathUuid = rawPath => {
349
+ if (!rawPath.toLowerCase().startsWith(uuidPrefix)) return null;
350
+ const uid = rawPath.slice(uuidPrefix.length).replace(/\/+$/, '');
351
+ return !uid.includes('/') && UUID.test(uid) ? uid : null;
352
+ };
353
+ const needsRateOverrides = rules.some(rule => Object.keys(rateOverrides(rule.RATE_LIMIT || rule.rate_limit || {})).length);
354
+ if (needsRateOverrides && !(typeof native.supports === 'function' && native.supports('rate_overrides'))) {
355
+ native.free(); for (const entry of opened) entry.close();
356
+ throw new Error('Path-rule RATE_LIMIT needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
357
+ }
119
358
  const maxBytes = profile.max_bytes ?? 65536;
120
359
  let closed = false;
121
360
  const contextKey = Symbol('aiwaf.native.context');
122
361
  const pending = new Set();
362
+ // Keywords and countries change rarely, so they're read at most every storeCacheSeconds.
363
+ const cache = new Map();
364
+ const cached = (name, load) => {
365
+ const now = performance.now();
366
+ const entry = cache.get(name);
367
+ if (entry && now < entry.until) return entry.value;
368
+ const value = Promise.resolve().then(load).then(items => [...(items || [])].map(String));
369
+ cache.set(name, { until: now + storeCacheSeconds * 1000, value });
370
+ // A failed read isn't kept, so the next request tries again.
371
+ value.catch(() => { if (cache.get(name)?.value === value) cache.delete(name); });
372
+ return value;
373
+ };
374
+ // Blocklist and exemption answers, per IP and per IP and path, for storeCacheSeconds. A block
375
+ // or exemption made elsewhere can take that long to apply; this worker's own blocks apply at once.
376
+ const blockedIps = recentAnswers(storeCacheSeconds);
377
+ const exempted = recentAnswers(storeCacheSeconds);
378
+ const stageOn = (route, name) => route.plan.shouldApply(name) && (!profile.enabled || profile.enabled.includes(name));
379
+ // The host stores' facts for one request. A store read that fails is reported and treated
380
+ // as not blocked, not exempt and nothing learned, so storage outages don't block traffic.
381
+ const storeFacts = async (req, route) => {
382
+ const ip = clientIp(req);
383
+ const rawPath = String(req.path || req.url || '/').split('?')[0];
384
+ const read = async (load, fallback) => { try { return await load(); } catch (error) { report(error); return fallback; } };
385
+ // Only what this request's stages use: an exempt request runs logging alone.
386
+ const active = STAGE_NAMES.filter(name => stageOn(route, name));
387
+ if (!active.some(name => name !== 'logging')) return {};
388
+ const exempt = await read(() => exempted.get(`${ip}\u0000${rawPath}`, () => stores.isExempted(ip, rawPath)), false);
389
+ if (exempt) return { exempt: true };
390
+ const [blocked, keywords, countries] = await Promise.all([
391
+ active.includes('ip_keyword_block') || active.includes('ai_anomaly') ? read(() => blockedIps.get(ip, () => stores.isBlocked(ip)), false) : false,
392
+ active.includes('ip_keyword_block') ? read(() => cached('keywords', () => stores.topKeywords(2000)), []) : [],
393
+ active.includes('geo_block') ? read(() => cached('countries', () => stores.blockedCountries()), []) : []
394
+ ]);
395
+ return { blocked: !!blocked, exempt: false, dynamic_keywords: keywords, geo_countries: countries };
396
+ };
397
+ // The engine's literal, case-insensitive exemptions: exempt requests aren't rate limited,
398
+ // so they aren't counted either.
399
+ const exemptIps = new Set(profile.exempt_ips || []);
400
+ const exemptPaths = (profile.exempt_paths ?? ['/health', '/robots.txt', '/sitemap.xml']).map(p => String(p).toLowerCase());
401
+ // The shared count for this request's rate window, counted before the engine decides.
402
+ const rateCount = async (req, route, exempt) => {
403
+ const ip = clientIp(req);
404
+ const rawPath = String(req.path || req.url || '/').split('?')[0];
405
+ if (exempt || exemptIps.has(ip) || exemptPaths.some(p => rawPath.toLowerCase().startsWith(p))) return undefined;
406
+ const key = profile.rate_key_mode === 'ip' ? `ratelimit:${ip}` : `ratelimit:${ip}:${rawPath}`;
407
+ const window = Math.max(route.rate.window ?? profile.rate_window ?? 10, 1);
408
+ return rateCounter.count(key, Date.now() / 1000, window);
409
+ };
123
410
  const report = error => { if (options.onError) options.onError(error); else console.error('AIWAF native finalization failed:', error.message); };
411
+ // This pipeline takes no general settings, so these two come from the environment. Route
412
+ // checks run in aiwaf-wasm, loaded here so requests can use them straight away.
413
+ const observeRisks = routeRisks.createObserver({ AIWAF_PATH_MANIFEST: manifestPath, AIWAF_INJECTION_RISK_MODE: options.injectionRiskMode });
414
+ if (observeRisks) await wasmChecks.load();
124
415
  function payload(req) {
125
416
  const b = safeBody(req, maxBytes);
126
417
  const query = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
127
- if (b.exhausted && profile.sql_mode !== 'off') return { status: 413, rule: 'payload_inspection_limit' };
128
- return JSON.parse(native.inspect_payload(JSON.stringify([query, b.body, req.query ?? null])));
418
+ if (b.exhausted && profile.sql_mode !== 'off') {
419
+ return monitored({ status: 413, rule: 'payload_inspection_limit', mode: profile.sql_mode });
420
+ }
421
+ return monitored(JSON.parse(native.inspect_payload(JSON.stringify([query, b.body, req.query ?? null]))));
129
422
  }
423
+ // A uuidResolver may be async, so only requests it applies to wait for it.
130
424
  const middleware = (req, res, next) => {
131
425
  if (closed) return next(new Error('Native pipeline is closed'));
132
- let decision;
133
426
  const start = performance.now();
427
+ let route;
428
+ try { route = routePlan(req); } catch (error) { return next(error); }
429
+ const uid = options.uuidResolver && route.plan.shouldApply('uuid_tamper')
430
+ && (!profile.enabled || profile.enabled.includes('uuid_tamper'))
431
+ ? pathUuid(String(req.path || req.url || '/').split('?')[0]) : null;
432
+ let found = null;
433
+ if (uid) {
434
+ // A failing resolver doesn't block, as in the regular middleware.
435
+ try { found = options.uuidResolver(uid, req); } catch (_) { found = null; }
436
+ if (found && typeof found.then === 'function') found = found.then(exists => !!exists, () => null);
437
+ else if (found !== null) found = !!found;
438
+ }
439
+ const counted = rateCounter && stageOn(route, 'rate_limit');
440
+ const peek = !req[DEFER_BODY] && !req[PEEKED] && profile.sql_mode !== 'off' && stageOn(route, 'ip_keyword_block') && readable(req)
441
+ ? peekBody(req, maxBytes).then(prefix => { req[PEEKED] = prefix; }) : null;
442
+ if (!stores && !counted && !peek && !(found && typeof found.then === 'function')) return handle(req, res, next, route, start, found, null);
443
+ return Promise.all([found, stores ? storeFacts(req, route) : null, peek])
444
+ .then(async ([exists, facts]) => {
445
+ if (counted) {
446
+ let count;
447
+ try { count = await rateCount(req, route, facts?.exempt); } catch (error) {
448
+ report(error);
449
+ // As the regular rate limiter does: closed answers 503, open lets the request through.
450
+ if (rateFailureMode === 'closed') return res.status(503).json({ error: 'temporarily_unavailable' });
451
+ }
452
+ if (count !== undefined) facts = { ...(facts || {}), rate_count: count };
453
+ }
454
+ return handle(req, res, next, route, start, exists, facts);
455
+ }, next);
456
+ };
457
+ const handle = (req, res, next, route, start, uuidExists, facts) => {
458
+ if (closed) return next(new Error('Native pipeline is closed'));
459
+ let decision;
134
460
  try {
135
- const meta = req.aiwafRoute || {};
136
- const required = new Set((meta.requiredMiddlewares || []).map(normalizeMiddlewareName));
137
- const disabled = new Set((meta.fullyExempt ? ALL_MIDDLEWARES : meta.exemptMiddlewares || []).map(normalizeMiddlewareName));
138
- for (const key of required) disabled.delete(key);
461
+ const { plan, disabled, rate } = route;
462
+ if (observeRisks && plan.shouldApply('ip_keyword_block')
463
+ && (!profile.enabled || profile.enabled.includes('ip_keyword_block'))) {
464
+ const riskFinding = observeRisks(req);
465
+ if (riskFinding) return res.status(riskFinding.status).json({ error: riskFinding.rule });
466
+ }
139
467
  const rawPath = String(req.path || req.url || '/').split('?')[0];
140
468
  const body = req[DEFER_BODY] ? {body:null,exhausted:false} : safeBody(req, maxBytes);
141
469
  decision = JSON.parse(native.begin(JSON.stringify({
142
- // Express trust proxy controls forwarded-IP handling. Never trust XFF directly.
143
- ip: String(req.ip || req.socket?.remoteAddress || 'unknown').replace(/^::ffff:/, ''),
470
+ ip: clientIp(req),
144
471
  path: rawPath, method: String(req.method || 'GET'), headers: headers(req.headers),
145
472
  query: String(req.originalUrl || req.url || '').split('?').slice(1).join('?'),
146
473
  body: body.body, parsed_query: req.query ?? null,
147
474
  now: Date.now() / 1000, country: String(synchronous(options.countryLookup, req, '') || ''),
148
475
  authenticated: req[DEFER_BODY] ? false : !!synchronous(options.authenticated, req, false),
149
- exists: !!synchronous(options.routeExists, req, !!req.route), disabled: [...disabled],
150
- payload_exhausted: body.exhausted, defer_body: !!req[DEFER_BODY]
476
+ exists: !!synchronous(options.routeExists, req, !!req.route), disabled,
477
+ payload_exhausted: body.exhausted, defer_body: !!req[DEFER_BODY],
478
+ ...(Object.keys(rate).length ? { rate } : {}),
479
+ ...(uuidExists === null ? {} : { uuid_exists: uuidExists }),
480
+ ...(facts || {})
151
481
  })));
152
482
  } catch (error) { return next(error); }
483
+ if (decision.monitor) monitored({ rule: decision.monitor, mode: 'monitor' });
153
484
  pending.add(decision.context);
154
485
  req[contextKey] = decision.context;
155
486
  let done = false;
@@ -161,6 +492,7 @@ module.exports = async function createNativeMiddleware(options = {}) {
161
492
  if (blocks && effects.block_csv) blocks.append(effects.block_csv);
162
493
  if (keywords && effects.keyword_csv) keywords.append(effects.keyword_csv);
163
494
  if (log && effects.log_csv) log.append(effects.log_csv);
495
+ if (stores) writeEffects(effects);
164
496
  } catch (error) { report(error); }
165
497
  };
166
498
  res.on('finish', () => finalize(false));
@@ -168,17 +500,29 @@ module.exports = async function createNativeMiddleware(options = {}) {
168
500
  if (decision.status) return res.status(decision.status).json({ error: decision.reason });
169
501
  return next();
170
502
  };
503
+ // Store writes run after the response, so a slow or failing store never delays it.
504
+ const writeEffects = effects => {
505
+ if (effects.block) {
506
+ blockedIps.set(effects.block.ip, true);
507
+ Promise.resolve().then(() => stores.block(effects.block.ip, effects.block.reason, effects.block.expires_at)).catch(report);
508
+ }
509
+ if (effects.keyword) {
510
+ Promise.resolve().then(() => stores.learn(effects.keyword))
511
+ .then(() => cache.delete('keywords'), report);
512
+ }
513
+ };
171
514
  middleware.inspectPayload = req => {
172
- const disabled = req.aiwafRoute?.exemptMiddlewares || [];
173
515
  if (profile.enabled && !profile.enabled.includes('ip_keyword_block')) return null;
174
- if (req.aiwafRoute?.fullyExempt || disabled.includes('ip_keyword_block')) return null;
516
+ if (!routePlan(req).plan.shouldApply('ip_keyword_block')) return null;
517
+ const riskFinding = observeRisks ? observeRisks(req) : null;
518
+ if (riskFinding) return riskFinding;
175
519
  return payload(req);
176
520
  };
177
521
  middleware.diagnostics = () => JSON.parse(native.diagnostics());
178
522
  middleware.inspectBody = (req, body) => {
179
523
  const captured = safeBody({body,headers:{}},maxBytes);
180
- return JSON.parse(native.inspect_body(req[contextKey], JSON.stringify(captured.body), captured.exhausted,
181
- !!synchronous(options.authenticated,req,false), Date.now()/1000));
524
+ return monitored(JSON.parse(native.inspect_body(req[contextKey], JSON.stringify(captured.body), captured.exhausted,
525
+ !!synchronous(options.authenticated,req,false), Date.now()/1000)));
182
526
  };
183
527
  middleware.setModel = setModel;
184
528
  middleware.close = () => {
@@ -191,3 +535,6 @@ module.exports = async function createNativeMiddleware(options = {}) {
191
535
  return middleware;
192
536
  };
193
537
  module.exports.DEFER_BODY = DEFER_BODY;
538
+ module.exports.regularStores = regularStores;
539
+ module.exports.recentAnswers = recentAnswers;
540
+ module.exports.redisRateCounter = require('./nativeRateCounter').redisRateCounter;
@@ -0,0 +1,45 @@
1
+ 'use strict';
2
+
3
+ // Shared rate counts for the native pipeline. Redis counts; aiwaf-wasm still decides.
4
+ const crypto = require('crypto');
5
+
6
+ // The regular Python limiter's sliding window, so both runtimes keep the same bucket format.
7
+ const SCRIPT = `
8
+ local raw = redis.call('GET', KEYS[1])
9
+ local old = raw and cjson.decode(raw) or {}
10
+ local now, window = tonumber(ARGV[1]), tonumber(ARGV[2])
11
+ local current = {}
12
+ for _, timestamp in ipairs(old) do
13
+ if now - timestamp < window then table.insert(current, timestamp) end
14
+ end
15
+ table.insert(current, now)
16
+ redis.call('SET', KEYS[1], cjson.encode(current), 'PX', math.ceil(window * 1000))
17
+ return #current
18
+ `;
19
+
20
+ // A fixed-length key, so long paths can't make long Redis keys.
21
+ function boundedKey(namespace, key) {
22
+ return `${namespace}:${crypto.createHash('sha256').update(key).digest('hex')}`;
23
+ }
24
+
25
+ /**
26
+ * Counts native rate limits in Redis, atomically across workers. Takes a node-redis v4
27
+ * client (sendCommand) or an ioredis client (call).
28
+ */
29
+ function redisRateCounter(client, { namespace = 'aiwaf:native:rate:v1' } = {}) {
30
+ const call = typeof client?.call === 'function' ? args => client.call(...args)
31
+ : typeof client?.sendCommand === 'function' ? args => client.sendCommand(args) : null;
32
+ if (!call) throw new TypeError('redisRateCounter needs a node-redis or ioredis client');
33
+ if (typeof namespace !== 'string' || !namespace || Buffer.byteLength(namespace) > 100) {
34
+ throw new TypeError('namespace must be a nonempty string of at most 100 bytes');
35
+ }
36
+ return {
37
+ async count(key, now, windowSeconds) {
38
+ const count = Number(await call(['EVAL', SCRIPT, '1', boundedKey(namespace, key), String(now), String(windowSeconds)]));
39
+ if (!Number.isInteger(count) || count < 1) throw new Error('Invalid Redis rate count');
40
+ return count;
41
+ }
42
+ };
43
+ }
44
+
45
+ module.exports = { redisRateCounter, boundedKey, SCRIPT };