aiwaf 1.1.0 → 1.1.2

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.
package/index.js CHANGED
@@ -27,12 +27,15 @@ function withMiddlewares(selection) {
27
27
  }
28
28
 
29
29
  module.exports = createExpressMiddleware;
30
+ // Await startup once; this path requires native support and has no JS policy fallback.
31
+ module.exports.native = require('./lib/nativePipeline');
30
32
  module.exports.fastify = createFastifyPlugin;
31
33
  module.exports.hapi = createHapiPlugin;
32
34
  module.exports.koa = createKoaMiddleware;
33
35
  module.exports.nest = createNestMiddleware;
34
36
  module.exports.next = createNextHandler;
35
37
  module.exports.adonis = createAdonisMiddleware;
38
+ module.exports.bodyParser = require('./lib/bodyParser');
36
39
  module.exports.sails = createExpressMiddleware;
37
40
  module.exports.auto = withMiddlewares('auto');
38
41
  module.exports.all = withMiddlewares('all');
@@ -46,7 +46,7 @@ function createExpressLikeResponse(ctx) {
46
46
  module.exports = function createAdonisMiddleware(opts = {}) {
47
47
  const middleware = createExpressMiddleware(opts);
48
48
 
49
- return async (ctx, next) => {
49
+ const wrapper = async (ctx, next) => {
50
50
  const req = ctx.request?.request || ctx.request || {};
51
51
  const res = createExpressLikeResponse(ctx);
52
52
 
@@ -58,11 +58,12 @@ module.exports = function createAdonisMiddleware(opts = {}) {
58
58
 
59
59
  // Don't override headers - the raw request already has them from the HTTP server
60
60
 
61
- await new Promise(resolve => {
61
+ await new Promise((resolve, reject) => {
62
62
  let resolved = false;
63
- const finish = () => {
63
+ const finish = error => {
64
64
  if (resolved) return;
65
65
  resolved = true;
66
+ if (error) { reject(error); return; }
66
67
  resolve();
67
68
  };
68
69
  const maybePromise = middleware(req, res, finish);
@@ -70,7 +71,7 @@ module.exports = function createAdonisMiddleware(opts = {}) {
70
71
  finish();
71
72
  return;
72
73
  }
73
- Promise.resolve(maybePromise).then(finish).catch(finish);
74
+ Promise.resolve(maybePromise).then(() => finish()).catch(reject);
74
75
  });
75
76
 
76
77
  if (res._handled || ctx.response?.response?.writableEnded || ctx.response?.response?.headersSent) {
@@ -79,4 +80,6 @@ module.exports = function createAdonisMiddleware(opts = {}) {
79
80
 
80
81
  await next();
81
82
  };
83
+ if (middleware.ready) wrapper.ready = middleware.ready;
84
+ return wrapper;
82
85
  };
@@ -0,0 +1,25 @@
1
+ const express = require('express');
2
+
3
+ // Use before AIWAF in raw Node/custom Next servers and early Nest middleware.
4
+ // Keep original bytes available to proxies after parsing consumes the stream.
5
+ module.exports = function bodyParser(options = {}) {
6
+ const limit = Number(options.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
7
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1048576) {
8
+ throw new Error('AIWAF_PAYLOAD_MAX_BYTES must be 1..1048576');
9
+ }
10
+ const verify = (req, _res, bytes) => { req.aiwafRawBody = Buffer.from(bytes); };
11
+ const parsers = [express.json({ limit, verify, inflate: false }),
12
+ express.urlencoded({ limit, verify, extended: false, inflate: false })];
13
+ return (req, res, next) => {
14
+ const run = index => {
15
+ if (index === parsers.length) return next();
16
+ parsers[index](req, res, error => {
17
+ if (!error) return run(index + 1);
18
+ res.statusCode = [400, 413, 415].includes(error.status) ? error.status : 400;
19
+ res.setHeader('content-type', 'application/json');
20
+ res.end(JSON.stringify({ error: res.statusCode === 413 ? 'payload_inspection_limit' : 'invalid_request_body' }));
21
+ });
22
+ };
23
+ run(0);
24
+ };
25
+ };
@@ -31,6 +31,21 @@ function createExpressLikeResponse(reply) {
31
31
  function fastifyPlugin(fastify, opts = {}, done) {
32
32
  const middleware = createExpressMiddleware(opts);
33
33
 
34
+ if (middleware.ready) {
35
+ // Parsed bodies are available here; do not reject/inspect an unparsed stream onRequest.
36
+ fastify.addHook('preValidation', async (request, reply) => {
37
+ const native = await middleware.ready;
38
+ const req = request.raw;
39
+ req.ip = request.ip; req.body = request.body; req.query = request.query;
40
+ req.path = String(req.url || '/').split('?')[0];
41
+ await native(req, createExpressLikeResponse(reply), error => { if (error) throw error; });
42
+ if (reply.sent) return reply;
43
+ });
44
+ fastify.addHook('onClose', async () => (await middleware.ready).close());
45
+ middleware.ready.then(() => done(), done);
46
+ return;
47
+ }
48
+
34
49
  fastify.addHook('onRequest', async (request, reply) => {
35
50
  const res = createExpressLikeResponse(reply);
36
51
  await middleware(request.raw, res, () => {});
package/lib/hapiPlugin.js CHANGED
@@ -50,6 +50,28 @@ module.exports = {
50
50
  register: async (server, opts = {}) => {
51
51
  const middleware = createExpressMiddleware(opts);
52
52
 
53
+ if (middleware.ready) {
54
+ const native = await middleware.ready;
55
+ const { DEFER_BODY } = require('./nativePipeline');
56
+ server.ext('onRequest', (request, h) => {
57
+ const req = request.raw.req;
58
+ req.ip = request.info.remoteAddress; req.path = request.path;
59
+ req.url = request.url.pathname + request.url.search;
60
+ req[DEFER_BODY] = true;
61
+ req.body = undefined; req.query = undefined;
62
+ const res = createExpressLikeResponse(h, request.raw.res);
63
+ native(req, res, error => { if (error) throw error; });
64
+ return res._handled ? res.toResponse().takeover() : h.continue;
65
+ });
66
+ server.ext('onPreHandler', (request,h) => {
67
+ request.raw.req.auth = request.auth;
68
+ const finding=native.inspectBody(request.raw.req,request.payload);
69
+ return finding ? h.response({error:finding.rule}).code(finding.status).takeover() : h.continue;
70
+ });
71
+ server.events.once('stop', () => native.close());
72
+ return;
73
+ }
74
+
53
75
  server.ext('onPreHandler', async (request, h) => {
54
76
  const finding = await middleware.inspectPayload({
55
77
  headers: request.headers, ip: request.info?.remoteAddress,
@@ -33,7 +33,7 @@ function createExpressLikeResponse(ctx) {
33
33
  module.exports = function createKoaMiddleware(opts = {}) {
34
34
  const middleware = createExpressMiddleware(opts);
35
35
 
36
- return async (ctx, next) => {
36
+ const wrapper = async (ctx, next) => {
37
37
  const res = createExpressLikeResponse(ctx);
38
38
  const req = ctx.req; // Raw Node.js http.IncomingMessage - already has headers
39
39
 
@@ -47,18 +47,19 @@ module.exports = function createKoaMiddleware(opts = {}) {
47
47
  // Don't override headers - use what's already on the raw request
48
48
  // ctx.headers is Koa's parsed version, but req.headers from Node.js has the originals
49
49
 
50
- await new Promise(resolve => {
50
+ await new Promise((resolve, reject) => {
51
51
  let resolved = false;
52
- const finish = () => {
52
+ const finish = error => {
53
53
  if (resolved) return;
54
54
  resolved = true;
55
+ if (error) { reject(error); return; }
55
56
  resolve();
56
57
  };
57
58
  const maybePromise = middleware(req, res, finish);
58
59
  if (res._handled) {
59
60
  finish();
60
61
  }
61
- Promise.resolve(maybePromise).then(finish).catch(finish);
62
+ Promise.resolve(maybePromise).then(() => finish()).catch(reject);
62
63
  });
63
64
 
64
65
  if (ctx.body !== undefined) {
@@ -67,4 +68,6 @@ module.exports = function createKoaMiddleware(opts = {}) {
67
68
 
68
69
  await next();
69
70
  };
71
+ if (middleware.ready) wrapper.ready = middleware.ready;
72
+ return wrapper;
70
73
  };
@@ -0,0 +1,191 @@
1
+ // Explicit WASM-owned request engine. Node owns transport and immediate filesystem I/O.
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { performance } = require('perf_hooks');
5
+ const { createRequestPipeline } = require('./wasmAdapter');
6
+ const { ALL_MIDDLEWARES, normalizeMiddlewareName } = require('./pathRules');
7
+
8
+ const LOG_HEADER = 'timestamp,ip,method,path,status,response_time_ms,blocked,reason,country,user_agent\n';
9
+ const BLOCK_HEADER = 'ip,expires_at,reason\n';
10
+ const KEYWORD_HEADER = 'keyword\n';
11
+ const DEFER_BODY = Symbol('aiwaf.native.defer-body');
12
+ function writer(file, header, durable) {
13
+ fs.mkdirSync(path.dirname(file), { recursive: true });
14
+ if (fs.existsSync(file) && fs.statSync(file).size) {
15
+ const fd = fs.openSync(file, 'r');
16
+ try {
17
+ const bytes = Buffer.alloc(Buffer.byteLength(header));
18
+ fs.readSync(fd, bytes, 0, bytes.length, 0);
19
+ if (bytes.toString() !== header) throw new Error(`Incompatible native CSV schema: ${file}`);
20
+ } finally { fs.closeSync(fd); }
21
+ }
22
+ const fd = fs.openSync(file, 'a');
23
+ const append = row => {
24
+ const buffer = Buffer.from(row);
25
+ let offset = 0;
26
+ while (offset < buffer.length) {
27
+ const written = fs.writeSync(fd, buffer, offset, buffer.length - offset);
28
+ if (!written) throw new Error('Native CSV append made no progress');
29
+ offset += written;
30
+ }
31
+ if (durable) fs.fsyncSync(fd);
32
+ };
33
+ try { if (!fs.statSync(file).size) append(header); } catch (error) { fs.closeSync(fd); throw error; }
34
+ return { append, close() { fs.closeSync(fd); } };
35
+ }
36
+ // Startup only: quoted newlines and commas must round-trip persisted native CSV.
37
+ function readRows(file, expected) {
38
+ const text = fs.readFileSync(file, 'utf8');
39
+ const rows = []; let row = [], value = '', quoted = false;
40
+ for (let i = 0; i < text.length; i++) {
41
+ const ch = text[i];
42
+ if (ch === '"') {
43
+ if (quoted && text[i + 1] === '"') { value += '"'; i++; }
44
+ else quoted = !quoted;
45
+ } else if (!quoted && (ch === ',' || ch === '\n')) {
46
+ row.push(value); value = '';
47
+ if (ch === '\n') { rows.push(row); row = []; }
48
+ } else value += ch;
49
+ }
50
+ if (quoted || row.length || value) throw new Error('Incomplete native policy CSV');
51
+ if (rows.shift()?.join(',') !== expected.join(',')) throw new Error('Invalid native policy schema');
52
+ return rows.map(cells => {
53
+ if (cells.length !== expected.length) throw new Error('Invalid native policy CSV row');
54
+ return Object.fromEntries(expected.map((key, index) => [key, cells[index]]));
55
+ });
56
+ }
57
+ function safeBody(req, limit) {
58
+ 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'] };
62
+ }
63
+ if (body && typeof body.pipe === 'function') return { body: null, exhausted: true };
64
+ try {
65
+ const value = Buffer.isBuffer(body) ? body.toString('utf8') : body;
66
+ const encoded = JSON.stringify(value);
67
+ if (encoded === undefined || Buffer.byteLength(encoded) > limit * 8) return { body: null, exhausted: true };
68
+ return { body: value, exhausted: false };
69
+ } catch (_) { return { body: null, exhausted: true }; }
70
+ }
71
+ function headers(raw = {}) {
72
+ return Object.fromEntries(Object.entries(raw).map(([key, value]) => [
73
+ ['content-type', 'content-length'].includes(key.toLowerCase()) ? key.toUpperCase().replace(/-/g, '_') : `HTTP_${key.toUpperCase().replace(/-/g, '_')}`,
74
+ Array.isArray(value) ? value.join(', ') : String(value ?? '')
75
+ ]));
76
+ }
77
+ function synchronous(callback, req, fallback) {
78
+ const result = callback ? callback(req) : fallback;
79
+ if (result && typeof result.then === 'function') throw new TypeError('Native fact callbacks must return synchronous values');
80
+ return result;
81
+ }
82
+
83
+ module.exports = async function createNativeMiddleware(options = {}) {
84
+ if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Native adapter options must be an object');
85
+ 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']);
87
+ for (const key of Object.keys(options)) if (!allowed.has(key)) throw new Error(`Unknown native adapter option: ${key}`);
88
+ for (const key of ['countryLookup','authenticated','routeExists','onError']) {
89
+ if (options[key] != null && (typeof options[key] !== 'function' || options[key].constructor.name === 'AsyncFunction')) throw new TypeError(`${key} must be synchronous`);
90
+ }
91
+ const profile = JSON.parse(JSON.stringify(options.profile || {}));
92
+ const dataDir = path.resolve(options.dataDir || 'aiwaf_native_data');
93
+ // State files are dedicated to this adapter. Legacy ORM/CSV schemas are not mixed.
94
+ const blockPath = path.join(dataDir, 'native_blocks.csv');
95
+ const keywordPath = path.join(dataDir, 'native_keywords.csv');
96
+ const persist = options.persistBlocks !== false;
97
+ const opened = [];
98
+ let log, blocks, keywords, engine;
99
+ try {
100
+ if (persist) {
101
+ blocks = writer(blockPath, BLOCK_HEADER, true); opened.push(blocks);
102
+ keywords = writer(keywordPath, KEYWORD_HEADER, true); opened.push(keywords);
103
+ const blacklist = { ...(profile.blacklist || {}) };
104
+ for (const row of readRows(blockPath, ['ip','expires_at','reason'])) {
105
+ if (!row.ip || !row.expires_at || !Number.isFinite(Number(row.expires_at))) throw new Error('Invalid persisted block row');
106
+ blacklist[row.ip] = Number(row.expires_at);
107
+ }
108
+ profile.blacklist = blacklist;
109
+ profile.dynamic_keywords = [...new Set([...(profile.dynamic_keywords || []), ...readRows(keywordPath, ['keyword']).map(r => r.keyword)])];
110
+ }
111
+ engine = await createRequestPipeline(profile, options.model);
112
+ if (!profile.enabled || profile.enabled.includes('logging')) {
113
+ log = writer(path.resolve(options.logPath || path.join(dataDir, 'native_requests.csv')), LOG_HEADER, !!options.logFsync); opened.push(log);
114
+ }
115
+ } catch (error) { if (engine) engine.native.free(); for (const entry of opened) entry.close(); throw error; }
116
+ const { native, setModel } = engine;
117
+ const maxBytes = profile.max_bytes ?? 65536;
118
+ let closed = false;
119
+ const contextKey = Symbol('aiwaf.native.context');
120
+ const pending = new Set();
121
+ const report = error => { if (options.onError) options.onError(error); else console.error('AIWAF native finalization failed:', error.message); };
122
+ function payload(req) {
123
+ const b = safeBody(req, maxBytes);
124
+ const query = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
125
+ if (b.exhausted && profile.sql_mode !== 'off') return { status: 413, rule: 'payload_inspection_limit' };
126
+ return JSON.parse(native.inspect_payload(JSON.stringify([query, b.body, req.query ?? null])));
127
+ }
128
+ const middleware = (req, res, next) => {
129
+ if (closed) return next(new Error('Native pipeline is closed'));
130
+ let decision;
131
+ const start = performance.now();
132
+ try {
133
+ const meta = req.aiwafRoute || {};
134
+ const required = new Set((meta.requiredMiddlewares || []).map(normalizeMiddlewareName));
135
+ const disabled = new Set((meta.fullyExempt ? ALL_MIDDLEWARES : meta.exemptMiddlewares || []).map(normalizeMiddlewareName));
136
+ for (const key of required) disabled.delete(key);
137
+ const rawPath = String(req.path || req.url || '/').split('?')[0];
138
+ const body = req[DEFER_BODY] ? {body:null,exhausted:false} : safeBody(req, maxBytes);
139
+ decision = JSON.parse(native.begin(JSON.stringify({
140
+ // Express trust proxy controls forwarded-IP handling. Never trust XFF directly.
141
+ ip: String(req.ip || req.socket?.remoteAddress || 'unknown').replace(/^::ffff:/, ''),
142
+ path: rawPath, method: String(req.method || 'GET'), headers: headers(req.headers),
143
+ query: String(req.originalUrl || req.url || '').split('?').slice(1).join('?'),
144
+ body: body.body, parsed_query: req.query ?? null,
145
+ now: Date.now() / 1000, country: String(synchronous(options.countryLookup, req, '') || ''),
146
+ authenticated: req[DEFER_BODY] ? false : !!synchronous(options.authenticated, req, false),
147
+ exists: !!synchronous(options.routeExists, req, !!req.route), disabled: [...disabled],
148
+ payload_exhausted: body.exhausted, defer_body: !!req[DEFER_BODY]
149
+ })));
150
+ } catch (error) { return next(error); }
151
+ pending.add(decision.context);
152
+ req[contextKey] = decision.context;
153
+ let done = false;
154
+ const finalize = aborted => {
155
+ if (done || closed) return;
156
+ done = true; pending.delete(decision.context);
157
+ try {
158
+ const effects = JSON.parse(native.finish(decision.context, aborted ? 499 : res.statusCode || 200, performance.now() - start, Date.now() / 1000));
159
+ if (blocks && effects.block_csv) blocks.append(effects.block_csv);
160
+ if (keywords && effects.keyword_csv) keywords.append(effects.keyword_csv);
161
+ if (log && effects.log_csv) log.append(effects.log_csv);
162
+ } catch (error) { report(error); }
163
+ };
164
+ res.on('finish', () => finalize(false));
165
+ res.on('close', () => finalize(true));
166
+ if (decision.status) return res.status(decision.status).json({ error: decision.reason });
167
+ return next();
168
+ };
169
+ middleware.inspectPayload = req => {
170
+ const disabled = req.aiwafRoute?.exemptMiddlewares || [];
171
+ if (profile.enabled && !profile.enabled.includes('ip_keyword_block')) return null;
172
+ if (req.aiwafRoute?.fullyExempt || disabled.includes('ip_keyword_block')) return null;
173
+ return payload(req);
174
+ };
175
+ middleware.diagnostics = () => JSON.parse(native.diagnostics());
176
+ middleware.inspectBody = (req, body) => {
177
+ const captured = safeBody({body,headers:{}},maxBytes);
178
+ return JSON.parse(native.inspect_body(req[contextKey], JSON.stringify(captured.body), captured.exhausted,
179
+ !!synchronous(options.authenticated,req,false), Date.now()/1000));
180
+ };
181
+ middleware.setModel = setModel;
182
+ middleware.close = () => {
183
+ if (closed) return;
184
+ if (pending.size) throw new Error('Stop requests and finish in-flight responses before closing the native pipeline');
185
+ closed = true;
186
+ for (const entry of opened) entry.close();
187
+ native.free();
188
+ };
189
+ return middleware;
190
+ };
191
+ module.exports.DEFER_BODY = DEFER_BODY;
@@ -3,10 +3,12 @@ const createExpressMiddleware = require('./wafMiddleware');
3
3
  module.exports = function createNestMiddleware(opts = {}) {
4
4
  const middleware = createExpressMiddleware(opts);
5
5
 
6
- return class AIWAFNestMiddleware {
6
+ class AIWAFNestMiddleware {
7
7
  use(req, res, next) {
8
8
  // Express middleware - req/res already have headers set by Express itself
9
9
  return middleware(req, res, next);
10
10
  }
11
11
  };
12
+ if (middleware.ready) AIWAFNestMiddleware.ready = middleware.ready;
13
+ return AIWAFNestMiddleware;
12
14
  };
@@ -42,8 +42,8 @@ function createExpressLikeResponse(res) {
42
42
  function wrapHandler(handler, opts) {
43
43
  const middleware = createExpressMiddleware(opts);
44
44
 
45
- return async (req, res) => {
46
- const handled = await new Promise(resolve => {
45
+ const wrapper = async (req, res) => {
46
+ const handled = await new Promise((resolve, reject) => {
47
47
  let done = false;
48
48
  const finish = () => {
49
49
  if (done) return;
@@ -53,12 +53,12 @@ function wrapHandler(handler, opts) {
53
53
  res.on('finish', finish);
54
54
  res.on('close', finish);
55
55
  const wrappedRes = createExpressLikeResponse(res);
56
- const maybePromise = middleware(req, wrappedRes, () => finish());
56
+ const maybePromise = middleware(req, wrappedRes, error => error ? reject(error) : finish());
57
57
  if (wrappedRes._handled) {
58
58
  finish();
59
59
  return;
60
60
  }
61
- Promise.resolve(maybePromise).then(finish).catch(finish);
61
+ Promise.resolve(maybePromise).then(() => finish()).catch(reject);
62
62
  });
63
63
 
64
64
  if (handled) return;
@@ -66,6 +66,8 @@ function wrapHandler(handler, opts) {
66
66
  if (res.finished) return;
67
67
  return handler(req, res);
68
68
  };
69
+ if (middleware.ready) wrapper.ready = middleware.ready;
70
+ return wrapper;
69
71
  }
70
72
 
71
73
  module.exports = function createNextHandler(handlerOrOpts, maybeOpts) {
@@ -5,6 +5,12 @@ let cacheBackend;
5
5
  let opts;
6
6
  let cleanupInterval;
7
7
 
8
+ function unavailable() {
9
+ const error = new Error('Rate cache unavailable');
10
+ error.code = 'AIWAF_RATE_CACHE_UNAVAILABLE';
11
+ return error;
12
+ }
13
+
8
14
  const defaultMemoryCache = new NodeCache({ stdTTL: 60, checkperiod: 120 }); // Auto cleanup every 2 minutes
9
15
 
10
16
  const fallbackCache = {
@@ -84,11 +90,13 @@ module.exports = {
84
90
  WINDOW_SEC: o?.WINDOW_SEC ?? 60,
85
91
  MAX_REQ: o?.MAX_REQ ?? 100,
86
92
  FLOOD_REQ: o?.FLOOD_REQ ?? 200,
93
+ failureMode: o?.AIWAF_RATE_CACHE_FAILURE_MODE ?? 'closed',
87
94
  cache: o?.cache
88
95
  };
89
96
  const requiredOps = ['lPush', 'expire', 'lLen', 'lRange'];
90
97
  const externalCache = opts.cache;
91
98
  const hasRequiredOps = externalCache && requiredOps.every(op => typeof externalCache[op] === 'function');
99
+ if (!['closed', 'open'].includes(opts.failureMode)) throw new Error('AIWAF_RATE_CACHE_FAILURE_MODE must be closed or open');
92
100
  cacheBackend = hasRequiredOps ? externalCache : fallbackCache;
93
101
 
94
102
  // Start cleanup interval for fallback cache
@@ -114,7 +122,8 @@ module.exports = {
114
122
  await blacklistManager.block(ip, 'flood');
115
123
  }
116
124
  } catch (err) {
117
- console.warn('Cache error in record().', err.message);
125
+ console.warn('Rate cache unavailable in record().');
126
+ if (opts.failureMode === 'closed') throw unavailable();
118
127
  }
119
128
  },
120
129
 
@@ -123,7 +132,8 @@ module.exports = {
123
132
  try {
124
133
  if (await blacklistManager.isBlocked(ip)) return true;
125
134
  } catch (err) {
126
- console.warn('Blacklist check error:', err.message);
135
+ console.warn('Blacklist unavailable during rate check.');
136
+ if (opts.failureMode === 'closed') throw unavailable();
127
137
  }
128
138
 
129
139
  try {
@@ -133,7 +143,8 @@ module.exports = {
133
143
  const within = timestamps.filter(t => now - t < effective.WINDOW_SEC * 1000);
134
144
  return within.length > effective.MAX_REQ;
135
145
  } catch (err) {
136
- console.warn('Cache error in isBlocked().', err.message);
146
+ console.warn('Rate cache unavailable in isBlocked().');
147
+ if (opts.failureMode === 'closed') throw unavailable();
137
148
  return false; // Fail open
138
149
  }
139
150
  },
@@ -134,6 +134,7 @@ function normalizeSettings(rawOpts = {}) {
134
134
  AIWAF_ROUTE_PLAN_VERSION: firstDefined(rawOpts.AIWAF_ROUTE_PLAN_VERSION, rawOpts.routePlanVersion, legacy.routePlanVersion, process.env.AIWAF_ROUTE_PLAN_VERSION, 0),
135
135
  AIWAF_ACCESS_LOG: firstDefined(rawOpts.AIWAF_ACCESS_LOG, rawOpts.accessLog, process.env.AIWAF_ACCESS_LOG, process.env.NODE_LOG_PATH),
136
136
 
137
+ AIWAF_RATE_CACHE_FAILURE_MODE: firstDefined(rawOpts.AIWAF_RATE_CACHE_FAILURE_MODE, process.env.AIWAF_RATE_CACHE_FAILURE_MODE, 'closed'),
137
138
  AIWAF_FORCE_JSON_ERRORS: toBool(firstDefined(rawOpts.AIWAF_FORCE_JSON_ERRORS, rawOpts.forceJsonErrors, legacy.errors?.forceJson), true)
138
139
  };
139
140
 
@@ -129,6 +129,18 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
129
129
 
130
130
 
131
131
  module.exports = function aiwaf(rawOpts = {}) {
132
+ if (rawOpts.AIWAF_NATIVE_PIPELINE !== undefined) {
133
+ if (Object.keys(rawOpts).some(key => key !== 'AIWAF_NATIVE_PIPELINE')) {
134
+ throw new Error('Native pipeline uses a dedicated profile; do not mix legacy options');
135
+ }
136
+ const ready = require('./nativePipeline')(rawOpts.AIWAF_NATIVE_PIPELINE);
137
+ // Compatibility wrapper for framework adapters. Await ready during application startup.
138
+ // No legacy modules are initialized and no fallback is selected on this branch.
139
+ const middleware = async (req, res, next) => (await ready)(req, res, next);
140
+ middleware.ready = ready;
141
+ middleware.inspectPayload = async req => (await ready).inspectPayload(req);
142
+ return middleware;
143
+ }
132
144
  let opts = normalizeSettings(rawOpts);
133
145
  const inspectSql = createInspector(opts);
134
146
  opts.AIWAF_MIDDLEWARES = normalizedMiddlewareList(opts.AIWAF_MIDDLEWARES);
@@ -390,17 +402,24 @@ module.exports = function aiwaf(rawOpts = {}) {
390
402
  }
391
403
 
392
404
  if (shouldApply('rate_limit')) {
393
- const rateOverrides = routePlan.getOverrides('RATE_LIMIT');
394
- await rateLimiter.record(ip, rateOverrides);
405
+ try {
406
+ const rateOverrides = routePlan.getOverrides('RATE_LIMIT');
407
+ await rateLimiter.record(ip, rateOverrides);
395
408
 
396
- if (await rateLimiter.isBlocked(ip, rateOverrides)) {
397
- if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
398
- console.error(`[AIWAF-BLOCK-RATE] ip=${ip}`);
409
+ if (await rateLimiter.isBlocked(ip, rateOverrides)) {
410
+ if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
411
+ console.error(`[AIWAF-BLOCK-RATE] ip=${ip}`);
412
+ }
413
+ if (await blacklistManager.isBlocked(ip)) {
414
+ return deny(403, 'blocked', 'flood_or_blacklist');
415
+ }
416
+ return deny(429, 'too_many_requests', 'rate_limit');
399
417
  }
400
- if (await blacklistManager.isBlocked(ip)) {
401
- return deny(403, 'blocked', 'flood_or_blacklist');
418
+ } catch (error) {
419
+ if (error.code === 'AIWAF_RATE_CACHE_UNAVAILABLE') {
420
+ return deny(503, 'temporarily_unavailable', 'rate_cache_unavailable');
402
421
  }
403
- return deny(429, 'too_many_requests', 'rate_limit');
422
+ throw error;
404
423
  }
405
424
  }
406
425
 
@@ -45,7 +45,8 @@ async function loadWasmFromDisk() {
45
45
  build_records: bg.build_records,
46
46
  rust_payload_from_records: bg.rust_payload_from_records,
47
47
  python_feature_from_record: bg.python_feature_from_record,
48
- python_features_batched: bg.python_features_batched
48
+ python_features_batched: bg.python_features_batched,
49
+ NativeRequestPipeline: bg.NativeRequestPipeline
49
50
  };
50
51
  }
51
52
 
@@ -522,7 +523,29 @@ function getWasmStatus() {
522
523
  };
523
524
  }
524
525
 
526
+ async function createRequestPipeline(profile = {}, model = null) {
527
+ const mod = await loadWasm();
528
+ if (!mod || typeof mod.NativeRequestPipeline !== 'function') {
529
+ throw new Error('Native pipeline requires aiwaf-wasm with NativeRequestPipeline support; no fallback');
530
+ }
531
+ const native = new mod.NativeRequestPipeline(JSON.stringify(profile));
532
+ if (['begin','finish','inspect_payload','inspect_body','set_model','clear_model','diagnostics'].some(name => typeof native[name] !== 'function')) {
533
+ native.free();
534
+ throw new Error('Incompatible NativeRequestPipeline API; install the matching WASM build');
535
+ }
536
+ const setModel = value => {
537
+ if (value == null) { native.clear_model(); return; }
538
+ if (!value.__aiwafWasm || typeof value.toJSON !== 'function') throw new TypeError('A trained Rust/WASM model is required');
539
+ const Forest = mod.IsolationForest || mod.AiwafIsolationForest;
540
+ const snapshot = Forest.from_json(value.toJSON());
541
+ try { native.set_model(snapshot); } finally { snapshot.free(); }
542
+ };
543
+ try { if (model) setModel(model); } catch (error) { native.free(); throw error; }
544
+ return { native, setModel };
545
+ }
546
+
525
547
  module.exports = {
548
+ createRequestPipeline,
526
549
  createIsolationForest,
527
550
  createIsolationForestFromJSON,
528
551
  validateHeaders,
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Aayush Gauba
4
+ Copyright (c) 2026 AIWAF
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.