aiwaf 1.2.1 → 1.2.3

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.
@@ -158,6 +158,51 @@ async function readModelFile(file) {
158
158
  }
159
159
  return require('./wasmAdapter').createIsolationForestFromJSON(data.model_state);
160
160
  }
161
+ // A model from the app's model store, read as the regular anomaly check reads it: none when
162
+ // the store has none or can't be read. A model in the older JavaScript format can't be used.
163
+ async function loadedModel(load) {
164
+ let data = null;
165
+ try { data = await load(); } catch (_) { data = null; }
166
+ if (!data) return null;
167
+ if (data.model_type !== 'aiwaf_wasm.IsolationForest' || !data.model_state) {
168
+ throw new Error('The stored model is in an older format the native pipeline can\'t load. Retrain with: aiwaf train');
169
+ }
170
+ return require('./wasmAdapter').createIsolationForestFromJSON(data.model_state);
171
+ }
172
+ const COUNTRY = Symbol('aiwaf.country');
173
+ // Node.js's regular anomaly check (the ai_anomaly stage in lib/wafMiddleware.js): for a path
174
+ // with no known route, the regular model's verdict on the request's features, then its recent
175
+ // history from the request log. Resolves to a block reason, or null.
176
+ async function createRegularAnomaly(opts) {
177
+ const anomalyDetector = require('./anomalyDetector');
178
+ const featureUtils = require('./featureUtils');
179
+ featureUtils.init(opts);
180
+ await anomalyDetector.init(opts);
181
+ return {
182
+ start: req => featureUtils.markRequestStart(req),
183
+ async check(req, ip) {
184
+ if (require('./wafMiddleware').matchesKnownRoute(req.app, req.path || req.url || '/')) return null;
185
+ const features = await featureUtils.extractFeatures(req);
186
+ if (!(await anomalyDetector.isAnomalous(features)) || !anomalyDetector.isModelSufficientlyTrained()) return null;
187
+ const now = Date.now();
188
+ let rows = [];
189
+ try { rows = await require('./requestLogStore').recent(5000); } catch (_) { rows = []; }
190
+ const recent = rows.filter(row => row.ip_address === ip)
191
+ .map(row => ({ timestamp: row.created_at ? new Date(row.created_at).getTime() : now, path: row.path,
192
+ status: Number(row.status || 0), responseTime: Number(row.response_time_ms || 0) }))
193
+ .filter(entry => now - entry.timestamp <= 5 * 60 * 1000);
194
+ const stats = await anomalyDetector.analyzeRecentBehaviorAccelerated(recent);
195
+ return stats && stats.should_block
196
+ ? `AI anomaly + scanning 404s (total:${stats.max_404s}, scanning:${stats.scanning_404s}, kw:${stats.avg_kw_hits.toFixed(1)}, burst:${stats.avg_burst.toFixed(1)})`
197
+ : null;
198
+ }
199
+ };
200
+ }
201
+ // Recorded for the regular request logger, as the regular middleware records its blocks.
202
+ function markBlocked(res, reason, country = '') {
203
+ if (!res.locals) res.locals = {};
204
+ res.locals.aiwafDecision = { blocked: true, reason, country };
205
+ }
161
206
  function headers(raw = {}) {
162
207
  return Object.fromEntries(Object.entries(raw).map(([key, value]) => [
163
208
  ['content-type', 'content-length'].includes(key.toLowerCase()) ? key.toUpperCase().replace(/-/g, '_') : `HTTP_${key.toUpperCase().replace(/-/g, '_')}`,
@@ -194,7 +239,7 @@ function recentAnswers(seconds, limit = 10000) {
194
239
  const STORE_METHODS = ['isBlocked', 'isExempted', 'topKeywords', 'blockedCountries', 'block', 'learn'];
195
240
  // Node's own blocklist, exemption, keyword and geo stores: a database when one is configured,
196
241
  // otherwise their CSV files, as the regular middleware uses them.
197
- function regularStores({ dynamicTopN = 10, exemptionsDb = true } = {}) {
242
+ function regularStores({ dynamicTopN = 10, exemptionsDb = true, extendedInfo = null } = {}) {
198
243
  const blocklistManager = require('./blocklistManager');
199
244
  const exemptionStore = require('./exemptionStore');
200
245
  const dynamicKeywordStore = require('./dynamicKeywordStore');
@@ -212,8 +257,17 @@ function regularStores({ dynamicTopN = 10, exemptionsDb = true } = {}) {
212
257
  // A learned keyword applies once its count passes dynamicTopN, as in the regular middleware.
213
258
  topKeywords: async limit => (await dynamicKeywordStore.list(limit))
214
259
  .filter(row => Number(row.count || 0) > dynamicTopN).map(row => String(row.keyword)),
260
+ // The counts themselves, so learning not yet written can count at once, as the regular
261
+ // middleware's in-memory counts do.
262
+ keywordCounts: async limit => (await dynamicKeywordStore.list(limit))
263
+ .map(row => [String(row.keyword), Number(row.count || 0)]),
264
+ activeAbove: dynamicTopN,
215
265
  blockedCountries: async () => (await geoStore.listBlockedCountries()).map(row => String(row.country_code)),
216
- block: (ip, reason) => blocklistManager.block(ip, reason),
266
+ // As the regular middleware writes a block: with the request's extended info when the app
267
+ // captures it (AIWAF_CAPTURE_EXTENDED_REQUEST_INFO), otherwise an empty object.
268
+ block: (ip, reason, _expiresAt, req) => blocklistManager.block(ip, reason, req ? {
269
+ extendedRequestInfo: (extendedInfo && require('./runtimeUtils').extractExtendedRequestInfo(req, extendedInfo)) || {}
270
+ } : undefined),
217
271
  learn: keyword => dynamicKeywordStore.increment(keyword)
218
272
  };
219
273
  }
@@ -227,10 +281,14 @@ module.exports = async function createNativeMiddleware(options = {}) {
227
281
  if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Native adapter options must be an object');
228
282
  if (options.profile !== undefined && (!options.profile || typeof options.profile !== 'object' || Array.isArray(options.profile))) throw new TypeError('Native profile must be an object');
229
283
  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']);
284
+ 'rateCounter', 'rateCounterFallback', 'rateFailureMode', 'trustedProxies', 'modelFile', 'modelLoader', 'regularLog', 'modelGate', 'exact', 'regularAnomaly', 'userAgentVerdict']);
231
285
  for (const key of Object.keys(options)) if (!allowed.has(key)) throw new Error(`Unknown native adapter option: ${key}`);
232
286
  if (options.uuidResolver != null && typeof options.uuidResolver !== 'function') throw new TypeError('uuidResolver must be a function');
233
- for (const key of ['countryLookup','authenticated','routeExists','onError']) {
287
+ // countryLookup may return a promise; the request waits for it, as for uuidResolver.
288
+ if (options.countryLookup != null && typeof options.countryLookup !== 'function') throw new TypeError('countryLookup must be a function');
289
+ if (options.modelLoader != null && typeof options.modelLoader !== 'function') throw new TypeError('modelLoader must be a function');
290
+ if (options.userAgentVerdict != null && typeof options.userAgentVerdict !== 'function') throw new TypeError('userAgentVerdict must be a function');
291
+ for (const key of ['authenticated','routeExists','onError']) {
234
292
  if (options[key] != null && (typeof options[key] !== 'function' || options[key].constructor.name === 'AsyncFunction')) throw new TypeError(`${key} must be synchronous`);
235
293
  }
236
294
  if (options.pathRules != null && !Array.isArray(options.pathRules)) throw new TypeError('pathRules must be an array of rules');
@@ -255,23 +313,44 @@ module.exports = async function createNativeMiddleware(options = {}) {
255
313
  if (options.modelFile != null && (options.model != null || typeof options.modelFile !== 'string')) {
256
314
  throw new TypeError('modelFile must be a path, and can\'t be combined with model');
257
315
  }
316
+ // The regular request logger, run beside the native pipeline with the regular options, when
317
+ // the app logs requests its own way (a JSONL, CSV or database log).
318
+ let regularLog = null;
319
+ if (options.regularLog != null) {
320
+ regularLog = require('./middlewareLogger');
321
+ regularLog.init(options.regularLog);
322
+ }
323
+ // The regular anomaly check, run with the regular options after the engine's stages, as the
324
+ // regular middleware runs it last: its features, model, log minimum and request-log history.
325
+ let regularAnomaly = null;
326
+ if (options.regularAnomaly != null) regularAnomaly = await createRegularAnomaly(options.regularAnomaly);
258
327
  const storeCacheSeconds = Number(options.storeCacheSeconds ?? 5);
259
328
  if (!(storeCacheSeconds >= 0)) throw new TypeError('storeCacheSeconds must be a non-negative number');
260
329
  const profile = JSON.parse(JSON.stringify(options.profile || {}));
261
330
  const manifestPath = options.manifestPath ?? process.env.AIWAF_PATH_MANIFEST;
262
331
  const rules = getEffectivePathRules(options.pathRules || [], manifestPath ? { manifestPath } : undefined);
263
- // Checked once, so a bad rule fails at startup rather than on a request.
332
+ // The regular rate limiter flood-blocks above the flood threshold before a higher limit is
333
+ // reached, so a limit above it acts as the threshold: the engine is given that.
334
+ if (profile.rate_max !== undefined && profile.rate_max > (profile.rate_flood ?? 40)) profile.rate_max = profile.rate_flood ?? 40;
264
335
  const profileRate = { window: profile.rate_window ?? 10, max: profile.rate_max ?? 20, flood: profile.rate_flood ?? 40 };
336
+ const effectiveRate = overrides => {
337
+ if (!Object.keys(overrides).length) return overrides;
338
+ const limits = { ...profileRate, ...overrides };
339
+ limits.flood = Math.min(limits.flood, 100000);
340
+ limits.max = Math.min(limits.max, limits.flood);
341
+ return limits;
342
+ };
343
+ // Checked once, so a bad rule fails at startup rather than on a request.
265
344
  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) {
345
+ const limits = effectiveRate(rateOverrides(rule.RATE_LIMIT || rule.rate_limit || {}));
346
+ if (Object.keys(limits).length && (!(limits.window > 0) || !(limits.max > 0))) {
268
347
  throw new Error(`Invalid RATE_LIMIT for path rule ${JSON.stringify(rule.PREFIX ?? rule.prefix)}`);
269
348
  }
270
349
  }
271
350
  const routePlan = req => {
272
351
  const meta = req.aiwafRoute || {};
273
352
  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')) };
353
+ return { plan, disabled: ALL_MIDDLEWARES.filter(name => !plan.shouldApply(name)), rate: effectiveRate(rateOverrides(plan.getOverrides('RATE_LIMIT'))) };
275
354
  };
276
355
  if (!Object.hasOwn(profile, 'blocklist') && Object.hasOwn(profile, 'blacklist')) profile.blocklist = profile.blacklist;
277
356
  delete profile.blacklist;
@@ -288,6 +367,35 @@ module.exports = async function createNativeMiddleware(options = {}) {
288
367
  rateCounter = null;
289
368
  } else if (!supported) throw new Error('rateCounter needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
290
369
  }
370
+ {
371
+ // Header caps, blocked user agents and login forms need a newer aiwaf-wasm. An older one
372
+ // runs without them only when they're the regular defaults, which it handled as before.
373
+ const { LEGACY_DEFAULTS } = require('./nativeSettings');
374
+ const given = Object.keys(LEGACY_DEFAULTS).filter(key => profile[key] !== undefined);
375
+ if (options.userAgentVerdict) {
376
+ // The app's User-Agent lists are matched here and passed per request.
377
+ const probe = await createRequestPipeline({});
378
+ const supported = typeof probe.native.supports === 'function' && probe.native.supports('user_agent_verdict');
379
+ probe.native.free();
380
+ if (!supported) throw new Error('userAgentVerdict needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
381
+ }
382
+ if (given.length) {
383
+ const probe = await createRequestPipeline({});
384
+ const supports = feature => typeof probe.native.supports === 'function' && probe.native.supports(feature);
385
+ const missing = given.filter(key => !supports(LEGACY_DEFAULTS[key][0]));
386
+ probe.native.free();
387
+ // An entry's third item adapts the profile for an older engine itself, saying whether it could.
388
+ const usable = key => (typeof LEGACY_DEFAULTS[key][2] === 'function' ? LEGACY_DEFAULTS[key][2](profile)
389
+ : LEGACY_DEFAULTS[key].length >= 2 && JSON.stringify(profile[key]) === JSON.stringify(LEGACY_DEFAULTS[key][1]));
390
+ // Chosen automatically, the native pipeline must answer exactly as the regular middleware
391
+ // would, so an engine missing any of these leaves the app on the regular middleware.
392
+ const unusable = options.exact ? missing : missing.filter(key => !usable(key));
393
+ if (unusable.length) {
394
+ throw new Error(`${unusable.join(', ')} need a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest`);
395
+ }
396
+ for (const key of missing) delete profile[key];
397
+ }
398
+ }
291
399
  if (stores) {
292
400
  // Checked before the profile is built, since older engines reject policy_store.
293
401
  const probe = await createRequestPipeline({});
@@ -317,6 +425,10 @@ module.exports = async function createNativeMiddleware(options = {}) {
317
425
  }
318
426
  let model = options.model;
319
427
  if (options.modelFile != null) model = await readModelFile(options.modelFile);
428
+ if (options.modelLoader != null) model = await loadedModel(options.modelLoader);
429
+ // The regular anomaly check uses its model only once there are AIWAF_MIN_AI_LOGS recent
430
+ // logs, counted when it starts.
431
+ if (model != null && typeof options.modelGate === 'function' && !(await options.modelGate())) model = null;
320
432
  try {
321
433
  engine = await createRequestPipeline(profile, model);
322
434
  } catch (error) {
@@ -361,11 +473,11 @@ module.exports = async function createNativeMiddleware(options = {}) {
361
473
  const pending = new Set();
362
474
  // Keywords and countries change rarely, so they're read at most every storeCacheSeconds.
363
475
  const cache = new Map();
364
- const cached = (name, load) => {
476
+ const cached = (name, load, item = String) => {
365
477
  const now = performance.now();
366
478
  const entry = cache.get(name);
367
479
  if (entry && now < entry.until) return entry.value;
368
- const value = Promise.resolve().then(load).then(items => [...(items || [])].map(String));
480
+ const value = Promise.resolve().then(load).then(items => [...(items || [])].map(item));
369
481
  cache.set(name, { until: now + storeCacheSeconds * 1000, value });
370
482
  // A failed read isn't kept, so the next request tries again.
371
483
  value.catch(() => { if (cache.get(name)?.value === value) cache.delete(name); });
@@ -378,6 +490,16 @@ module.exports = async function createNativeMiddleware(options = {}) {
378
490
  const stageOn = (route, name) => route.plan.shouldApply(name) && (!profile.enabled || profile.enabled.includes(name));
379
491
  // The host stores' facts for one request. A store read that fails is reported and treated
380
492
  // as not blocked, not exempt and nothing learned, so storage outages don't block traffic.
493
+ // Learned keywords not yet in the store, counted at once: the store write runs after the
494
+ // response, and the next request shouldn't wait for it or miss it.
495
+ const pendingLearned = new Map();
496
+ const activeKeywords = async () => {
497
+ if (typeof stores.keywordCounts !== 'function') return cached('keywords', () => stores.topKeywords(2000));
498
+ const counts = new Map(await cached('keywordCounts', () => stores.keywordCounts(2000),
499
+ ([keyword, count]) => [String(keyword), Number(count) || 0]));
500
+ for (const [keyword, pending] of pendingLearned) counts.set(keyword, (counts.get(keyword) || 0) + pending);
501
+ return [...counts].filter(([, count]) => count > Number(stores.activeAbove ?? 0)).map(([keyword]) => keyword);
502
+ };
381
503
  const storeFacts = async (req, route) => {
382
504
  const ip = clientIp(req);
383
505
  const rawPath = String(req.path || req.url || '/').split('?')[0];
@@ -389,7 +511,7 @@ module.exports = async function createNativeMiddleware(options = {}) {
389
511
  if (exempt) return { exempt: true };
390
512
  const [blocked, keywords, countries] = await Promise.all([
391
513
  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)), []) : [],
514
+ active.includes('ip_keyword_block') ? read(activeKeywords, []) : [],
393
515
  active.includes('geo_block') ? read(() => cached('countries', () => stores.blockedCountries()), []) : []
394
516
  ]);
395
517
  return { blocked: !!blocked, exempt: false, dynamic_keywords: keywords, geo_countries: countries };
@@ -407,6 +529,7 @@ module.exports = async function createNativeMiddleware(options = {}) {
407
529
  const window = Math.max(route.rate.window ?? profile.rate_window ?? 10, 1);
408
530
  return rateCounter.count(key, Date.now() / 1000, window);
409
531
  };
532
+ let logFailed = false;
410
533
  const report = error => { if (options.onError) options.onError(error); else console.error('AIWAF native finalization failed:', error.message); };
411
534
  // This pipeline takes no general settings, so these two come from the environment. Route
412
535
  // checks run in aiwaf-wasm, loaded here so requests can use them straight away.
@@ -436,24 +559,44 @@ module.exports = async function createNativeMiddleware(options = {}) {
436
559
  if (found && typeof found.then === 'function') found = found.then(exists => !!exists, () => null);
437
560
  else if (found !== null) found = !!found;
438
561
  }
562
+ if (regularLog && route.plan.shouldApply('logging')) regularLog.attach(req, res, { ip: clientIp(req) });
563
+ if (regularAnomaly) regularAnomaly.start(req);
564
+ let country = null;
565
+ if (options.countryLookup) {
566
+ try { country = options.countryLookup(req); } catch (error) { return next(error); }
567
+ if (country && typeof country.then === 'function') {
568
+ // A lookup that fails finds no country, as the regular geo check does.
569
+ country = country.then(value => { req[COUNTRY] = String(value || ''); }, () => { req[COUNTRY] = ''; });
570
+ } else {
571
+ req[COUNTRY] = String(country || '');
572
+ country = null;
573
+ }
574
+ }
439
575
  const counted = rateCounter && stageOn(route, 'rate_limit');
440
576
  const peek = !req[DEFER_BODY] && !req[PEEKED] && profile.sql_mode !== 'off' && stageOn(route, 'ip_keyword_block') && readable(req)
441
577
  ? 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])
578
+ if (!stores && !counted && !peek && !country && !(found && typeof found.then === 'function')) return handle(req, res, next, route, start, found, null);
579
+ return Promise.all([found, stores ? storeFacts(req, route) : null, peek, country])
444
580
  .then(async ([exists, facts]) => {
445
581
  if (counted) {
446
582
  let count;
447
583
  try { count = await rateCount(req, route, facts?.exempt); } catch (error) {
448
584
  report(error);
449
585
  // 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' });
586
+ if (rateFailureMode === 'closed') {
587
+ markBlocked(res, 'rate_cache_unavailable');
588
+ return res.status(503).json({ error: 'temporarily_unavailable' });
589
+ }
451
590
  }
452
591
  if (count !== undefined) facts = { ...(facts || {}), rate_count: count };
453
592
  }
454
593
  return handle(req, res, next, route, start, exists, facts);
455
594
  }, next);
456
595
  };
596
+ // Node.js's header check reads the protocol, which isn't a header, as server-protocol.
597
+ const requestHeaders = profile.header_policy === 'node'
598
+ ? req => (req.httpVersion ? { ...headers(req.headers), SERVER_PROTOCOL: `HTTP/${req.httpVersion}` } : headers(req.headers))
599
+ : req => headers(req.headers);
457
600
  const handle = (req, res, next, route, start, uuidExists, facts) => {
458
601
  if (closed) return next(new Error('Native pipeline is closed'));
459
602
  let decision;
@@ -462,19 +605,23 @@ module.exports = async function createNativeMiddleware(options = {}) {
462
605
  if (observeRisks && plan.shouldApply('ip_keyword_block')
463
606
  && (!profile.enabled || profile.enabled.includes('ip_keyword_block'))) {
464
607
  const riskFinding = observeRisks(req);
465
- if (riskFinding) return res.status(riskFinding.status).json({ error: riskFinding.rule });
608
+ if (riskFinding) {
609
+ markBlocked(res, riskFinding.rule);
610
+ return res.status(riskFinding.status).json({ error: riskFinding.rule });
611
+ }
466
612
  }
467
613
  const rawPath = String(req.path || req.url || '/').split('?')[0];
468
614
  const body = req[DEFER_BODY] ? {body:null,exhausted:false} : safeBody(req, maxBytes);
469
615
  decision = JSON.parse(native.begin(JSON.stringify({
470
616
  ip: clientIp(req),
471
- path: rawPath, method: String(req.method || 'GET'), headers: headers(req.headers),
617
+ path: rawPath, method: String(req.method || 'GET'), headers: requestHeaders(req),
472
618
  query: String(req.originalUrl || req.url || '').split('?').slice(1).join('?'),
473
619
  body: body.body, parsed_query: req.query ?? null,
474
- now: Date.now() / 1000, country: String(synchronous(options.countryLookup, req, '') || ''),
620
+ now: Date.now() / 1000, country: req[COUNTRY] ?? '',
475
621
  authenticated: req[DEFER_BODY] ? false : !!synchronous(options.authenticated, req, false),
476
622
  exists: !!synchronous(options.routeExists, req, !!req.route), disabled,
477
623
  payload_exhausted: body.exhausted, defer_body: !!req[DEFER_BODY],
624
+ ...(options.userAgentVerdict ? { user_agent_verdict: options.userAgentVerdict(req.headers?.['user-agent']) } : {}),
478
625
  ...(Object.keys(rate).length ? { rate } : {}),
479
626
  ...(uuidExists === null ? {} : { uuid_exists: uuidExists }),
480
627
  ...(facts || {})
@@ -491,24 +638,53 @@ module.exports = async function createNativeMiddleware(options = {}) {
491
638
  const effects = JSON.parse(native.finish(decision.context, aborted ? 499 : res.statusCode || 200, performance.now() - start, Date.now() / 1000));
492
639
  if (blocks && effects.block_csv) blocks.append(effects.block_csv);
493
640
  if (keywords && effects.keyword_csv) keywords.append(effects.keyword_csv);
494
- if (log && effects.log_csv) log.append(effects.log_csv);
495
- if (stores) writeEffects(effects);
641
+ if (log && effects.log_csv) {
642
+ // A request log that can't be written (a full disk, say) is reported once, not per request.
643
+ try { log.append(effects.log_csv); } catch (error) { if (!logFailed) { logFailed = true; report(error); } }
644
+ }
645
+ if (stores) writeEffects(effects, req);
496
646
  } catch (error) { report(error); }
497
647
  };
498
648
  res.on('finish', () => finalize(false));
499
649
  res.on('close', () => finalize(true));
500
- if (decision.status) return res.status(decision.status).json({ error: decision.reason });
650
+ if (decision.status) {
651
+ markBlocked(res, decision.reason, decision.reason === 'geo_block' ? req[COUNTRY] ?? '' : '');
652
+ return res.status(decision.status).json({ error: decision.reason });
653
+ }
654
+ if (regularAnomaly && route.plan.shouldApply('ai_anomaly')) {
655
+ const ip = clientIp(req);
656
+ return regularAnomaly.check(req, ip).then(reason => {
657
+ if (!reason) return next();
658
+ if (stores) {
659
+ blockedIps.set(ip, true);
660
+ Promise.resolve().then(() => stores.block(ip, reason, undefined, req)).catch(report);
661
+ }
662
+ markBlocked(res, 'anomaly');
663
+ return res.status(403).json({ error: 'blocked' });
664
+ }, next);
665
+ }
501
666
  return next();
502
667
  };
503
668
  // Store writes run after the response, so a slow or failing store never delays it.
504
- const writeEffects = effects => {
669
+ const writeEffects = (effects, req) => {
505
670
  if (effects.block) {
506
671
  blockedIps.set(effects.block.ip, true);
507
- Promise.resolve().then(() => stores.block(effects.block.ip, effects.block.reason, effects.block.expires_at)).catch(report);
672
+ Promise.resolve().then(() => stores.block(effects.block.ip, effects.block.reason, effects.block.expires_at, req)).catch(report);
508
673
  }
509
- if (effects.keyword) {
510
- Promise.resolve().then(() => stores.learn(effects.keyword))
511
- .then(() => cache.delete('keywords'), report);
674
+ // Node.js's learning rule reports every learned segment; the native rule, one keyword.
675
+ const learned = effects.keywords && effects.keywords.length ? effects.keywords : (effects.keyword ? [effects.keyword] : []);
676
+ for (const keyword of learned) pendingLearned.set(keyword, (pendingLearned.get(keyword) || 0) + 1);
677
+ if (learned.length) {
678
+ Promise.resolve().then(async () => { for (const keyword of learned) await stores.learn(keyword); })
679
+ .finally(() => {
680
+ // Written (or failed): the store's own count takes over.
681
+ for (const keyword of learned) {
682
+ const left = (pendingLearned.get(keyword) || 0) - 1;
683
+ if (left > 0) pendingLearned.set(keyword, left); else pendingLearned.delete(keyword);
684
+ }
685
+ cache.delete('keywords');
686
+ cache.delete('keywordCounts');
687
+ }).catch(report);
512
688
  }
513
689
  };
514
690
  middleware.inspectPayload = req => {
@@ -537,4 +713,5 @@ module.exports = async function createNativeMiddleware(options = {}) {
537
713
  module.exports.DEFER_BODY = DEFER_BODY;
538
714
  module.exports.regularStores = regularStores;
539
715
  module.exports.recentAnswers = recentAnswers;
716
+ module.exports.rateOverrides = rateOverrides;
540
717
  module.exports.redisRateCounter = require('./nativeRateCounter').redisRateCounter;