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.
@@ -96,8 +96,8 @@ module.exports = {
96
96
  }
97
97
  }
98
98
 
99
- const current = rows();
100
- csvStore.appendRow(csvPath, headers, { id: csvStore.nextId(current), ...payload });
99
+ // IDs only increase, so the last row gives the next one without reading the whole log.
100
+ csvStore.appendRow(csvPath, headers, { id: csvStore.nextId(csvStore.readTailRows(csvPath, headers, 1)), ...payload });
101
101
  },
102
102
 
103
103
  async recent(limit = 5000) {
@@ -105,15 +105,15 @@ module.exports = {
105
105
 
106
106
  if (await initialize()) {
107
107
  try {
108
- return db('request_logs').select('*').orderBy('created_at', 'desc').limit(normalizedLimit);
108
+ return await db('request_logs').select('*').orderBy('created_at', 'desc').limit(normalizedLimit);
109
109
  } catch (err) {
110
110
  dbAvailable = false;
111
111
  }
112
112
  }
113
113
 
114
- return rows()
115
- .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)))
116
- .slice(0, normalizedLimit);
114
+ // The log is appended in time order, so the newest rows are its last lines.
115
+ return csvStore.readTailRows(csvPath, headers, normalizedLimit)
116
+ .sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
117
117
  },
118
118
 
119
119
  async geoSummary(limit = 25) {
@@ -121,7 +121,7 @@ module.exports = {
121
121
 
122
122
  if (await initialize()) {
123
123
  try {
124
- return db('request_logs')
124
+ return await db('request_logs')
125
125
  .select('country')
126
126
  .count({ requests: '*' })
127
127
  .sum({ blocked_count: db.raw('CASE WHEN blocked THEN 1 ELSE 0 END') })
@@ -1,3 +1,5 @@
1
+ const { loginPathPrefixes } = require('./honeypotDefaults');
2
+
1
3
  function firstDefined(...values) {
2
4
  for (const value of values) {
3
5
  if (value !== undefined && value !== null) return value;
@@ -76,7 +78,7 @@ function normalizeSettings(rawOpts = {}) {
76
78
  HONEYPOT_FIELD: firstDefined(rawOpts.HONEYPOT_FIELD, rawOpts.honeypotField, legacy.honeypot?.field),
77
79
  AIWAF_MIN_FORM_TIME: toNumber(firstDefined(rawOpts.AIWAF_MIN_FORM_TIME, rawOpts.minFormTime, legacy.honeypot?.minFormTime, process.env.AIWAF_MIN_FORM_TIME), 0),
78
80
  AIWAF_MAX_PAGE_TIME: toNumber(firstDefined(rawOpts.AIWAF_MAX_PAGE_TIME, rawOpts.maxPageTime, legacy.honeypot?.maxPageTime, process.env.AIWAF_MAX_PAGE_TIME), 3600),
79
- AIWAF_LOGIN_PATH_PREFIXES: toArray(firstDefined(rawOpts.AIWAF_LOGIN_PATH_PREFIXES, rawOpts.loginPathPrefixes, legacy.honeypot?.loginPathPrefixes, process.env.AIWAF_LOGIN_PATH_PREFIXES), undefined),
81
+ AIWAF_LOGIN_PATH_PREFIXES: toArray(firstDefined(rawOpts.AIWAF_LOGIN_PATH_PREFIXES, rawOpts.loginPathPrefixes, legacy.honeypot?.loginPathPrefixes, process.env.AIWAF_LOGIN_PATH_PREFIXES), [...loginPathPrefixes]),
80
82
  AIWAF_POST_ONLY_SUFFIXES: toArray(firstDefined(rawOpts.AIWAF_POST_ONLY_SUFFIXES, rawOpts.postOnlySuffixes, legacy.honeypot?.postOnlySuffixes, process.env.AIWAF_POST_ONLY_SUFFIXES), undefined),
81
83
  AIWAF_ALLOWED_METHODS: toArray(firstDefined(rawOpts.AIWAF_ALLOWED_METHODS, rawOpts.allowedMethods, legacy.honeypot?.allowedMethods, process.env.AIWAF_ALLOWED_METHODS), undefined),
82
84
  AIWAF_METHOD_POLICY_ENABLED: toBool(firstDefined(rawOpts.AIWAF_METHOD_POLICY_ENABLED, rawOpts.methodPolicyEnabled, legacy.honeypot?.methodPolicyEnabled, process.env.AIWAF_METHOD_POLICY_ENABLED), false),
@@ -9,10 +9,16 @@ let config = {
9
9
  uuidResolver: null
10
10
  };
11
11
 
12
+ // The prefix is literal text: escaped, and compiled once per prefix.
13
+ let prefixPattern = { prefix: null, regex: null };
12
14
  function extractUuid(req) {
13
15
  if (req?.params?.uuid) return String(req.params.uuid);
14
16
  const path = String(req.path || req.url || '');
15
- const regex = new RegExp(`^${config.prefix}/([^/]+)$`);
17
+ if (prefixPattern.prefix !== config.prefix) {
18
+ const escaped = String(config.prefix).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
19
+ prefixPattern = { prefix: config.prefix, regex: new RegExp(`^${escaped}/([^/]+)$`) };
20
+ }
21
+ const regex = prefixPattern.regex;
16
22
  const match = path.match(regex);
17
23
  return match ? match[1] : null;
18
24
  }
@@ -44,9 +44,20 @@ function knownRoutes(app) {
44
44
 
45
45
  // An Express route path (a string, an array of them, or a RegExp) matched against a request
46
46
  // path: :name is one segment (:name? optional) and * is anything. Other characters are literal.
47
+ const compiledRoutes = new Map();
47
48
  function routeMatches(route, path) {
48
49
  if (route instanceof RegExp) return route.test(path);
49
50
  if (Array.isArray(route)) return route.some(item => routeMatches(item, path));
51
+ const key = String(route);
52
+ if (compiledRoutes.has(key)) return compiledRoutes.get(key)?.test(path) ?? false;
53
+ const regex = compileRoute(key);
54
+ if (compiledRoutes.size >= 1024) compiledRoutes.clear();
55
+ compiledRoutes.set(key, regex);
56
+ return regex ? regex.test(path) : false;
57
+ }
58
+
59
+ // null when the route can't be compiled, which then matches nothing.
60
+ function compileRoute(route) {
50
61
  const pattern = String(route).split(/(\/?:\w+\??|\*)/).map(part => {
51
62
  if (part === '*') return '.*';
52
63
  const param = part.match(/^(\/?):\w+(\?)?$/);
@@ -54,9 +65,9 @@ function routeMatches(route, path) {
54
65
  return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
55
66
  }).join('');
56
67
  try {
57
- return new RegExp(`^${pattern}/?$`).test(path);
68
+ return new RegExp(`^${pattern}/?$`);
58
69
  } catch (_) {
59
- return false;
70
+ return null;
60
71
  }
61
72
  }
62
73
 
@@ -147,7 +158,7 @@ function applyAutoMiddlewareDefaults(opts, enabled, rawOpts = {}) {
147
158
 
148
159
  // The first aiwaf-wasm with every engine feature from_settings relies on: stores, shared rate
149
160
  // counts, path-rule limits, monitor mode and UUID resolvers.
150
- const NATIVE_DEFAULT_WASM = '0.2.7';
161
+ const NATIVE_DEFAULT_WASM = '0.2.8';
151
162
 
152
163
  function installedWasmVersion() {
153
164
  const fs = require('fs');
@@ -173,14 +184,31 @@ const OFF = new Set(['false', '0', 'off', 'no']);
173
184
  function automaticNative(rawOpts) {
174
185
  if (OFF.has(String(process.env.AIWAF_NATIVE_PIPELINE ?? '').trim().toLowerCase())) return null;
175
186
  const version = installedWasmVersion();
176
- if (!version || !atLeast(version, NATIVE_DEFAULT_WASM)) return null;
187
+ if (!version) return staysRegular('aiwaf-wasm isn\'t installed (npm install aiwaf-wasm).');
188
+ if (!atLeast(version, NATIVE_DEFAULT_WASM)) {
189
+ return staysRegular(`the installed aiwaf-wasm ${version} is older than ${NATIVE_DEFAULT_WASM} (npm install aiwaf-wasm@latest).`);
190
+ }
177
191
  let conversion;
178
192
  try {
179
193
  conversion = require('./nativeSettings').nativeOptionsFromSettings(rawOpts);
180
- } catch (_) {
181
- return null; // Options the converter can't read stay with the regular middleware.
194
+ } catch (error) {
195
+ // Options the converter can't read stay with the regular middleware.
196
+ return staysRegular(`its options couldn't be converted (${error && error.message}).`);
182
197
  }
183
- return conversion.differences().length ? null : conversion;
198
+ const differences = conversion.differences();
199
+ if (!differences.length) return conversion;
200
+ return staysRegular(`these options don't carry over to it exactly:\n${differences
201
+ .map(note => `- ${note.setting}: ${note.outcome}. ${note.detail}`.trimEnd()).join('\n')}`);
202
+ }
203
+
204
+ // Why an app runs the regular middleware and not the native pipeline, said once per reason.
205
+ const reportedReasons = new Set();
206
+ function staysRegular(reason) {
207
+ if (!reportedReasons.has(reason)) {
208
+ reportedReasons.add(reason);
209
+ console.info(`AIWAF: using the regular middleware, not the native pipeline, because ${reason}`);
210
+ }
211
+ return null;
184
212
  }
185
213
 
186
214
  // Store reads fail open, as exemption checks already do: a storage outage is reported once per
@@ -218,6 +246,8 @@ module.exports = function aiwaf(rawOpts = {}) {
218
246
  const conversion = converted || require('./nativeSettings').nativeOptionsFromSettings(regular);
219
247
  conversion.log(nativeOptions.logger || console);
220
248
  native = { ...conversion.options, ...nativeOptions, profile: { ...conversion.profile, ...(overrides || {}) } };
249
+ // Chosen automatically, it runs only if it can answer exactly as the regular middleware.
250
+ if (rawOpts.AIWAF_NATIVE_PIPELINE.automatic) native.exact = true;
221
251
  } else if (Object.keys(rawOpts).some(key => key !== 'AIWAF_NATIVE_PIPELINE')) {
222
252
  throw new Error('Native pipeline uses a dedicated profile; do not mix legacy options');
223
253
  }
@@ -621,3 +651,4 @@ module.exports = function aiwaf(rawOpts = {}) {
621
651
  };
622
652
 
623
653
  module.exports.NATIVE_DEFAULT_WASM = NATIVE_DEFAULT_WASM;
654
+ module.exports.matchesKnownRoute = matchesKnownRoute;
@@ -315,7 +315,10 @@ async function validateHeaders(headers, config) {
315
315
  if (config && typeof mod.validate_headers_with_config === 'function') {
316
316
  const required = (config.requiredHeaders && config.requiredHeaders.length) ? config.requiredHeaders : null;
317
317
  const minScore = Number.isFinite(Number(config.minScore)) ? Number(config.minScore) : null;
318
- result = mod.validate_headers_with_config(headerInput, required, minScore);
318
+ // An older aiwaf-wasm takes no cap, ignores it and keeps its own 500.
319
+ const maxUserAgent = Number.isInteger(config.maxUserAgentLength) && config.maxUserAgentLength >= 0
320
+ ? config.maxUserAgentLength : undefined;
321
+ result = mod.validate_headers_with_config(headerInput, required, minScore, maxUserAgent);
319
322
  } else {
320
323
  result = mod.validate_headers(headerInput);
321
324
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiwaf",
3
- "version": "1.2.2",
3
+ "version": "1.2.3",
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.7",
37
+ "aiwaf-wasm": "^0.2.8",
38
38
  "express": "^4.21.2",
39
39
  "glob": "^14.0.6",
40
40
  "knex": "^2.4.2",