aiwaf 1.2.4 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,301 @@
1
+ 'use strict';
2
+
3
+ // What each handler reads from the query and body, with types, for the route manifest. init
4
+ // saves these as each route's inputs (name to int, float, bool, uuid or text) and
5
+ // inputs_complete: true only when every read was understood. Requests are then reviewed against
6
+ // them in aiwaf-wasm: see AIWAF_ROUTE_SCHEMA_MODE.
7
+ //
8
+ // Anything not understood makes the list incomplete rather than guessed: the request passed to a
9
+ // function, req.query or req.body used whole, a key that isn't a constant, the raw body or URL
10
+ // parsed by hand, or route middleware that isn't a body parser.
11
+
12
+ const REQUEST_NAMES = new Set(['req', 'request']);
13
+ const CONTEXT_NAMES = new Set(['ctx', 'context']);
14
+ const CONTAINERS = new Set(['query', 'body']);
15
+ const CONVERTERS = new Map([
16
+ ['parseInt', 'int'], ['Number.parseInt', 'int'], ['Number', 'float'], ['parseFloat', 'float'],
17
+ ['Number.parseFloat', 'float'], ['Boolean', 'bool']
18
+ ]);
19
+ // Request members that read the query string or body some other way.
20
+ const RAW_MEMBERS = new Set(['rawBody', 'read', 'pipe', 'on', 'once', 'body_raw', 'files', 'file']);
21
+ const URL_PARSERS = /^(?:URL|URLSearchParams|url\.parse|querystring\.parse|qs\.parse|parseUrl)$/;
22
+ // Route middleware that only parses or guards: anything else may read the body itself.
23
+ const SAFE_MIDDLEWARE = /^(?:express\.(?:json|urlencoded|text|raw)|bodyParser\.\w+|cors|helmet|compression|multer)\b/;
24
+ const ROUTE_METHODS = new Set(['all', 'delete', 'get', 'head', 'options', 'patch', 'post', 'put']);
25
+ const SKIPPED = new Set(['loc', 'start', 'end', 'extra', 'leadingComments', 'trailingComments', 'innerComments', 'typeAnnotation', 'returnType', 'typeParameters']);
26
+
27
+ function dotted(node) {
28
+ if (!node) return '';
29
+ if (node.type === 'Identifier') return node.name;
30
+ if (node.type === 'ThisExpression') return 'this';
31
+ if ((node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression') && !node.computed) {
32
+ const base = dotted(node.object);
33
+ return base ? `${base}.${node.property.name}` : '';
34
+ }
35
+ if (node.type === 'CallExpression' || node.type === 'OptionalCallExpression') return dotted(node.callee);
36
+ if (node.type === 'NewExpression') return dotted(node.callee);
37
+ return '';
38
+ }
39
+
40
+ function isMember(node) {
41
+ return node && (node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression');
42
+ }
43
+
44
+ function isCall(node) {
45
+ return node && (node.type === 'CallExpression' || node.type === 'OptionalCallExpression' || node.type === 'NewExpression');
46
+ }
47
+
48
+ function isFunction(node) {
49
+ return node && ['ArrowFunctionExpression', 'FunctionDeclaration', 'FunctionExpression', 'ObjectMethod', 'ClassMethod'].includes(node.type);
50
+ }
51
+
52
+ function memberKey(node, constants = new Map()) {
53
+ if (!node.computed) return node.property.name;
54
+ if (node.property.type === 'StringLiteral') return node.property.value;
55
+ // A key held in a module-level string constant, as in req.query[PAGE].
56
+ return node.property.type === 'Identifier' && constants.has(node.property.name) ? constants.get(node.property.name) : null;
57
+ }
58
+
59
+ function children(node) {
60
+ const out = [];
61
+ for (const key of Object.keys(node)) {
62
+ if (SKIPPED.has(key)) continue;
63
+ const value = node[key];
64
+ if (Array.isArray(value)) {
65
+ for (const item of value) if (item && typeof item.type === 'string') out.push(item);
66
+ } else if (value && typeof value.type === 'string') {
67
+ out.push(value);
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+
73
+ function merge(inputs, name, kind) {
74
+ // A name read as two types, or as text anywhere, is text: the weaker reading wins.
75
+ inputs[name] = inputs[name] === undefined || inputs[name] === kind ? kind : 'text';
76
+ }
77
+
78
+ // The type a zod field's chain says, as in z.number().int() or z.string().uuid().
79
+ function zodType(source) {
80
+ if (/\.uuid\(/.test(source)) return 'uuid';
81
+ if (/\bboolean\(/.test(source)) return 'bool';
82
+ if (/\bnumber\(/.test(source) || /\bbigint\(/.test(source)) return /\.int\(/.test(source) ? 'int' : 'float';
83
+ return 'text';
84
+ }
85
+
86
+ // Module-level zod object schemas, as const Body = z.object({ name: z.string() }), by name.
87
+ function zodSchemas(ast, source) {
88
+ const schemas = new Map();
89
+ const visit = node => {
90
+ if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier' && node.init) {
91
+ let call = node.init;
92
+ const text = source.slice(node.init.start, node.init.end);
93
+ while (isCall(call) && isMember(call.callee) && dotted(call.callee) !== 'z.object') call = call.callee.object;
94
+ const object = isCall(call) && dotted(call.callee) === 'z.object' ? call.arguments[0] : null;
95
+ if (object && object.type === 'ObjectExpression') {
96
+ const fields = {};
97
+ let complete = !/\.(?:passthrough|catchall)\(/.test(text.slice(call.end - node.init.start));
98
+ for (const property of object.properties) {
99
+ const key = property.type === 'ObjectProperty' ? (property.key.name || property.key.value) : null;
100
+ if (!key) { complete = false; continue; }
101
+ merge(fields, key, zodType(source.slice(property.value.start, property.value.end)));
102
+ }
103
+ schemas.set(node.id.name, complete ? fields : null);
104
+ }
105
+ }
106
+ for (const child of children(node)) visit(child);
107
+ };
108
+ visit(ast);
109
+ return schemas;
110
+ }
111
+
112
+ /**
113
+ * What one handler reads: { inputs, complete }. scope holds the file's functions, which the
114
+ * request is followed into when passed to one, and its string constants. named, when given, is
115
+ * the parameter that holds the request in a followed function.
116
+ */
117
+ function handlerInputs(node, schemas, scope = { functions: new Map(), constants: new Map(), active: new Set() }, named = null) {
118
+ const inputs = {};
119
+ let complete = true;
120
+ const requests = new Set();
121
+ const contexts = new Set();
122
+ for (const parameter of node.params || []) {
123
+ const target = parameter.type === 'AssignmentPattern' ? parameter.left : parameter;
124
+ if (named !== null) {
125
+ if (target.type === 'Identifier' && target.name === named) requests.add(target.name);
126
+ } else if (target.type === 'Identifier' && REQUEST_NAMES.has(target.name)) requests.add(target.name);
127
+ else if (target.type === 'Identifier' && CONTEXT_NAMES.has(target.name)) contexts.add(target.name);
128
+ else if (target.type === 'ObjectPattern') complete = false; // ({ body, query }) destructured from the request.
129
+ }
130
+ const follow = (call, item) => {
131
+ // The request passed to a function in this file, as in return render(req, res): its reads count.
132
+ const target = call.callee.type === 'Identifier' ? scope.functions.get(call.callee.name) : null;
133
+ if (!target || scope.active.has(target) || scope.active.size >= 4) return false;
134
+ const index = call.arguments.indexOf(item);
135
+ const parameter = (target.params || [])[index];
136
+ const name = parameter && (parameter.type === 'AssignmentPattern' ? parameter.left : parameter);
137
+ if (!name || name.type !== 'Identifier') return false;
138
+ scope.active.add(target);
139
+ try {
140
+ const found = handlerInputs(target, schemas, scope, name.name);
141
+ for (const [key, kind] of Object.entries(found.inputs)) merge(inputs, key, kind);
142
+ if (!found.complete) complete = false;
143
+ } finally {
144
+ scope.active.delete(target);
145
+ }
146
+ return true;
147
+ };
148
+ const parents = new Map();
149
+ const nodes = [];
150
+ const index = (item, parent) => {
151
+ parents.set(item, parent);
152
+ nodes.push(item);
153
+ for (const child of children(item)) index(child, item);
154
+ };
155
+ // The body only: the parameters themselves aren't uses of the request.
156
+ if (node.body) index(node.body, node);
157
+ const aliases = new Set();
158
+
159
+ const converted = read => {
160
+ let current = read;
161
+ let parent = parents.get(current);
162
+ // Through a default, as in parseInt(req.query.page || '1').
163
+ while (parent && parent.type === 'LogicalExpression' && parent.left === current) {
164
+ current = parent;
165
+ parent = parents.get(current);
166
+ }
167
+ if (isCall(parent) && parent.arguments[0] === current) return CONVERTERS.get(dotted(parent.callee)) || 'text';
168
+ if (parent && parent.type === 'UnaryExpression' && parent.operator === '+') return 'float';
169
+ return 'text';
170
+ };
171
+
172
+ const container = expr => {
173
+ const parent = parents.get(expr);
174
+ if (isMember(parent) && parent.object === expr) {
175
+ const key = memberKey(parent, scope.constants);
176
+ if (key === null) complete = false;
177
+ else merge(inputs, key, converted(parent));
178
+ return;
179
+ }
180
+ if (parent && parent.type === 'VariableDeclarator' && parent.init === expr) {
181
+ if (parent.id.type === 'Identifier') {
182
+ aliases.add(parent.id.name);
183
+ return;
184
+ }
185
+ if (parent.id.type === 'ObjectPattern') {
186
+ for (const property of parent.id.properties) {
187
+ const key = property.type === 'ObjectProperty' ? (property.key.name || property.key.value) : null;
188
+ if (!key || property.computed) complete = false;
189
+ else merge(inputs, key, 'text');
190
+ }
191
+ return;
192
+ }
193
+ }
194
+ if (parent && parent.type === 'BinaryExpression' && parent.operator === 'in' && parent.right === expr) return;
195
+ if (isCall(parent) && parent.arguments.includes(expr) && isMember(parent.callee)) {
196
+ // Body.parse(req.body) with a zod object schema from this file.
197
+ const method = parent.callee.property.name;
198
+ const fields = ['parse', 'safeParse', 'parseAsync', 'safeParseAsync'].includes(method)
199
+ ? schemas.get(dotted(parent.callee.object)) : undefined;
200
+ if (fields) {
201
+ for (const [key, kind] of Object.entries(fields)) merge(inputs, key, kind);
202
+ return;
203
+ }
204
+ }
205
+ complete = false;
206
+ };
207
+
208
+ const isRequest = item => item && item.type === 'Identifier' && requests.has(item.name);
209
+ const isContext = item => item && item.type === 'Identifier' && contexts.has(item.name);
210
+ for (const item of nodes) {
211
+ if (isMember(item) && !item.computed && (isRequest(item.object) || isContext(item.object)
212
+ || (isMember(item.object) && isContext(item.object.object) && memberKey(item.object) === 'request'))) {
213
+ const name = item.property.name;
214
+ // Koa's ctx.body is the response; its request body is ctx.request.body.
215
+ const response = isContext(item.object) && name === 'body';
216
+ if (response) continue;
217
+ if (CONTAINERS.has(name)) container(item);
218
+ else if (RAW_MEMBERS.has(name)) complete = false;
219
+ else if (name === 'param') {
220
+ const call = parents.get(item);
221
+ const key = isCall(call) && call.arguments[0];
222
+ if (key && key.type === 'StringLiteral') merge(inputs, key.value, converted(call));
223
+ else complete = false;
224
+ } else if (['url', 'originalUrl', 'querystring', 'search', 'href'].includes(name)) {
225
+ // The URL is fine to log or redirect to, but not to read the query from by hand.
226
+ const call = parents.get(item);
227
+ if (isCall(call) && URL_PARSERS.test(dotted(call.callee))) complete = false;
228
+ }
229
+ } else if (item.type === 'Identifier' && (requests.has(item.name) || contexts.has(item.name))) {
230
+ const parent = parents.get(item);
231
+ const declared = parent && (parent.type === 'VariableDeclarator' && parent.id === item);
232
+ if (!(isMember(parent) && parent.object === item) && !declared && !(parent && parent.type === 'ObjectProperty' && parent.key === item)
233
+ && !(isCall(parent) && parent.arguments.includes(item) && follow(parent, item))) {
234
+ complete = false; // The request goes somewhere that may read it.
235
+ }
236
+ }
237
+ }
238
+ // What's read from an alias, as const body = req.body, then body.name.
239
+ for (const item of nodes) {
240
+ if (item.type === 'Identifier' && aliases.has(item.name)) {
241
+ const parent = parents.get(item);
242
+ if (parent && parent.type === 'VariableDeclarator' && parent.id === item) continue;
243
+ if (isMember(parent) && parent.property === item && !parent.computed) continue;
244
+ if (parent && parent.type === 'ObjectProperty' && parent.key === item && !parent.computed) continue;
245
+ container(item);
246
+ }
247
+ }
248
+ return { inputs, complete };
249
+ }
250
+
251
+ /**
252
+ * Each handler's inputs in one parsed file: { function, file, inputs, complete }. label(node,
253
+ * parent) names a handler as the injection audit does, so both link to the same routes.
254
+ */
255
+ function fileInputs(ast, filename, source, label) {
256
+ const schemas = zodSchemas(ast, source || '');
257
+ // The file's top-level functions and string constants.
258
+ const scope = { functions: new Map(), constants: new Map(), active: new Set() };
259
+ for (const statement of (ast.program || ast).body || []) {
260
+ const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
261
+ if (!declaration) continue;
262
+ if (declaration.type === 'FunctionDeclaration' && declaration.id) scope.functions.set(declaration.id.name, declaration);
263
+ if (declaration.type === 'VariableDeclaration') {
264
+ for (const item of declaration.declarations) {
265
+ if (item.id.type !== 'Identifier' || !item.init) continue;
266
+ if (isFunction(item.init)) scope.functions.set(item.id.name, item.init);
267
+ if (declaration.kind === 'const' && item.init.type === 'StringLiteral') scope.constants.set(item.id.name, item.init.value);
268
+ }
269
+ }
270
+ }
271
+ const results = [];
272
+ const visit = (node, parent) => {
273
+ if (isFunction(node) && (node.params || []).some(parameter => {
274
+ const target = parameter.type === 'AssignmentPattern' ? parameter.left : parameter;
275
+ return target.type === 'Identifier' && (REQUEST_NAMES.has(target.name) || CONTEXT_NAMES.has(target.name));
276
+ })) {
277
+ scope.active.add(node);
278
+ const found = handlerInputs(node, schemas, scope);
279
+ scope.active.delete(node);
280
+ // app.post('/x', auth, handler): middleware before the handler may read the body itself.
281
+ if (isCall(parent) && isMember(parent.callee) && ROUTE_METHODS.has(parent.callee.property.name)) {
282
+ const others = parent.arguments.slice(1).filter(argument => argument !== node);
283
+ if (others.some(argument => !(isCall(argument) && SAFE_MIDDLEWARE.test(dotted(argument.callee))))) found.complete = false;
284
+ }
285
+ results.push({ function: label(node, parent), file: filename, inputs: found.inputs, complete: found.complete });
286
+ }
287
+ for (const child of children(node)) visit(child, node);
288
+ };
289
+ visit(ast.program || ast, null);
290
+ return results;
291
+ }
292
+
293
+ /** Adds one handler's inputs to a route; a route served by several takes them all. */
294
+ function mergeInto(routes, path, entry) {
295
+ const data = routes[path];
296
+ data.inputs = data.inputs || {};
297
+ for (const [name, kind] of Object.entries(entry.inputs)) merge(data.inputs, name, kind);
298
+ data.inputs_complete = (data.inputs_complete ?? true) && Boolean(entry.complete);
299
+ }
300
+
301
+ module.exports = { fileInputs, handlerInputs, mergeInto };
@@ -6,7 +6,7 @@ const { createRequestPipeline } = require('./wasmAdapter');
6
6
  const wasmChecks = require('./wasmChecks');
7
7
  const routeRisks = require('./routeRisks');
8
8
  const { ALL_MIDDLEWARES, createRoutePlan } = require('./pathRules');
9
- const { getEffectivePathRules } = require('./pathManifest');
9
+ const { getEffectivePathRules, loadManifest } = require('./pathManifest');
10
10
  const { getRequestIp } = require('./runtimeUtils');
11
11
 
12
12
  // RATE_LIMIT names accepted in path rules, as in the regular rate limiter.
@@ -76,11 +76,11 @@ function readRows(file, expected) {
76
76
  return Object.fromEntries(expected.map((key, index) => [key, cells[index]]));
77
77
  });
78
78
  }
79
- // The content types whose bodies are inspected, as in Python. Uploads and other bodies
80
- // (multipart, binary) pass through unread, as in the regular middleware.
79
+ // The content types whose bodies are inspected, as in Python. A multipart form is checked by
80
+ // its first max bytes; other bodies (binary uploads) pass through unread.
81
81
  function inspectable(req) {
82
82
  const media = String(req.headers?.['content-type'] || '').split(';', 1)[0].trim().toLowerCase();
83
- return ['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'].includes(media)
83
+ return ['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml', 'multipart/form-data'].includes(media)
84
84
  || media.endsWith('+json') || media.endsWith('+xml');
85
85
  }
86
86
  function declaredBody(req) {
@@ -93,38 +93,16 @@ function readable(req) {
93
93
  && typeof req.read === 'function' && typeof req.unshift === 'function' && !req.readableEnded;
94
94
  }
95
95
  const PEEKED = Symbol('aiwaf.native.peeked-body');
96
- // Reads at most limit + 1 bytes of the body, then puts them back on the stream, so body
97
- // parsers after this adapter still read the whole body. Python's adapters do the same.
98
- function peekBody(req, limit) {
99
- return new Promise((resolve, reject) => {
100
- const chunks = [];
101
- let size = 0;
102
- const expected = Number(req.headers?.['content-length']) || null;
103
- const finish = () => {
104
- req.removeListener('readable', onReadable);
105
- req.removeListener('error', onError);
106
- const prefix = Buffer.concat(chunks);
107
- if (prefix.length) req.unshift(prefix);
108
- resolve(prefix);
109
- };
110
- const onError = error => { req.removeListener('readable', onReadable); reject(error); };
111
- function onReadable() {
112
- let chunk;
113
- while ((chunk = req.read()) !== null) {
114
- chunks.push(chunk);
115
- size += chunk.length;
116
- if (size > limit || size === expected) return finish();
117
- }
118
- // The whole body is buffered: put it back before the stream emits 'end'.
119
- if (req._readableState?.ended) finish();
120
- }
121
- req.on('error', onError);
122
- req.on('readable', onReadable);
123
- });
124
- }
96
+ const { peekBody, isMultipart } = require('./bodyPeek');
125
97
  function safeBody(req, limit) {
126
98
  const peeked = req[PEEKED];
127
99
  if (peeked) {
100
+ // A large upload is checked by its start: its text fields and file headers come first.
101
+ if (isMultipart(req)) {
102
+ // The query is counted twice in the check, as sent and parsed.
103
+ const query = Buffer.byteLength(String(req.originalUrl || req.url || '').split('?').slice(1).join('?'));
104
+ return { body: peeked.subarray(0, Math.max(0, limit - 2 * query)).toString('utf8'), exhausted: false };
105
+ }
128
106
  if (peeked.length > limit) return { body: null, exhausted: true };
129
107
  const text = peeked.toString('utf8');
130
108
  // JSON is parsed here, as a body parser would, so it's checked exactly like a parsed body.
@@ -280,7 +258,7 @@ function synchronous(callback, req, fallback) {
280
258
  module.exports = async function createNativeMiddleware(options = {}) {
281
259
  if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Native adapter options must be an object');
282
260
  if (options.profile !== undefined && (!options.profile || typeof options.profile !== 'object' || Array.isArray(options.profile))) throw new TypeError('Native profile must be an object');
283
- const allowed = new Set(['profile', 'dataDir', 'logPath', 'logFsync', 'persistBlocks', 'model', 'countryLookup', 'authenticated', 'routeExists', 'onError', 'pathRules', 'manifestPath', 'injectionRiskMode', 'logger', 'uuidResolver', 'stores', 'storeCacheSeconds', 'storesFallback',
261
+ const allowed = new Set(['profile', 'dataDir', 'logPath', 'logFsync', 'persistBlocks', 'model', 'countryLookup', 'authenticated', 'routeExists', 'onError', 'pathRules', 'manifestPath', 'injectionRiskMode', 'routeSchemaMode', 'logger', 'uuidResolver', 'stores', 'storeCacheSeconds', 'storesFallback',
284
262
  'rateCounter', 'rateCounterFallback', 'rateFailureMode', 'trustedProxies', 'modelFile', 'modelLoader', 'regularLog', 'modelGate', 'exact', 'regularAnomaly', 'userAgentVerdict']);
285
263
  for (const key of Object.keys(options)) if (!allowed.has(key)) throw new Error(`Unknown native adapter option: ${key}`);
286
264
  if (options.uuidResolver != null && typeof options.uuidResolver !== 'function') throw new TypeError('uuidResolver must be a function');
@@ -406,6 +384,22 @@ module.exports = async function createNativeMiddleware(options = {}) {
406
384
  stores = null;
407
385
  } else if (!supported) throw new Error('stores needs a newer aiwaf-wasm. Run: npm install aiwaf-wasm@latest');
408
386
  }
387
+ // The manifest's saved inputs, which the engine reviews payload findings against, as the
388
+ // regular middleware does: see AIWAF_ROUTE_SCHEMA_MODE.
389
+ const schemaMode = String(options.routeSchemaMode ?? process.env.AIWAF_ROUTE_SCHEMA_MODE ?? 'monitor').trim().toLowerCase();
390
+ if (!['enforce', 'monitor', 'off'].includes(schemaMode)) throw new Error('AIWAF_ROUTE_SCHEMA_MODE must be enforce, monitor, or off');
391
+ const manifest = schemaMode === 'off' ? null : loadManifest(manifestPath || undefined);
392
+ if (Object.values((manifest && manifest.routes) || {}).some(entry => entry && entry.inputs && typeof entry.inputs === 'object')) {
393
+ const probe = await createRequestPipeline({});
394
+ const supported = typeof probe.native.supports === 'function' && probe.native.supports('route_schema');
395
+ probe.native.free();
396
+ if (supported) {
397
+ profile.route_schema_mode = schemaMode;
398
+ profile.route_manifest = manifest;
399
+ } else {
400
+ (options.logger || console).warn?.('AIWAF native: route schemas need a newer aiwaf-wasm, so they aren\'t reviewed. Run: npm install aiwaf-wasm@latest');
401
+ }
402
+ }
409
403
  // With stores, blocks and learned keywords live in the stores instead of dataDir.
410
404
  const persist = !stores && options.persistBlocks !== false;
411
405
  if (stores) profile.policy_store = 'host';
@@ -445,6 +439,13 @@ module.exports = async function createNativeMiddleware(options = {}) {
445
439
  const { native, setModel } = engine;
446
440
  const logger = options.logger || console;
447
441
  // Monitored SQL findings are logged as the regular middleware logs them, and never block.
442
+ // The engine's route schema review returns its log line with the result.
443
+ const reviewed = result => {
444
+ if (!result || !result.schema) return result;
445
+ try { logger.warn?.(result.schema); } catch (_) { /* Logging must not decide the outcome. */ }
446
+ const { schema, ...rest } = result;
447
+ return rest.rule ? rest : null;
448
+ };
448
449
  const monitored = finding => {
449
450
  if (finding?.mode !== 'monitor') return finding;
450
451
  logger.warn?.({ event: 'aiwaf.payload', rule: finding.rule, mode: 'monitor' });
@@ -533,15 +534,24 @@ module.exports = async function createNativeMiddleware(options = {}) {
533
534
  const report = error => { if (options.onError) options.onError(error); else console.error('AIWAF native finalization failed:', error.message); };
534
535
  // This pipeline takes no general settings, so these two come from the environment. Route
535
536
  // checks run in aiwaf-wasm, loaded here so requests can use them straight away.
536
- const observeRisks = routeRisks.createObserver({ AIWAF_PATH_MANIFEST: manifestPath, AIWAF_INJECTION_RISK_MODE: options.injectionRiskMode });
537
- if (observeRisks) await wasmChecks.load();
537
+ const observeRisks = routeRisks.createObserver({ AIWAF_PATH_MANIFEST: manifestPath, AIWAF_INJECTION_RISK_MODE: options.injectionRiskMode,
538
+ AIWAF_ROUTE_SCHEMA_MODE: 'off' });
539
+ // inspect_payload takes no path, so its findings are reviewed here against the route's saved
540
+ // inputs, as the engine reviews its own.
541
+ const schemaObserver = profile.route_schema_mode
542
+ ? routeRisks.createObserver({ AIWAF_PATH_MANIFEST: manifestPath, AIWAF_INJECTION_RISK_MODE: 'off',
543
+ AIWAF_ROUTE_SCHEMA_MODE: profile.route_schema_mode, logger })
544
+ : null;
545
+ if (observeRisks || schemaObserver) await wasmChecks.load();
538
546
  function payload(req) {
539
547
  const b = safeBody(req, maxBytes);
540
548
  const query = String(req.originalUrl || req.url || '').split('?').slice(1).join('?');
541
549
  if (b.exhausted && profile.sql_mode !== 'off') {
542
550
  return monitored({ status: 413, rule: 'payload_inspection_limit', mode: profile.sql_mode });
543
551
  }
544
- return monitored(JSON.parse(native.inspect_payload(JSON.stringify([query, b.body, req.query ?? null]))));
552
+ let finding = JSON.parse(native.inspect_payload(JSON.stringify([query, b.body, req.query ?? null])));
553
+ if (schemaObserver?.review) finding = schemaObserver.review(req, finding, maxBytes, b.body);
554
+ return monitored(finding);
545
555
  }
546
556
  // A uuidResolver may be async, so only requests it applies to wait for it.
547
557
  const middleware = (req, res, next) => {
@@ -628,6 +638,7 @@ module.exports = async function createNativeMiddleware(options = {}) {
628
638
  })));
629
639
  } catch (error) { return next(error); }
630
640
  if (decision.monitor) monitored({ rule: decision.monitor, mode: 'monitor' });
641
+ if (decision.schema) reviewed(decision);
631
642
  pending.add(decision.context);
632
643
  req[contextKey] = decision.context;
633
644
  let done = false;
@@ -697,8 +708,8 @@ module.exports = async function createNativeMiddleware(options = {}) {
697
708
  middleware.diagnostics = () => JSON.parse(native.diagnostics());
698
709
  middleware.inspectBody = (req, body) => {
699
710
  const captured = safeBody({body,headers:{}},maxBytes);
700
- return monitored(JSON.parse(native.inspect_body(req[contextKey], JSON.stringify(captured.body), captured.exhausted,
701
- !!synchronous(options.authenticated,req,false), Date.now()/1000)));
711
+ return monitored(reviewed(JSON.parse(native.inspect_body(req[contextKey], JSON.stringify(captured.body), captured.exhausted,
712
+ !!synchronous(options.authenticated,req,false), Date.now()/1000))));
702
713
  };
703
714
  middleware.setModel = setModel;
704
715
  middleware.close = () => {
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+
3
+ // AIWAF_PROFILE: one setting for sensible defaults.
4
+ // - balanced (the default) keeps every default as it is.
5
+ // - strict halves the rate limits and turns the method policy on.
6
+ // - monitor is a dry run: every check runs, and what it would block is logged instead, as
7
+ // "AIWAF monitor: would block ...". Nothing is blocked and no IP is added to the blocklist.
8
+ // A setting given explicitly always wins over the profile.
9
+
10
+ const PROFILES = ['strict', 'balanced', 'monitor'];
11
+ let active = null;
12
+
13
+ function resolve(value) {
14
+ const raw = value === undefined || value === null || value === '' ? process.env.AIWAF_PROFILE : value;
15
+ const name = String(raw || 'balanced').trim().toLowerCase();
16
+ if (!PROFILES.includes(name)) throw new Error(`AIWAF_PROFILE must be one of ${PROFILES.join(', ')}, not ${JSON.stringify(raw)}`);
17
+ return name;
18
+ }
19
+
20
+ function activate(value) {
21
+ active = resolve(value);
22
+ return active;
23
+ }
24
+
25
+ function monitoring() {
26
+ try {
27
+ return (active || resolve()) === 'monitor';
28
+ } catch (_error) {
29
+ return false;
30
+ }
31
+ }
32
+
33
+ // The defaults a profile sets, given Node's own defaults.
34
+ function defaultsFor(profile) {
35
+ if (profile === 'strict') {
36
+ return { MAX_REQ: 50, FLOOD_REQ: 100, AIWAF_METHOD_POLICY_ENABLED: true, AIWAF_SQL_INJECTION_MODE: 'block', AIWAF_INJECTION_RISK_MODE: 'block' };
37
+ }
38
+ if (profile === 'monitor') return { AIWAF_SQL_INJECTION_MODE: 'monitor', AIWAF_INJECTION_RISK_MODE: 'log' };
39
+ return {};
40
+ }
41
+
42
+ function wouldBlock(method, path, ip, status, reason) {
43
+ console.warn(`AIWAF monitor: would block ${method || '-'} ${path || '-'} from ${ip || '-'} with ${status} (${reason || 'blocked'})`);
44
+ }
45
+
46
+ // True in monitor mode, after logging the IP that would have been added to the blocklist.
47
+ function skipBlocklist(ip, reason) {
48
+ if (!monitoring()) return false;
49
+ console.warn(`AIWAF monitor: would add ${ip} to the blocklist (${reason})`);
50
+ return true;
51
+ }
52
+
53
+ module.exports = { PROFILES, activate, defaultsFor, monitoring, resolve, skipBlocklist, wouldBlock };