aiwaf 1.2.2 → 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,6 +313,17 @@ 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 || {}));
@@ -298,6 +367,35 @@ module.exports = async function createNativeMiddleware(options = {}) {
298
367
  rateCounter = null;
299
368
  } else if (!supported) throw new Error('rateCounter needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
300
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
+ }
301
399
  if (stores) {
302
400
  // Checked before the profile is built, since older engines reject policy_store.
303
401
  const probe = await createRequestPipeline({});
@@ -327,6 +425,10 @@ module.exports = async function createNativeMiddleware(options = {}) {
327
425
  }
328
426
  let model = options.model;
329
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;
330
432
  try {
331
433
  engine = await createRequestPipeline(profile, model);
332
434
  } catch (error) {
@@ -371,11 +473,11 @@ module.exports = async function createNativeMiddleware(options = {}) {
371
473
  const pending = new Set();
372
474
  // Keywords and countries change rarely, so they're read at most every storeCacheSeconds.
373
475
  const cache = new Map();
374
- const cached = (name, load) => {
476
+ const cached = (name, load, item = String) => {
375
477
  const now = performance.now();
376
478
  const entry = cache.get(name);
377
479
  if (entry && now < entry.until) return entry.value;
378
- const value = Promise.resolve().then(load).then(items => [...(items || [])].map(String));
480
+ const value = Promise.resolve().then(load).then(items => [...(items || [])].map(item));
379
481
  cache.set(name, { until: now + storeCacheSeconds * 1000, value });
380
482
  // A failed read isn't kept, so the next request tries again.
381
483
  value.catch(() => { if (cache.get(name)?.value === value) cache.delete(name); });
@@ -388,6 +490,16 @@ module.exports = async function createNativeMiddleware(options = {}) {
388
490
  const stageOn = (route, name) => route.plan.shouldApply(name) && (!profile.enabled || profile.enabled.includes(name));
389
491
  // The host stores' facts for one request. A store read that fails is reported and treated
390
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
+ };
391
503
  const storeFacts = async (req, route) => {
392
504
  const ip = clientIp(req);
393
505
  const rawPath = String(req.path || req.url || '/').split('?')[0];
@@ -399,7 +511,7 @@ module.exports = async function createNativeMiddleware(options = {}) {
399
511
  if (exempt) return { exempt: true };
400
512
  const [blocked, keywords, countries] = await Promise.all([
401
513
  active.includes('ip_keyword_block') || active.includes('ai_anomaly') ? read(() => blockedIps.get(ip, () => stores.isBlocked(ip)), false) : false,
402
- active.includes('ip_keyword_block') ? read(() => cached('keywords', () => stores.topKeywords(2000)), []) : [],
514
+ active.includes('ip_keyword_block') ? read(activeKeywords, []) : [],
403
515
  active.includes('geo_block') ? read(() => cached('countries', () => stores.blockedCountries()), []) : []
404
516
  ]);
405
517
  return { blocked: !!blocked, exempt: false, dynamic_keywords: keywords, geo_countries: countries };
@@ -417,6 +529,7 @@ module.exports = async function createNativeMiddleware(options = {}) {
417
529
  const window = Math.max(route.rate.window ?? profile.rate_window ?? 10, 1);
418
530
  return rateCounter.count(key, Date.now() / 1000, window);
419
531
  };
532
+ let logFailed = false;
420
533
  const report = error => { if (options.onError) options.onError(error); else console.error('AIWAF native finalization failed:', error.message); };
421
534
  // This pipeline takes no general settings, so these two come from the environment. Route
422
535
  // checks run in aiwaf-wasm, loaded here so requests can use them straight away.
@@ -446,24 +559,44 @@ module.exports = async function createNativeMiddleware(options = {}) {
446
559
  if (found && typeof found.then === 'function') found = found.then(exists => !!exists, () => null);
447
560
  else if (found !== null) found = !!found;
448
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
+ }
449
575
  const counted = rateCounter && stageOn(route, 'rate_limit');
450
576
  const peek = !req[DEFER_BODY] && !req[PEEKED] && profile.sql_mode !== 'off' && stageOn(route, 'ip_keyword_block') && readable(req)
451
577
  ? peekBody(req, maxBytes).then(prefix => { req[PEEKED] = prefix; }) : null;
452
- if (!stores && !counted && !peek && !(found && typeof found.then === 'function')) return handle(req, res, next, route, start, found, null);
453
- 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])
454
580
  .then(async ([exists, facts]) => {
455
581
  if (counted) {
456
582
  let count;
457
583
  try { count = await rateCount(req, route, facts?.exempt); } catch (error) {
458
584
  report(error);
459
585
  // As the regular rate limiter does: closed answers 503, open lets the request through.
460
- 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
+ }
461
590
  }
462
591
  if (count !== undefined) facts = { ...(facts || {}), rate_count: count };
463
592
  }
464
593
  return handle(req, res, next, route, start, exists, facts);
465
594
  }, next);
466
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);
467
600
  const handle = (req, res, next, route, start, uuidExists, facts) => {
468
601
  if (closed) return next(new Error('Native pipeline is closed'));
469
602
  let decision;
@@ -472,19 +605,23 @@ module.exports = async function createNativeMiddleware(options = {}) {
472
605
  if (observeRisks && plan.shouldApply('ip_keyword_block')
473
606
  && (!profile.enabled || profile.enabled.includes('ip_keyword_block'))) {
474
607
  const riskFinding = observeRisks(req);
475
- 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
+ }
476
612
  }
477
613
  const rawPath = String(req.path || req.url || '/').split('?')[0];
478
614
  const body = req[DEFER_BODY] ? {body:null,exhausted:false} : safeBody(req, maxBytes);
479
615
  decision = JSON.parse(native.begin(JSON.stringify({
480
616
  ip: clientIp(req),
481
- path: rawPath, method: String(req.method || 'GET'), headers: headers(req.headers),
617
+ path: rawPath, method: String(req.method || 'GET'), headers: requestHeaders(req),
482
618
  query: String(req.originalUrl || req.url || '').split('?').slice(1).join('?'),
483
619
  body: body.body, parsed_query: req.query ?? null,
484
- now: Date.now() / 1000, country: String(synchronous(options.countryLookup, req, '') || ''),
620
+ now: Date.now() / 1000, country: req[COUNTRY] ?? '',
485
621
  authenticated: req[DEFER_BODY] ? false : !!synchronous(options.authenticated, req, false),
486
622
  exists: !!synchronous(options.routeExists, req, !!req.route), disabled,
487
623
  payload_exhausted: body.exhausted, defer_body: !!req[DEFER_BODY],
624
+ ...(options.userAgentVerdict ? { user_agent_verdict: options.userAgentVerdict(req.headers?.['user-agent']) } : {}),
488
625
  ...(Object.keys(rate).length ? { rate } : {}),
489
626
  ...(uuidExists === null ? {} : { uuid_exists: uuidExists }),
490
627
  ...(facts || {})
@@ -501,24 +638,53 @@ module.exports = async function createNativeMiddleware(options = {}) {
501
638
  const effects = JSON.parse(native.finish(decision.context, aborted ? 499 : res.statusCode || 200, performance.now() - start, Date.now() / 1000));
502
639
  if (blocks && effects.block_csv) blocks.append(effects.block_csv);
503
640
  if (keywords && effects.keyword_csv) keywords.append(effects.keyword_csv);
504
- if (log && effects.log_csv) log.append(effects.log_csv);
505
- 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);
506
646
  } catch (error) { report(error); }
507
647
  };
508
648
  res.on('finish', () => finalize(false));
509
649
  res.on('close', () => finalize(true));
510
- 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
+ }
511
666
  return next();
512
667
  };
513
668
  // Store writes run after the response, so a slow or failing store never delays it.
514
- const writeEffects = effects => {
669
+ const writeEffects = (effects, req) => {
515
670
  if (effects.block) {
516
671
  blockedIps.set(effects.block.ip, true);
517
- 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);
518
673
  }
519
- if (effects.keyword) {
520
- Promise.resolve().then(() => stores.learn(effects.keyword))
521
- .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);
522
688
  }
523
689
  };
524
690
  middleware.inspectPayload = req => {
@@ -57,35 +57,45 @@ function settingsModel(opts) {
57
57
  } catch (_) { return { kind: 'unreadable', file }; }
58
58
  }
59
59
 
60
+ // Profile values an older aiwaf-wasm can't take, with the feature that adds them and the value
61
+ // the converter writes for the regular defaults. An older engine runs without them only then,
62
+ // keeping the behavior it always had.
63
+ // The regular header check skips these, unless AIWAF_STATIC_EXTENSIONS or AIWAF_STATIC_PATHS
64
+ // replace them (js/lib/headerValidation.js).
65
+ const REGULAR_STATIC_EXTENSIONS = ['.css', '.js', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg', '.woff', '.woff2', '.ttf'];
66
+ const REGULAR_STATIC_PATHS = ['/static/', '/media/', '/assets/', '/favicon.ico'];
67
+ const LEGACY_DEFAULTS = {
68
+ header_bytes_without_prefix: ['header_limits', true],
69
+ blocked_user_agents: ['header_limits', normalizeSettings({}).AIWAF_BLOCKED_USER_AGENTS.map(agent => String(agent).toLowerCase())],
70
+ login_prefixes: ['login_prefixes', [].concat(normalizeSettings({}).AIWAF_LOGIN_PATH_PREFIXES || [])],
71
+ header_max_bytes: ['header_limits'],
72
+ header_max_count: ['header_limits'],
73
+ header_max_user_agent: ['header_limits'],
74
+ header_max_accept: ['header_limits'],
75
+ exempt_keywords: ['keyword_exemptions'],
76
+ allowed_path_keywords: ['keyword_exemptions'],
77
+ post_only_suffixes: ['post_only_suffixes'],
78
+ required_headers_by_method: ['method_headers'],
79
+ // An older engine checks headers its own way when on, and not at all when off.
80
+ header_policy: ['header_policy', 'node', profile => {
81
+ if (profile.header_policy !== 'node_ua') return profile.header_policy === 'node';
82
+ profile.enabled = (profile.enabled || []).filter(stage => stage !== 'header_validation');
83
+ return true;
84
+ }],
85
+ header_skip_extensions: ['header_policy', REGULAR_STATIC_EXTENSIONS],
86
+ header_skip_paths: ['header_policy', REGULAR_STATIC_PATHS],
87
+ header_wasm_check: ['header_policy', true],
88
+ learn_context: ['learn_context', 'node'],
89
+ learn_scan_patterns: ['learn_context', [...require('./trainingLogic').SCANNING_PATTERNS]],
90
+ learn_static_keywords: ['learn_context', [...require('./featureUtils').STATIC_KW]],
91
+ suspicious_user_agents: ['user_agent_lists'],
92
+ legitimate_bots: ['user_agent_lists']
93
+ };
60
94
  const STAGES = ['geo_block', 'ip_keyword_block', 'rate_limit', 'ai_anomaly', 'honeypot', 'uuid_tamper', 'header_validation', 'logging'];
61
95
  const PATTERN = /[*?[]/;
62
96
  // Options with no native equivalent, reported when they differ from the regular defaults.
63
97
  const NOT_CARRIED = {
64
- AIWAF_ALLOWED_PATH_KEYWORDS: 'The native pipeline has its own legitimate_keywords list.',
65
- AIWAF_EXEMPT_KEYWORDS: 'The native pipeline has no exempt keywords.',
66
- AIWAF_LOGIN_PATH_PREFIXES: 'The native pipeline treats paths under /login and /admin/login as login forms.',
67
- AIWAF_POST_ONLY_SUFFIXES: 'The native method policy is allowed_methods only.',
68
- AIWAF_MAX_HEADER_BYTES: 'The native header limits are fixed.',
69
- AIWAF_MAX_HEADER_COUNT: 'The native header limits are fixed.',
70
- AIWAF_MAX_USER_AGENT_LENGTH: 'The native header limits are fixed.',
71
- AIWAF_MAX_ACCEPT_LENGTH: 'The native header limits are fixed.',
72
- AIWAF_BLOCKED_USER_AGENTS: 'The native header check has its own list of scanner user agents.',
73
- AIWAF_GEO_MMDB_PATH: 'Pass a countryLookup(req) option to the native pipeline instead.',
74
- AIWAF_GEO_CACHE_SECONDS: 'Country lookups come from countryLookup(req).',
75
- AIWAF_GEO_CACHE_PREFIX: 'Country lookups come from countryLookup(req).',
76
- AIWAF_MODEL_STORAGE: 'The native pipeline loads a model from a file only; pass a model option instead.',
77
- AIWAF_MODEL_STORAGE_FALLBACK: 'The native pipeline loads a model from a file only; pass a model option instead.',
78
- AIWAF_MODEL_CACHE_KEY: 'Pass a model option to the native pipeline instead.',
79
- AIWAF_MODEL_CACHE_TTL: 'Pass a model option to the native pipeline instead.',
80
- AIWAF_MIDDLEWARE_LOG_PATH: 'Native logs go to logPath, by default native_requests.csv in dataDir.',
81
- AIWAF_MIDDLEWARE_LOG_DB: 'The native pipeline logs to a CSV file only.',
82
- AIWAF_MIDDLEWARE_LOG_CSV: 'The native pipeline logs to a CSV file only.',
83
- AIWAF_MIDDLEWARE_LOG_CSV_PATH: 'Native logs go to logPath, by default native_requests.csv in dataDir.',
84
- AIWAF_CAPTURE_EXTENDED_REQUEST_INFO: 'The native log has fixed columns.',
85
- AIWAF_EXTENDED_INFO_MAX_HEADERS: 'The native log has fixed columns.',
86
- AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH: 'The native log has fixed columns.',
87
98
  AIWAF_DYNAMIC_KEYWORDS_DB: 'The native pipeline reads learned keywords from the keyword store.',
88
- AIWAF_MIN_AI_LOGS: 'Training settings don\'t apply to request handling.',
89
99
  AIWAF_ROUTE_PLAN_VERSION: 'The native pipeline compiles path rules once at startup.',
90
100
  AIWAF_FORCE_JSON_ERRORS: 'Native responses are always JSON.'
91
101
  };
@@ -96,7 +106,14 @@ const CARRIED = ['WINDOW_SEC', 'MAX_REQ', 'FLOOD_REQ', 'AIWAF_MIN_FORM_TIME', 'A
96
106
  'AIWAF_GEO_BLOCK_ENABLED', 'AIWAF_GEO_ALLOW_COUNTRIES', 'AIWAF_GEO_BLOCK_COUNTRIES', 'AIWAF_HEADER_VALIDATION',
97
107
  'AIWAF_REQUIRED_HEADERS', 'AIWAF_HEADER_QUALITY_MIN_SCORE', 'AIWAF_EXEMPT_PATHS', 'AIWAF_EXEMPT_IPS',
98
108
  'AIWAF_MIDDLEWARES', 'AIWAF_DISABLE_MIDDLEWARES', 'AIWAF_MIDDLEWARE_LOGGING', 'AIWAF_PATH_RULES',
99
- 'AIWAF_PATH_MANIFEST', 'AIWAF_INJECTION_RISK_MODE', 'dynamicTopN', 'AIWAF_EXEMPTIONS_DB', 'AIWAF_TRUSTED_PROXIES'];
109
+ 'AIWAF_PATH_MANIFEST', 'AIWAF_INJECTION_RISK_MODE', 'dynamicTopN', 'AIWAF_EXEMPTIONS_DB', 'AIWAF_TRUSTED_PROXIES',
110
+ 'AIWAF_GEO_MMDB_PATH', 'AIWAF_GEO_CACHE_SECONDS', 'AIWAF_GEO_CACHE_PREFIX', 'AIWAF_LOGIN_PATH_PREFIXES',
111
+ 'AIWAF_MAX_HEADER_BYTES', 'AIWAF_MAX_HEADER_COUNT', 'AIWAF_MAX_USER_AGENT_LENGTH', 'AIWAF_MAX_ACCEPT_LENGTH',
112
+ 'AIWAF_BLOCKED_USER_AGENTS', 'AIWAF_ALLOWED_PATH_KEYWORDS', 'AIWAF_EXEMPT_KEYWORDS', 'AIWAF_POST_ONLY_SUFFIXES',
113
+ 'AIWAF_MODEL_STORAGE', 'AIWAF_MODEL_STORAGE_FALLBACK', 'AIWAF_MODEL_CACHE_KEY', 'AIWAF_MODEL_CACHE_TTL',
114
+ 'AIWAF_MIDDLEWARE_LOG_PATH', 'AIWAF_MIDDLEWARE_LOG_DB', 'AIWAF_MIDDLEWARE_LOG_CSV', 'AIWAF_MIDDLEWARE_LOG_CSV_PATH',
115
+ 'AIWAF_CAPTURE_EXTENDED_REQUEST_INFO', 'AIWAF_EXTENDED_INFO_MAX_HEADERS', 'AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH',
116
+ 'AIWAF_MIN_AI_LOGS'];
100
117
  // Where settingsCompat reads each number from, in the same order, so unreadable values can be reported.
101
118
  const NUMBER_SOURCES = {
102
119
  WINDOW_SEC: ['WINDOW_SEC', 'windowSec', 'AIWAF_WINDOW_SECONDS', 'env:AIWAF_RATE_WINDOW'],
@@ -148,6 +165,16 @@ function nativeOptionsFromSettings(rawOpts = {}) {
148
165
  profile.honeypot_field = opts.HONEYPOT_FIELD ? String(opts.HONEYPOT_FIELD) : '';
149
166
  profile.allowed_methods = opts.AIWAF_METHOD_POLICY_ENABLED === true
150
167
  ? (opts.AIWAF_ALLOWED_METHODS || []).map(method => String(method).toUpperCase()) : [];
168
+ // With the method policy, a GET to a post-only path is refused. The regular check lowercases
169
+ // the path, so a suffix with capitals never matches there.
170
+ const postOnly = opts.AIWAF_METHOD_POLICY_ENABLED === true
171
+ ? [].concat(opts.AIWAF_POST_ONLY_SUFFIXES || []).map(String).filter(suffix => suffix === suffix.toLowerCase()) : [];
172
+ if (postOnly.length) profile.post_only_suffixes = postOnly;
173
+ // A keyword exempt by name, or any keyword on a path with an allowed fragment, doesn't block.
174
+ for (const [key, setting] of [['exempt_keywords', 'AIWAF_EXEMPT_KEYWORDS'], ['allowed_path_keywords', 'AIWAF_ALLOWED_PATH_KEYWORDS']]) {
175
+ const values = [].concat(opts[setting] || []).map(value => String(value).toLowerCase());
176
+ if (values.length) profile[key] = values;
177
+ }
151
178
  const list = (value, setting) => {
152
179
  if (value == null) return [];
153
180
  if (Array.isArray(value)) return value.map(String);
@@ -164,15 +191,51 @@ function nativeOptionsFromSettings(rawOpts = {}) {
164
191
  }
165
192
  const required = opts.AIWAF_REQUIRED_HEADERS || [];
166
193
  if (required && typeof required === 'object' && !Array.isArray(required)) {
167
- profile.required_headers = (required.DEFAULT || []).map(headerName);
168
- note('AIWAF_REQUIRED_HEADERS', 'changed', 'Per-method lists aren\'t supported natively, so its DEFAULT list applies to every method.');
194
+ // Per method, falling back to DEFAULT, as the regular check reads them. It looks a method
195
+ // up as uppercase, so a lowercase key never applies there.
196
+ profile.required_headers = [].concat(required.DEFAULT || []).map(headerName);
197
+ const byMethod = Object.entries(required).filter(([method, list]) => method !== 'DEFAULT'
198
+ && method === method.toUpperCase() && list);
199
+ if (byMethod.length) {
200
+ profile.required_headers_by_method = Object.fromEntries(byMethod.map(([method, list]) => [method, [].concat(list).map(headerName)]));
201
+ }
169
202
  } else {
170
203
  profile.required_headers = [].concat(required).map(headerName);
171
204
  }
205
+ // The header caps, blocked user agents and login forms the regular checks use. A newer
206
+ // aiwaf-wasm takes them; an older one keeps its own, which the adapter allows only when these
207
+ // are the regular defaults (see LEGACY_DEFAULTS).
208
+ for (const [key, setting] of [['header_max_bytes', 'AIWAF_MAX_HEADER_BYTES'], ['header_max_count', 'AIWAF_MAX_HEADER_COUNT'],
209
+ ['header_max_user_agent', 'AIWAF_MAX_USER_AGENT_LENGTH'], ['header_max_accept', 'AIWAF_MAX_ACCEPT_LENGTH']]) {
210
+ if (same(opts[setting], defaults[setting])) continue;
211
+ if (Number.isInteger(opts[setting]) && opts[setting] >= 0) profile[key] = opts[setting];
212
+ else note(setting, 'not carried', 'The native header caps are whole numbers of zero or more, so the native default applies.');
213
+ }
214
+ // Node.js counts header names as sent (user-agent), without Python's HTTP_.
215
+ profile.header_bytes_without_prefix = true;
216
+ // Keywords are learned from 404s as the regular middleware learns them.
217
+ profile.learn_context = 'node';
218
+ profile.learn_scan_patterns = [...require('./trainingLogic').SCANNING_PATTERNS];
219
+ profile.learn_static_keywords = [...require('./featureUtils').STATIC_KW];
220
+ // Node.js's own header check, then aiwaf-wasm's, as the regular middleware runs them.
221
+ const wasmHeaderCheck = rawOpts.AIWAF_WASM_VALIDATION !== false && rawOpts.AIWAF_WASM_HEADER_VALIDATION !== false;
222
+ profile.header_policy = opts.AIWAF_HEADER_VALIDATION ? 'node' : 'node_ua';
223
+ profile.header_skip_extensions = [].concat(rawOpts.AIWAF_STATIC_EXTENSIONS || REGULAR_STATIC_EXTENSIONS).map(value => String(value).toLowerCase());
224
+ profile.header_skip_paths = [].concat(rawOpts.AIWAF_STATIC_PATHS || REGULAR_STATIC_PATHS).map(value => String(value).toLowerCase());
225
+ profile.header_wasm_check = wasmHeaderCheck;
226
+ // The app's own User-Agent lists are tested by the adapter, in JavaScript, exactly as the
227
+ // regular check tests them; the engine takes the verdict.
228
+ const ownAgentLists = ['AIWAF_SUSPICIOUS_USER_AGENTS', 'AIWAF_LEGITIMATE_BOTS'].filter(setting => Array.isArray(rawOpts[setting]));
229
+ for (const setting of ownAgentLists) note(setting, 'carried');
230
+ const userAgentVerdict = ownAgentLists.length ? require('./headerValidation').userAgentVerdict(opts) : null;
231
+ profile.blocked_user_agents = [].concat(opts.AIWAF_BLOCKED_USER_AGENTS || []).map(agent => String(agent).toLowerCase());
232
+ // The regular check lowercases the path, so a prefix with capitals never matches there.
233
+ profile.login_prefixes = [].concat(opts.AIWAF_LOGIN_PATH_PREFIXES || []).map(String)
234
+ .filter(prefix => prefix === prefix.toLowerCase());
172
235
  // With no required headers, the regular check also skips the quality score.
173
236
  // Scores are whole numbers, so a fractional minimum is the next whole one.
174
237
  const minScore = Number(opts.AIWAF_HEADER_QUALITY_MIN_SCORE);
175
- if (!profile.required_headers.length) profile.header_min_score = 0;
238
+ if (!profile.required_headers.length && !profile.required_headers_by_method) profile.header_min_score = 0;
176
239
  else if (Number.isFinite(minScore) && Math.abs(minScore) < 2 ** 31) profile.header_min_score = Math.ceil(minScore);
177
240
  else note('AIWAF_HEADER_QUALITY_MIN_SCORE', 'not carried', 'It isn\'t a usable score, so the native default applies.');
178
241
  profile.sql_mode = String(rawOpts.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').trim().toLowerCase();
@@ -205,18 +268,25 @@ function nativeOptionsFromSettings(rawOpts = {}) {
205
268
  const auto = isAutoSelection(requested);
206
269
  const explicit = key => Object.hasOwn(rawOpts, key) || process.env[key] !== undefined;
207
270
  const logging = opts.AIWAF_MIDDLEWARE_LOGGING || (auto && enabled.has('logging') && !explicit('AIWAF_MIDDLEWARE_LOGGING'));
208
- if (!opts.AIWAF_HEADER_VALIDATION) enabled.delete('header_validation');
271
+ // With AIWAF_HEADER_VALIDATION off, the regular middleware still runs aiwaf-wasm's User-Agent
272
+ // check where the header stage applies, unless its aiwaf-wasm checks are off too.
273
+ if (!opts.AIWAF_HEADER_VALIDATION && !wasmHeaderCheck) enabled.delete('header_validation');
209
274
  if (!logging) enabled.delete('logging');
210
275
  profile.enabled = STAGES.filter(stage => enabled.has(stage));
211
- if (enabled.has('logging')) {
212
- note('AIWAF_MIDDLEWARE_LOGGING', 'changed', 'Requests are logged to native_requests.csv in dataDir, with the native log\'s columns.');
213
- }
276
+ // Requests are logged by the regular request logger, beside the native pipeline, to the same
277
+ // JSONL, CSV or database log, with the same columns.
278
+ const regularLog = enabled.has('logging');
279
+ if (regularLog) profile.enabled = profile.enabled.filter(stage => stage !== 'logging');
214
280
  // The regular middleware's stores: the same blocks, exemptions, learned keywords and blocked
215
281
  // countries. An older aiwaf-wasm can't use them, and then the adapter keeps its own in dataDir.
216
282
  note('stores', 'carried');
217
283
 
218
284
  const options = {
219
- stores: regularStores({ dynamicTopN: opts.dynamicTopN, exemptionsDb: opts.AIWAF_EXEMPTIONS_DB }),
285
+ stores: regularStores({ dynamicTopN: opts.dynamicTopN, exemptionsDb: opts.AIWAF_EXEMPTIONS_DB, extendedInfo: {
286
+ enabled: opts.AIWAF_CAPTURE_EXTENDED_REQUEST_INFO,
287
+ maxHeaders: opts.AIWAF_EXTENDED_INFO_MAX_HEADERS,
288
+ maxValueLength: opts.AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH
289
+ } }),
220
290
  storesFallback: 'csv',
221
291
  rateFailureMode: opts.AIWAF_RATE_CACHE_FAILURE_MODE,
222
292
  // Resolved as the regular middleware resolves it, with its default trusted proxies.
@@ -233,6 +303,12 @@ function nativeOptionsFromSettings(rawOpts = {}) {
233
303
  note('AIWAF_INJECTION_RISK_MODE', 'not carried', 'It must be block, log or off, so the native default applies.');
234
304
  }
235
305
  }
306
+ if (profile.enabled.includes('geo_block')) {
307
+ // Countries come from where the regular geo check finds them: its geoResolver, which the
308
+ // request waits for, or else the MMDB database, then the x-country-code header.
309
+ options.countryLookup = require('./geoBlocker').createCountryLookup(opts, options.trustedProxies, rawOpts.geoResolver);
310
+ if (typeof rawOpts.geoResolver === 'function') note('geoResolver', 'carried');
311
+ }
236
312
  // The regular UUID check matches one segment under uuidRoutePrefix, and asks uuidResolver.
237
313
  const uuidPrefix = rawOpts.uuidRoutePrefix || '/user';
238
314
  profile.uuid_prefix = `${String(uuidPrefix).replace(/\/+$/, '')}/`;
@@ -252,15 +328,17 @@ function nativeOptionsFromSettings(rawOpts = {}) {
252
328
  note('cache', 'not carried', 'Shared native rate limits need a node-redis or ioredis client, so rate limits are counted in each worker.');
253
329
  }
254
330
  if (opts.AIWAF_RATE_CACHE_FAILURE_MODE !== 'closed') note('AIWAF_RATE_CACHE_FAILURE_MODE', 'carried');
255
- const model = settingsModel(opts);
256
- if (model.kind === 'wasm') {
257
- options.modelFile = model.file;
258
- note('AIWAF_MODEL_PATH', 'carried');
259
- } else if (model.kind === 'js' || model.kind === 'unreadable') {
260
- note('AIWAF_MODEL_PATH', 'not carried', `${model.file} is in an older model format the native pipeline can't load. Retrain with: aiwaf train`);
261
- } else if (model.kind === 'none' && opts.AIWAF_MODEL_PATH) {
262
- note('AIWAF_MODEL_PATH', 'carried', 'No model file exists there yet, so anomaly detection runs without a model, as in the regular middleware.');
331
+ if (regularLog) options.regularLog = { ...opts, AIWAF_MIDDLEWARE_LOGGING: true };
332
+ if (userAgentVerdict) options.userAgentVerdict = userAgentVerdict;
333
+ // Anomalies are checked by the regular anomaly check, after the engine's stages, with the
334
+ // regular model, wherever the app keeps it and in whatever format.
335
+ const regularAnomaly = profile.enabled.includes('ai_anomaly');
336
+ if (regularAnomaly) {
337
+ options.regularAnomaly = opts;
338
+ profile.enabled = profile.enabled.filter(stage => stage !== 'ai_anomaly');
263
339
  }
340
+ // The regular anomaly check loads the model itself; without that stage no model is used.
341
+ if (opts.AIWAF_MODEL_PATH) note('AIWAF_MODEL_PATH', 'carried');
264
342
  for (const [key, reason] of Object.entries(NOT_CARRIED)) {
265
343
  if (!same(opts[key], defaults[key])) note(key, 'not carried', reason);
266
344
  }
@@ -303,4 +381,4 @@ function nativeOptionsFromSettings(rawOpts = {}) {
303
381
  };
304
382
  }
305
383
 
306
- module.exports = { nativeOptionsFromSettings, settingsModel, SHIPPED_MODEL_SHA256 };
384
+ module.exports = { nativeOptionsFromSettings, settingsModel, SHIPPED_MODEL_SHA256, LEGACY_DEFAULTS };
package/lib/pathRules.js CHANGED
@@ -37,11 +37,18 @@ function normalizePaths(items = []) {
37
37
  return (items || []).map(item => normalizePath(item, false));
38
38
  }
39
39
 
40
+ // Patterns come from configuration, so each is compiled once.
41
+ const compiledWildcards = new Map();
40
42
  function wildcardMatch(pathValue, pattern) {
41
- const escaped = String(pattern)
42
- .replace(/[.+?^${}()|[\]\\]/g, '\\$&')
43
- .replace(/\*/g, '.*');
44
- return new RegExp(`^${escaped}$`).test(pathValue);
43
+ const key = String(pattern);
44
+ let regex = compiledWildcards.get(key);
45
+ if (!regex) {
46
+ const escaped = key.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
47
+ regex = new RegExp(`^${escaped}$`);
48
+ if (compiledWildcards.size >= 1024) compiledWildcards.clear();
49
+ compiledWildcards.set(key, regex);
50
+ }
51
+ return regex.test(pathValue);
45
52
  }
46
53
 
47
54
  function isPathExempt(pathValue, exemptPaths = [], { allowWildcards = true, allowPrefix = true } = {}) {
@@ -101,7 +108,25 @@ function isMiddlewareDisabledForPath(path, rules, middlewareName) {
101
108
  return disabled.some(entry => normalizeMiddlewareName(entry) === target);
102
109
  }
103
110
 
111
+ // Path rules and route markers are fixed once the app runs, so a plan is built once per path
112
+ // and markers, for each rules list. Plans are only read, and getOverrides returns copies.
113
+ const planCaches = new WeakMap();
104
114
  function createRoutePlan(path, rules = [], context = {}) {
115
+ if (!Array.isArray(rules)) return buildRoutePlan(path, rules, context);
116
+ const key = [path, rules.length, context.fullyExempt ? 1 : 0, (context.exemptMiddlewares || []).join(','),
117
+ (context.requiredMiddlewares || []).join(',')].join('\u0000');
118
+ let plans = planCaches.get(rules);
119
+ if (!plans) planCaches.set(rules, plans = new Map());
120
+ let plan = plans.get(key);
121
+ if (!plan) {
122
+ plan = buildRoutePlan(path, rules, context);
123
+ if (plans.size >= 4096) plans.delete(plans.keys().next().value);
124
+ plans.set(key, plan);
125
+ }
126
+ return plan;
127
+ }
128
+
129
+ function buildRoutePlan(path, rules = [], context = {}) {
105
130
  const required = new Set((context.requiredMiddlewares || []).map(normalizeMiddlewareName));
106
131
  const exempt = new Set((context.exemptMiddlewares || []).map(normalizeMiddlewareName));
107
132
  const fullyExempt = !!context.fullyExempt;