aiwaf 1.2.0 → 1.2.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/README.md CHANGED
@@ -39,13 +39,13 @@ the supported Redis backends when sharing limits across workers.
39
39
 
40
40
  Each package is versioned and released independently.
41
41
 
42
- Python 1.2.0, Rust/Python 0.2.9, Node.js 1.2.0, WASM 0.2.7, and Java 1.3.6 are local source targets. See the package table below and [CHANGELOG](CHANGELOG.md) for release changes.
42
+ Python 1.2.2, Rust/Python 0.2.10, Node.js 1.2.2, WASM 0.2.7, and Java 1.3.6 are local source targets. See the package table below and [CHANGELOG](CHANGELOG.md) for release changes.
43
43
 
44
44
  | Runtime | Package | Repository version | Primary use |
45
45
  | --- | --- | ---: | --- |
46
- | Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.2.0` | Django, Flask, and FastAPI protection |
47
- | Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.2.0` | Express and Node framework middleware |
48
- | Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.9` | Native Python acceleration and JSON model inference |
46
+ | Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.2.2` | Django, Flask, and FastAPI protection |
47
+ | Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.2.2` | Express and Node framework middleware |
48
+ | Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.10` | Native Python acceleration and JSON model inference |
49
49
  | WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.7` | Rust detection and model primitives for JavaScript |
50
50
  | Java | `io.github.aiwaf-project:aiwaf-java` | `1.3.6` | Spring MVC and Jakarta Servlet protection |
51
51
 
@@ -87,7 +87,7 @@ When a peer that isn't trusted sends `X-Forwarded-For` or `X-Real-IP`, all three
87
87
  > [!IMPORTANT]
88
88
  > If your proxy or CDN connects from a public address (Cloudflare or Google Cloud load balancers, for example), add its ranges to `AIWAF_TRUSTED_PROXIES`. Otherwise every visitor appears to come from the proxy, and rate limiting or a block can then affect all of them. The `cloudflare` name trusts every Cloudflare address, and anyone can send requests through Cloudflare. If clients could also send requests through Cloudflare to your origin from outside your zone, restrict the origin to your zone, for example with authenticated origin pulls.
89
89
 
90
- If untrusted hosts can reach the application directly from your private network, narrow the list to your proxy's addresses. Addresses already resolved by Flask's `ProxyFix`, Uvicorn's `--proxy-headers`, or Express `trust proxy` are respected, except that AIWAF still walks the headers when the resolved address is itself in a trusted range. The Rust-owned Node pipeline uses `req.ip` only, so configure `trust proxy` there.
90
+ If untrusted hosts can reach the application directly from your private network, narrow the list to your proxy's addresses. Addresses already resolved by Flask's `ProxyFix`, Uvicorn's `--proxy-headers`, or Express `trust proxy` are respected, except that AIWAF still walks the headers when the resolved address is itself in a trusted range. The Rust-owned Node pipeline resolves the address the same way when it runs from the regular options (the default, or `from_settings`); configured on its own, it uses `req.ip` unless its `trustedProxies` option is set.
91
91
 
92
92
  ## Injection audit
93
93
 
@@ -256,7 +256,7 @@ pip install "aiwaf[django]"
256
256
  pip install "aiwaf[flask]"
257
257
  pip install "aiwaf[fastapi]"
258
258
 
259
- # Backward-compatible alias; Python 1.2.0 already installs aiwaf-rust
259
+ # Backward-compatible alias; Python 1.2.2 already installs aiwaf-rust
260
260
  pip install "aiwaf[rust]"
261
261
 
262
262
  # Node.js middleware
@@ -280,7 +280,7 @@ Java 1.3.6, after it is published to Maven Central:
280
280
 
281
281
  The Python package requires Python 3.10 or newer. Framework dependencies are optional, so install only the extra needed by the application.
282
282
 
283
- Python 1.2.0 requires `aiwaf-rust>=0.2.9`; the `rust` extra remains an installation
283
+ Python 1.2.2 requires `aiwaf-rust>=0.2.10`; the `rust` extra remains an installation
284
284
  alias. Publish the matching Rust wheel with `NativeCSVPipeline` support before
285
285
  the Python release. The Rust release workflow builds Linux x86_64/aarch64,
286
286
  musl x86_64, macOS x86_64/arm64 and Windows x86_64 wheels and checks the native
@@ -1666,9 +1666,9 @@ Release versions and tags must match the relevant manifest.
1666
1666
 
1667
1667
  | Package | Manifest | Tag | Workflow |
1668
1668
  | --- | --- | --- | --- |
1669
- | Python `aiwaf` | `pyproject.toml` | `python-v1.2.0` | `python-publish.yml` |
1670
- | npm `aiwaf` | `js/package.json` | `js-v1.2.0` | `npm-publish.yml` |
1671
- | PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.9` | `rust-publish.yml` |
1669
+ | Python `aiwaf` | `pyproject.toml` | `python-v1.2.2` | `python-publish.yml` |
1670
+ | npm `aiwaf` | `js/package.json` | `js-v1.2.2` | `npm-publish.yml` |
1671
+ | PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.10` | `rust-publish.yml` |
1672
1672
  | npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.7` | `wasm-publish.yml` |
1673
1673
  | Maven `aiwaf-java` | `java/pom.xml` | `java-v1.3.6` | `java-publish.yml` |
1674
1674
 
@@ -1678,13 +1678,10 @@ Java publishing uses the protected `maven-publish` environment plus `GPG_PRIVATE
1678
1678
 
1679
1679
  Registry releases are immutable. Increment the relevant manifest version before publishing another release.
1680
1680
 
1681
- For this release, publish `aiwaf-rust 0.2.9` before Python `aiwaf 1.2.0`, and
1682
- `aiwaf-wasm 0.2.7` before npm `aiwaf 1.2.0`. Python `aiwaf` 1.2.0 requires
1683
- `aiwaf-rust>=0.2.9`, so its CI installs need 0.2.9 published first. npm `aiwaf` 1.2.0
1684
- needs `aiwaf-wasm` 0.2.7, but its dependency and lockfile still name 0.2.6 so that
1685
- `npm ci` keeps working until 0.2.7 is published. After WASM publication, run
1686
- `npm install aiwaf-wasm@^0.2.7` in `js/` to update both, commit that, run `npm ci`
1687
- and the release checks, and only then publish npm `aiwaf`. Java has no changes since
1681
+ This release is Python `aiwaf 1.2.2` with `aiwaf-rust 0.2.10`, and npm `aiwaf 1.2.2`.
1682
+ Publish `aiwaf-rust 0.2.10` before Python `aiwaf 1.2.2`, which requires it. `aiwaf-wasm`
1683
+ 0.2.7 is unchanged, so npm `aiwaf` 1.2.2 can be published directly. npm `aiwaf` 1.2.2 declares `aiwaf-wasm ^0.2.7`; the published
1684
+ 1.2.0 still declared `^0.2.6`. Java has no changes since
1688
1685
  1.3.6, which is already published.
1689
1686
 
1690
1687
  ## Security and limitations
@@ -260,18 +260,28 @@ module.exports = async function createNativeMiddleware(options = {}) {
260
260
  const profile = JSON.parse(JSON.stringify(options.profile || {}));
261
261
  const manifestPath = options.manifestPath ?? process.env.AIWAF_PATH_MANIFEST;
262
262
  const rules = getEffectivePathRules(options.pathRules || [], manifestPath ? { manifestPath } : undefined);
263
- // Checked once, so a bad rule fails at startup rather than on a request.
263
+ // The regular rate limiter flood-blocks above the flood threshold before a higher limit is
264
+ // reached, so a limit above it acts as the threshold: the engine is given that.
265
+ if (profile.rate_max !== undefined && profile.rate_max > (profile.rate_flood ?? 40)) profile.rate_max = profile.rate_flood ?? 40;
264
266
  const profileRate = { window: profile.rate_window ?? 10, max: profile.rate_max ?? 20, flood: profile.rate_flood ?? 40 };
267
+ const effectiveRate = overrides => {
268
+ if (!Object.keys(overrides).length) return overrides;
269
+ const limits = { ...profileRate, ...overrides };
270
+ limits.flood = Math.min(limits.flood, 100000);
271
+ limits.max = Math.min(limits.max, limits.flood);
272
+ return limits;
273
+ };
274
+ // Checked once, so a bad rule fails at startup rather than on a request.
265
275
  for (const rule of rules) {
266
- const limits = { ...profileRate, ...rateOverrides(rule.RATE_LIMIT || rule.rate_limit || {}) };
267
- if (!(limits.window > 0) || !(limits.max > 0) || limits.flood < limits.max || limits.flood > 100000) {
276
+ const limits = effectiveRate(rateOverrides(rule.RATE_LIMIT || rule.rate_limit || {}));
277
+ if (Object.keys(limits).length && (!(limits.window > 0) || !(limits.max > 0))) {
268
278
  throw new Error(`Invalid RATE_LIMIT for path rule ${JSON.stringify(rule.PREFIX ?? rule.prefix)}`);
269
279
  }
270
280
  }
271
281
  const routePlan = req => {
272
282
  const meta = req.aiwafRoute || {};
273
283
  const plan = createRoutePlan(String(req.path || req.url || '/').split('?')[0], rules, meta);
274
- return { plan, disabled: ALL_MIDDLEWARES.filter(name => !plan.shouldApply(name)), rate: rateOverrides(plan.getOverrides('RATE_LIMIT')) };
284
+ return { plan, disabled: ALL_MIDDLEWARES.filter(name => !plan.shouldApply(name)), rate: effectiveRate(rateOverrides(plan.getOverrides('RATE_LIMIT'))) };
275
285
  };
276
286
  if (!Object.hasOwn(profile, 'blocklist') && Object.hasOwn(profile, 'blacklist')) profile.blocklist = profile.blacklist;
277
287
  delete profile.blacklist;
@@ -537,4 +547,5 @@ module.exports = async function createNativeMiddleware(options = {}) {
537
547
  module.exports.DEFER_BODY = DEFER_BODY;
538
548
  module.exports.regularStores = regularStores;
539
549
  module.exports.recentAnswers = recentAnswers;
550
+ module.exports.rateOverrides = rateOverrides;
540
551
  module.exports.redisRateCounter = require('./nativeRateCounter').redisRateCounter;
@@ -19,6 +19,32 @@ const SHIPPED_MODEL_SHA256 = '56254f9bdeba0f96bed3c72ce88ed9f1e5ad552d7510c84742
19
19
  const SHIPPED_MODEL = path.join(__dirname, '..', 'resources', 'model.json');
20
20
 
21
21
  /** What the regular middleware would load as its anomaly model, read without loading it. */
22
+ /** Path rules whose rate limits the native engine can apply; the others are reported. */
23
+ function nativePathRules(rules, note) {
24
+ if (rules == null) return [];
25
+ if (!Array.isArray(rules)) {
26
+ note('AIWAF_PATH_RULES', 'not carried', 'It isn\'t a list of rules.');
27
+ return [];
28
+ }
29
+ const { rateOverrides } = require('./nativePipeline');
30
+ return rules.flatMap(rule => {
31
+ if (!rule || typeof rule !== 'object' || Array.isArray(rule)) {
32
+ note('AIWAF_PATH_RULES', 'not carried', `A path rule must be an object, not ${JSON.stringify(rule)}.`);
33
+ return [];
34
+ }
35
+ let reason = null;
36
+ try {
37
+ const limits = rateOverrides(rule.RATE_LIMIT || rule.rate_limit || {});
38
+ if ((limits.window !== undefined && !(limits.window > 0)) || (limits.max !== undefined && !(limits.max > 0))
39
+ || (limits.flood !== undefined && !(limits.flood > 0))) reason = 'the native pipeline needs a positive window and limits';
40
+ } catch (error) { reason = error.message; }
41
+ if (!reason) return [rule];
42
+ note('AIWAF_PATH_RULES', 'not carried', `The RATE_LIMIT for ${JSON.stringify(rule.PREFIX ?? rule.prefix)} isn't used natively: ${reason}.`);
43
+ const { RATE_LIMIT: _a, rate_limit: _b, ...rest } = rule;
44
+ return [rest];
45
+ });
46
+ }
47
+
22
48
  function settingsModel(opts) {
23
49
  if ((opts.AIWAF_MODEL_STORAGE || 'file') !== 'file') return { kind: 'storage' };
24
50
  const file = opts.AIWAF_MODEL_PATH || SHIPPED_MODEL;
@@ -96,24 +122,46 @@ function nativeOptionsFromSettings(rawOpts = {}) {
96
122
  profile.rate_window = opts.WINDOW_SEC;
97
123
  profile.rate_max = opts.MAX_REQ;
98
124
  profile.rate_flood = opts.FLOOD_REQ;
99
- if (profile.rate_flood < profile.rate_max) {
125
+ // Values the native engine can't take are reported and left at its defaults. A count over a
126
+ // fractional limit is the same as over its whole part, as the regular comparisons work.
127
+ const unusable = (key, setting, reason) => {
128
+ delete profile[key];
129
+ note(setting, 'not carried', `The native pipeline needs ${reason}, so its default applies.`);
130
+ };
131
+ if (!(Number(profile.rate_window) > 0)) unusable('rate_window', 'WINDOW_SEC', 'a positive window');
132
+ for (const [key, setting] of [['rate_max', 'MAX_REQ'], ['rate_flood', 'FLOOD_REQ']]) {
133
+ if (Number.isFinite(Number(profile[key])) && Math.floor(profile[key]) >= 1) profile[key] = Math.floor(profile[key]);
134
+ else unusable(key, setting, 'a limit of at least 1');
135
+ }
136
+ if (profile.rate_max !== undefined && profile.rate_flood !== undefined && profile.rate_flood < profile.rate_max) {
100
137
  profile.rate_max = profile.rate_flood;
101
- note('MAX_REQ', 'changed', `It's above FLOOD_REQ (${profile.rate_flood}), so requests were flood-blocked first. The native limit is ${profile.rate_flood}.`);
138
+ note('MAX_REQ', 'carried', `It's above FLOOD_REQ (${profile.rate_flood}), so requests are flood-blocked first. The native limit is ${profile.rate_flood}, which blocks at the same point.`);
102
139
  }
103
140
  if (profile.rate_flood > 100000) {
104
141
  profile.rate_flood = 100000;
105
142
  note('FLOOD_REQ', 'changed', 'The native flood threshold is at most 100000.');
106
143
  }
107
- profile.min_form_time = opts.AIWAF_MIN_FORM_TIME;
144
+ // A negative minimum form time never blocks, as 0 doesn't.
145
+ profile.min_form_time = Number.isFinite(Number(opts.AIWAF_MIN_FORM_TIME)) ? Math.max(0, Number(opts.AIWAF_MIN_FORM_TIME)) : 1;
108
146
  if (opts.AIWAF_MAX_PAGE_TIME > 0) profile.max_page_time = opts.AIWAF_MAX_PAGE_TIME;
109
147
  else note('AIWAF_MAX_PAGE_TIME', 'not carried', 'The native page expiry must be positive, so its default applies.');
110
148
  profile.honeypot_field = opts.HONEYPOT_FIELD ? String(opts.HONEYPOT_FIELD) : '';
111
149
  profile.allowed_methods = opts.AIWAF_METHOD_POLICY_ENABLED === true
112
150
  ? (opts.AIWAF_ALLOWED_METHODS || []).map(method => String(method).toUpperCase()) : [];
113
- profile.static_keywords = [...(opts.staticKeywords || [])].map(String);
151
+ const list = (value, setting) => {
152
+ if (value == null) return [];
153
+ if (Array.isArray(value)) return value.map(String);
154
+ if (typeof value === 'string') return value.split(',').map(item => item.trim()).filter(Boolean);
155
+ note(setting, 'not carried', 'It isn\'t a list, so the native default applies.');
156
+ return null;
157
+ };
158
+ const keywords = list(opts.staticKeywords, 'staticKeywords');
159
+ if (keywords) profile.static_keywords = keywords;
114
160
  profile.learning = opts.AIWAF_ENABLE_KEYWORD_LEARNING !== false;
115
- profile.geo_allow = [...(opts.AIWAF_GEO_ALLOW_COUNTRIES || [])];
116
- profile.geo_block = [...(opts.AIWAF_GEO_BLOCK_COUNTRIES || [])];
161
+ for (const [key, setting] of [['geo_allow', 'AIWAF_GEO_ALLOW_COUNTRIES'], ['geo_block', 'AIWAF_GEO_BLOCK_COUNTRIES']]) {
162
+ const countries = list(opts[setting], setting);
163
+ if (countries) profile[key] = countries;
164
+ }
117
165
  const required = opts.AIWAF_REQUIRED_HEADERS || [];
118
166
  if (required && typeof required === 'object' && !Array.isArray(required)) {
119
167
  profile.required_headers = (required.DEFAULT || []).map(headerName);
@@ -122,9 +170,17 @@ function nativeOptionsFromSettings(rawOpts = {}) {
122
170
  profile.required_headers = [].concat(required).map(headerName);
123
171
  }
124
172
  // With no required headers, the regular check also skips the quality score.
125
- profile.header_min_score = profile.required_headers.length ? opts.AIWAF_HEADER_QUALITY_MIN_SCORE : 0;
126
- profile.sql_mode = String(rawOpts.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').toLowerCase();
173
+ // Scores are whole numbers, so a fractional minimum is the next whole one.
174
+ const minScore = Number(opts.AIWAF_HEADER_QUALITY_MIN_SCORE);
175
+ if (!profile.required_headers.length) profile.header_min_score = 0;
176
+ else if (Number.isFinite(minScore) && Math.abs(minScore) < 2 ** 31) profile.header_min_score = Math.ceil(minScore);
177
+ else note('AIWAF_HEADER_QUALITY_MIN_SCORE', 'not carried', 'It isn\'t a usable score, so the native default applies.');
178
+ profile.sql_mode = String(rawOpts.AIWAF_SQL_INJECTION_MODE ?? process.env.AIWAF_SQL_INJECTION_MODE ?? 'block').trim().toLowerCase();
179
+ if (!['block', 'monitor', 'off'].includes(profile.sql_mode)) unusable('sql_mode', 'AIWAF_SQL_INJECTION_MODE', 'block, monitor or off');
127
180
  profile.max_bytes = Number(rawOpts.AIWAF_PAYLOAD_MAX_BYTES ?? process.env.AIWAF_PAYLOAD_MAX_BYTES ?? 65536);
181
+ if (!(Number.isInteger(profile.max_bytes) && profile.max_bytes >= 1 && profile.max_bytes <= 1048576)) {
182
+ unusable('max_bytes', 'AIWAF_PAYLOAD_MAX_BYTES', 'a whole number of bytes from 1 to 1048576');
183
+ }
128
184
 
129
185
  const paths = (opts.AIWAF_EXEMPT_PATHS || []).map(String);
130
186
  profile.exempt_paths = paths.filter(path => !PATTERN.test(path));
@@ -165,10 +221,18 @@ function nativeOptionsFromSettings(rawOpts = {}) {
165
221
  rateFailureMode: opts.AIWAF_RATE_CACHE_FAILURE_MODE,
166
222
  // Resolved as the regular middleware resolves it, with its default trusted proxies.
167
223
  trustedProxies: opts.AIWAF_TRUSTED_PROXIES ?? 'default',
168
- pathRules: opts.AIWAF_PATH_RULES || [],
224
+ pathRules: nativePathRules(opts.AIWAF_PATH_RULES, note),
169
225
  manifestPath: opts.AIWAF_PATH_MANIFEST,
170
226
  injectionRiskMode: opts.AIWAF_INJECTION_RISK_MODE
171
227
  };
228
+ if (options.injectionRiskMode != null) {
229
+ const mode = String(options.injectionRiskMode).trim().toLowerCase();
230
+ if (['block', 'log', 'off'].includes(mode)) options.injectionRiskMode = mode;
231
+ else {
232
+ delete options.injectionRiskMode;
233
+ note('AIWAF_INJECTION_RISK_MODE', 'not carried', 'It must be block, log or off, so the native default applies.');
234
+ }
235
+ }
172
236
  // The regular UUID check matches one segment under uuidRoutePrefix, and asks uuidResolver.
173
237
  const uuidPrefix = rawOpts.uuidRoutePrefix || '/user';
174
238
  profile.uuid_prefix = `${String(uuidPrefix).replace(/\/+$/, '')}/`;
@@ -42,6 +42,24 @@ function knownRoutes(app) {
42
42
  .map(layer => layer.route.path);
43
43
  }
44
44
 
45
+ // An Express route path (a string, an array of them, or a RegExp) matched against a request
46
+ // path: :name is one segment (:name? optional) and * is anything. Other characters are literal.
47
+ function routeMatches(route, path) {
48
+ if (route instanceof RegExp) return route.test(path);
49
+ if (Array.isArray(route)) return route.some(item => routeMatches(item, path));
50
+ const pattern = String(route).split(/(\/?:\w+\??|\*)/).map(part => {
51
+ if (part === '*') return '.*';
52
+ const param = part.match(/^(\/?):\w+(\?)?$/);
53
+ if (param) return param[2] ? `(?:${param[1] ? '/' : ''}[^/]+)?` : `${param[1] ? '/' : ''}[^/]+`;
54
+ return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
55
+ }).join('');
56
+ try {
57
+ return new RegExp(`^${pattern}/?$`).test(path);
58
+ } catch (_) {
59
+ return false;
60
+ }
61
+ }
62
+
45
63
  function matchesKnownRoute(app, path) {
46
64
  // In proxy setups, req.app may be undefined or not have routes
47
65
  // Return true (treat as known) to skip anomaly detection on proxies
@@ -62,10 +80,7 @@ function matchesKnownRoute(app, path) {
62
80
  return true;
63
81
  }
64
82
 
65
- const result = routes.some(route => {
66
- const regex = new RegExp(`^${String(route).replace(/:\\w+/g, '[^/]+')}$`);
67
- return regex.test(path);
68
- });
83
+ const result = routes.some(route => routeMatches(route, path));
69
84
 
70
85
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
71
86
  console.error(`[AIWAF-ROUTE-CHECK] path=${path} matched=${result}`);
@@ -159,10 +174,28 @@ function automaticNative(rawOpts) {
159
174
  if (OFF.has(String(process.env.AIWAF_NATIVE_PIPELINE ?? '').trim().toLowerCase())) return null;
160
175
  const version = installedWasmVersion();
161
176
  if (!version || !atLeast(version, NATIVE_DEFAULT_WASM)) return null;
162
- const conversion = require('./nativeSettings').nativeOptionsFromSettings(rawOpts);
177
+ let conversion;
178
+ try {
179
+ conversion = require('./nativeSettings').nativeOptionsFromSettings(rawOpts);
180
+ } catch (_) {
181
+ return null; // Options the converter can't read stay with the regular middleware.
182
+ }
163
183
  return conversion.differences().length ? null : conversion;
164
184
  }
165
185
 
186
+ // Store reads fail open, as exemption checks already do: a storage outage is reported once per
187
+ // kind and requests carry on unblocked, rather than every request failing.
188
+ const reportedStoreFailures = new Set();
189
+ function storeFailed(what, error) {
190
+ if (reportedStoreFailures.has(what)) return;
191
+ reportedStoreFailures.add(what);
192
+ console.warn(`AIWAF: ${what} failed (${error && error.message}); continuing without it. This is reported once.`);
193
+ }
194
+ const isBlocked = ip => Promise.resolve().then(() => blocklistManager.isBlocked(ip))
195
+ .catch(error => { storeFailed('blocklist read', error); return false; });
196
+ const recentRequests = limit => Promise.resolve().then(() => requestLogStore.recent(limit))
197
+ .catch(error => { storeFailed('request log read', error); return []; });
198
+
166
199
  module.exports = function aiwaf(rawOpts = {}) {
167
200
  if (rawOpts.AIWAF_NATIVE_PIPELINE === false) {
168
201
  const { AIWAF_NATIVE_PIPELINE: _off, ...regularOpts } = rawOpts;
@@ -172,7 +205,7 @@ module.exports = function aiwaf(rawOpts = {}) {
172
205
  if (conversion) {
173
206
  console.info('AIWAF: using the native pipeline, since every option carries over to it. '
174
207
  + 'Set AIWAF_NATIVE_PIPELINE: false (or the environment variable) to keep the regular middleware.');
175
- rawOpts = { ...rawOpts, AIWAF_NATIVE_PIPELINE: { fromSettings: true, conversion } };
208
+ rawOpts = { ...rawOpts, AIWAF_NATIVE_PIPELINE: { fromSettings: true, conversion, automatic: rawOpts } };
176
209
  }
177
210
  }
178
211
  if (rawOpts.AIWAF_NATIVE_PIPELINE !== undefined) {
@@ -181,17 +214,30 @@ module.exports = function aiwaf(rawOpts = {}) {
181
214
  if (fromSettings) {
182
215
  // Convert the regular options passed alongside; native options given here win, as in Python.
183
216
  const { AIWAF_NATIVE_PIPELINE: _ignored, ...regular } = rawOpts;
184
- const { fromSettings: _flag, profile: overrides, conversion: converted, ...nativeOptions } = typeof native === 'object' ? native : {};
217
+ const { fromSettings: _flag, profile: overrides, conversion: converted, automatic: _automatic, ...nativeOptions } = typeof native === 'object' ? native : {};
185
218
  const conversion = converted || require('./nativeSettings').nativeOptionsFromSettings(regular);
186
219
  conversion.log(nativeOptions.logger || console);
187
220
  native = { ...conversion.options, ...nativeOptions, profile: { ...conversion.profile, ...(overrides || {}) } };
188
221
  } else if (Object.keys(rawOpts).some(key => key !== 'AIWAF_NATIVE_PIPELINE')) {
189
222
  throw new Error('Native pipeline uses a dedicated profile; do not mix legacy options');
190
223
  }
191
- const ready = require('./nativePipeline')(native);
224
+ const automatic = rawOpts.AIWAF_NATIVE_PIPELINE?.automatic;
225
+ let ready = require('./nativePipeline')(native);
226
+ if (automatic) {
227
+ // Chosen automatically: if it can't start, the regular middleware runs instead, as it
228
+ // would have without the switch. A native pipeline chosen explicitly keeps its error.
229
+ ready = ready.catch(error => {
230
+ console.warn(`AIWAF: the native pipeline couldn't start (${error.message}), so the regular middleware runs instead.`);
231
+ const regular = aiwaf({ ...automatic, AIWAF_NATIVE_PIPELINE: false });
232
+ // The native methods framework adapters call.
233
+ Object.assign(regular, { inspectBody: () => null, close: () => {}, setModel: () => {},
234
+ diagnostics: () => ({ native: false, fallback: error.message }) });
235
+ return regular;
236
+ });
237
+ }
192
238
  // Compatibility wrapper for framework adapters. Await ready during application startup.
193
- // No legacy modules are initialized and no fallback is selected on this branch.
194
- const middleware = async (req, res, next) => (await ready)(req, res, next);
239
+ // A startup failure goes to next(error) for each request instead of an unhandled rejection.
240
+ const middleware = (req, res, next) => ready.then(handler => handler(req, res, next)).catch(next);
195
241
  middleware.ready = ready;
196
242
  middleware.inspectPayload = async req => (await ready).inspectPayload(req);
197
243
  return middleware;
@@ -263,7 +309,7 @@ module.exports = function aiwaf(rawOpts = {}) {
263
309
  }
264
310
  return finding;
265
311
  };
266
- const middleware = async (req, res, next) => {
312
+ const handle = async (req, res, next) => {
267
313
  const ip = getRequestIp(req, opts.AIWAF_TRUSTED_PROXIES);
268
314
  // Geo checks and logging must judge the same address as this middleware.
269
315
  req.aiwafClientIp = ip;
@@ -292,13 +338,14 @@ module.exports = function aiwaf(rawOpts = {}) {
292
338
  }
293
339
  const routePlan = createRoutePlan(path, pathRules, req.aiwafRoute || {});
294
340
  const shouldApply = name => enabledMiddlewares.has(normalizeMiddlewareName(name)) && routePlan.shouldApply(name);
295
- const blockIp = reason => blocklistManager.block(ip, reason, {
341
+ // A block that can't be written is reported; the request is still denied.
342
+ const blockIp = reason => Promise.resolve().then(() => blocklistManager.block(ip, reason, {
296
343
  extendedRequestInfo: extractExtendedRequestInfo(req, {
297
344
  enabled: opts.AIWAF_CAPTURE_EXTENDED_REQUEST_INFO,
298
345
  maxHeaders: opts.AIWAF_EXTENDED_INFO_MAX_HEADERS,
299
346
  maxValueLength: opts.AIWAF_EXTENDED_INFO_MAX_VALUE_LENGTH
300
347
  }) || {}
301
- });
348
+ })).catch(error => { storeFailed('blocklist write', error); return false; });
302
349
 
303
350
  // Debug: Log first character of path to ensure it's being captured
304
351
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
@@ -341,7 +388,7 @@ module.exports = function aiwaf(rawOpts = {}) {
341
388
  return next();
342
389
  }
343
390
 
344
- if (shouldApply('ip_keyword_block') && await blocklistManager.isBlocked(ip)) {
391
+ if (shouldApply('ip_keyword_block') && await isBlocked(ip)) {
345
392
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
346
393
  console.error(`[AIWAF-BLOCK-BLOCKLIST] ip=${ip}`);
347
394
  }
@@ -423,7 +470,7 @@ module.exports = function aiwaf(rawOpts = {}) {
423
470
  }
424
471
 
425
472
  if (opts.AIWAF_WASM_VALIDATE_RECENT && shouldApply('ai_anomaly')) {
426
- const recentRows = await requestLogStore.recent(200);
473
+ const recentRows = await recentRequests(200);
427
474
  const recent = recentRows
428
475
  .filter(row => row.ip_address === ip)
429
476
  .map(row => ({ path: row.path, status: Number(row.status || 0) }));
@@ -473,7 +520,7 @@ module.exports = function aiwaf(rawOpts = {}) {
473
520
  if (process.env.AIWAF_DEBUG_MIDDLEWARE) {
474
521
  console.error(`[AIWAF-BLOCK-RATE] ip=${ip}`);
475
522
  }
476
- if (await blocklistManager.isBlocked(ip)) {
523
+ if (await isBlocked(ip)) {
477
524
  return deny(403, 'blocked', 'flood_or_blocklist');
478
525
  }
479
526
  return deny(429, 'too_many_requests', 'rate_limit');
@@ -526,7 +573,7 @@ module.exports = function aiwaf(rawOpts = {}) {
526
573
  if (isAnomaly && anomalyDetector.isModelSufficientlyTrained()) {
527
574
  // Analyze recent behavior before blocking.
528
575
  const now = Date.now();
529
- const recentData = (await requestLogStore.recent(5000))
576
+ const recentData = (await recentRequests(5000))
530
577
  .filter(row => row.ip_address === ip)
531
578
  .map(row => ({
532
579
  timestamp: row.created_at ? new Date(row.created_at).getTime() : now,
@@ -564,6 +611,11 @@ module.exports = function aiwaf(rawOpts = {}) {
564
611
 
565
612
  next();
566
613
  };
614
+ // Express 4 doesn't await middleware, so an error here would otherwise be an unhandled
615
+ // rejection, which ends the process, and the request would hang. It goes to next(error).
616
+ const middleware = (req, res, next) => handle(req, res, next).catch(error => {
617
+ if (!res.headersSent) next(error);
618
+ });
567
619
  middleware.inspectPayload = inspectPayload;
568
620
  return middleware;
569
621
  };
@@ -541,7 +541,13 @@ async function createRequestPipeline(profile = {}, model = null) {
541
541
  wireProfile.blacklist = wireProfile.blocklist;
542
542
  delete wireProfile.blocklist;
543
543
  }
544
- const native = new mod.NativeRequestPipeline(JSON.stringify(wireProfile));
544
+ let native;
545
+ try {
546
+ native = new mod.NativeRequestPipeline(JSON.stringify(wireProfile));
547
+ } catch (error) {
548
+ // The engine reports its startup errors as strings; give them an Error's message and stack.
549
+ throw error instanceof Error ? error : new Error(`Native pipeline: ${String(error)}`);
550
+ }
545
551
  if (['begin','finish','inspect_payload','inspect_body','set_model','clear_model','diagnostics'].some(name => typeof native[name] !== 'function')) {
546
552
  native.free();
547
553
  throw new Error('Incompatible NativeRequestPipeline API; install the matching WASM build');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiwaf",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "@babel/parser": "^7.29.2",
37
- "aiwaf-wasm": "^0.2.6",
37
+ "aiwaf-wasm": "^0.2.7",
38
38
  "express": "^4.21.2",
39
39
  "glob": "^14.0.6",
40
40
  "knex": "^2.4.2",