aiwaf 1.2.2 → 1.2.4

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,15 +39,15 @@ 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.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.
42
+ Python 1.2.5, Rust/Python 0.2.12, Node.js 1.2.4, WASM 0.2.9, and Java 1.3.8 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.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
- | WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.7` | Rust detection and model primitives for JavaScript |
50
- | Java | `io.github.aiwaf-project:aiwaf-java` | `1.3.6` | Spring MVC and Jakarta Servlet protection |
46
+ | Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.2.5` | Django, Flask, and FastAPI protection |
47
+ | Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.2.4` | Express and Node framework middleware |
48
+ | Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.12` | Native Python acceleration and JSON model inference |
49
+ | WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.9` | Rust detection and model primitives for JavaScript |
50
+ | Java | `io.github.aiwaf-project:aiwaf-java` | `1.3.8` | Spring MVC and Jakarta Servlet protection |
51
51
 
52
52
  Supported framework integrations include Django, Flask, FastAPI, Express, Fastify, Hapi, Koa, NestJS, Next.js API routes, AdonisJS, Sails.js, Spring MVC, and Jakarta Servlet.
53
53
 
@@ -91,10 +91,9 @@ If untrusted hosts can reach the application directly from your private network,
91
91
 
92
92
  ## Injection audit
93
93
 
94
- `audit` reads your source code and reports where request input can reach SQL, NoSQL,
95
- shell commands, file paths, outbound requests, code evaluation, templates or
96
- deserialization. It parses files without running them, and it doesn't change how
97
- requests are handled.
94
+ `audit` reads your source code and reports where request input can reach a dangerous
95
+ operation. It parses files without running them, and it doesn't change how requests are
96
+ handled.
98
97
 
99
98
  ```bash
100
99
  aiwaf audit path/to/app # Python
@@ -104,18 +103,57 @@ java -cp <classpath> com.aiwaf.cli.AiwafConsole audit src # Java, needs a JDK
104
103
 
105
104
  | Language | Frameworks | Parser |
106
105
  | --- | --- | --- |
107
- | Python | Django, Flask, FastAPI | `ast` |
108
- | Node.js | Express, Fastify, Hapi, Koa, NestJS, Next.js, AdonisJS, Sails | `@babel/parser` |
109
- | Java | Spring, Jakarta Servlet, JAX-RS parameters | JDK Compiler Tree API |
106
+ | Python | Django, Flask, FastAPI, Graphene, Strawberry, Ariadne, Channels, Flask-SocketIO | `ast` |
107
+ | Node.js | Express, Fastify, Hapi, Koa, NestJS, Next.js (routes and server actions), Remix, tRPC, GraphQL resolvers, AdonisJS, Sails, ws and Socket.IO | `@babel/parser` |
108
+ | Java | Spring MVC and WebFlux, Spring GraphQL, Netflix DGS, Jakarta Servlet, JAX-RS, Spring messaging and Jakarta WebSocket | JDK Compiler Tree API |
110
109
 
111
- All three accept `--format text|json`, `--output <file>`, `--include-tests` and
112
- `--fail-on-findings` and `--manifest <file>`. The exit status is 0 when the scan completes, 1 with
113
- `--fail-on-findings` when something is found, and 2 for a bad path or argument.
110
+ It reports these operations:
111
+
112
+ | Operation | Examples |
113
+ | --- | --- |
114
+ | `sql`, `nosql` | `cursor.execute`, `db.query`, `jdbcTemplate.update`, `collection.find` |
115
+ | `command` | `os.system`, `exec`, `Runtime.exec`, `ProcessBuilder` |
116
+ | `path` | `open`, `fs.readFile`, `new File`, `Path.read_text` |
117
+ | `ssrf` | `requests.get`, `fetch`, `RestTemplate` |
118
+ | `code`, `template`, `deserialization` | `eval`, `render_template_string`, `pickle.loads` |
119
+ | `xss` | text returned from a Flask view, `res.send`, `ctx.body`, `response.getWriter()` |
120
+ | `redirect` | `redirect`, `res.redirect`, `sendRedirect` |
121
+ | `ldap`, `xpath` | `conn.search`, `client.search`, `xpath`, `XPath.evaluate` |
122
+ | `xxe` | XML parsers with external entities turned on |
123
+ | `redos` | regular expressions built from input |
124
+ | `prototype` (Node.js) | `obj[key] = value` with a key from input, `_.merge` |
125
+
126
+ It follows input through helpers, return values, other files and classes, objects that
127
+ keep input in fields, middleware that keeps input on the request, and callbacks such as
128
+ `.then()` and `.map()`. It understands checks: `if not name.isalnum(): return`, allowlists,
129
+ regex tests and `'..'` checks make a value safe, and encoders such as `html.escape` make
130
+ it safe only for what they encode for (HTML, not SQL). Values decided before the program
131
+ runs, dict keys and list positions are followed, so `m['safe']` isn't confused with
132
+ `m['input']`.
133
+
134
+ On the [OWASP Benchmark](https://owasp.org/www-project-benchmark/), whose labelled test
135
+ cases are real vulnerabilities or safe look-alikes, the Java audit finds every one of
136
+ 1,572 injection cases with no false alarms, and the Python audit every one of 677
137
+ (scores of +100 on OWASP's scale). The benchmarks are small synthetic cases, so this isn't
138
+ proof of the same on real applications; `scripts/audit_benchmark.py` repeats the
139
+ measurement on a checkout of either.
140
+
141
+ All three accept `--format text|json|sarif`, `--output <file>`, `--include-tests`,
142
+ `--fail-on-findings`, `--manifest <file>` and `--baseline <file>`. The exit status is 0
143
+ when the scan completes, 1 with `--fail-on-findings` when something is found, and 2 for a
144
+ bad path or argument.
145
+
146
+ - `--format sarif` writes SARIF 2.1.0, which GitHub code scanning and other tools read.
147
+ - `--baseline report.json` leaves out findings already in an earlier JSON report, so CI
148
+ fails only on new ones. Findings match by file, operation, call, function and input,
149
+ not line, so moved code still matches.
150
+ - A comment `aiwaf: ignore` on a finding's line or the line above leaves it out, and
151
+ `aiwaf: ignore[sql, xss]` leaves out only those operations. The report counts them.
114
152
 
115
153
  A finding is a path worth reading, not a confirmed vulnerability. A reverse proxy, for
116
154
  example, will report its upstream request because forwarding input is its job. A clean
117
- report doesn't prove the code is safe: input that crosses files, classes or dynamic
118
- calls can be missed, because helpers are only followed within one file or class.
155
+ report doesn't prove the code is safe: reflection, dynamic calls and library code can be
156
+ missed, and helpers are followed three calls deep.
119
157
 
120
158
  Java can also build a route manifest from source, without starting the application.
121
159
  This is how plain Servlet applications get a manifest:
@@ -256,7 +294,7 @@ pip install "aiwaf[django]"
256
294
  pip install "aiwaf[flask]"
257
295
  pip install "aiwaf[fastapi]"
258
296
 
259
- # Backward-compatible alias; Python 1.2.2 already installs aiwaf-rust
297
+ # Backward-compatible alias; Python 1.2.5 already installs aiwaf-rust
260
298
  pip install "aiwaf[rust]"
261
299
 
262
300
  # Node.js middleware
@@ -266,13 +304,13 @@ npm install aiwaf
266
304
  npm install aiwaf-wasm
267
305
  ```
268
306
 
269
- Java 1.3.6, after it is published to Maven Central:
307
+ Java 1.3.8, after it is published to Maven Central:
270
308
 
271
309
  ```xml
272
310
  <dependency>
273
311
  <groupId>io.github.aiwaf-project</groupId>
274
312
  <artifactId>aiwaf-java</artifactId>
275
- <version>1.3.6</version>
313
+ <version>1.3.8</version>
276
314
  </dependency>
277
315
  ```
278
316
 
@@ -280,7 +318,7 @@ Java 1.3.6, after it is published to Maven Central:
280
318
 
281
319
  The Python package requires Python 3.10 or newer. Framework dependencies are optional, so install only the extra needed by the application.
282
320
 
283
- Python 1.2.2 requires `aiwaf-rust>=0.2.10`; the `rust` extra remains an installation
321
+ Python 1.2.5 requires `aiwaf-rust>=0.2.12`; the `rust` extra remains an installation
284
322
  alias. Publish the matching Rust wheel with `NativeCSVPipeline` support before
285
323
  the Python release. The Rust release workflow builds Linux x86_64/aarch64,
286
324
  musl x86_64, macOS x86_64/arm64 and Windows x86_64 wheels and checks the native
@@ -945,9 +983,13 @@ The low-level `CSVStorage` key/value class remains available for explicit use,
945
983
  but framework CSV initialization selects `PolicyCSVStorage`.
946
984
 
947
985
  FastAPI also exposes `aiwaf.fast.trainer.train_from_logs(app, ...)`. Training
948
- refreshes learned keywords and can write a Rust JSON model artifact. Existing
949
- anomaly middleware instances require an explicit model reload or application
950
- restart to use the newly trained model.
986
+ refreshes learned keywords and can write a Rust JSON model artifact. Both
987
+ regular and native middleware load that artifact at startup when
988
+ `config.set("ai_anomaly.model_path", "/path/to/model.json")` is configured
989
+ (`AIWAF_MODEL_PATH` is also accepted). The trainer uses the same configured path
990
+ unless `model_path` is supplied explicitly. Restart the application after
991
+ retraining to load the new model. Missing or invalid files produce a warning
992
+ and leave model scoring disabled.
951
993
 
952
994
  ## JavaScript package
953
995
 
@@ -1099,7 +1141,7 @@ existence to `Boolean(req.route)`. Supply accurate facts when the firewall runs
1099
1141
  before Express resolves routes. Country headers are not implicitly trusted.
1100
1142
 
1101
1143
  **`aiwaf(options)` runs the native pipeline by default** when two things hold: the
1102
- installed aiwaf-wasm is 0.2.7 or newer (it has every native feature), and every option
1144
+ installed aiwaf-wasm is 0.2.9 or newer (it has every native feature), and every option
1103
1145
  carries over exactly, so the conversion report below lists no differences. Otherwise it
1104
1146
  runs the regular middleware, as before. It logs one line when it picks the native
1105
1147
  pipeline. To keep the regular middleware, set `AIWAF_NATIVE_PIPELINE: false` in the
@@ -1346,7 +1388,7 @@ cp -R ../licenses crates/aiwaf_wasm/pkg/
1346
1388
 
1347
1389
  ## Java package
1348
1390
 
1349
- AIWAF Java 1.3.6 targets Java 17, Spring Framework 7.0, and Jakarta Servlet 6.1. It is a native Java implementation and does not load the Rust library.
1391
+ AIWAF Java 1.3.8 targets Java 17, Spring Framework 7.0, and Jakarta Servlet 6.1. It is a native Java implementation and does not load the Rust library.
1350
1392
 
1351
1393
  ### Core engine
1352
1394
 
@@ -1435,7 +1477,7 @@ UUID protection uses Python-compatible weighted signals: malformed input, valid
1435
1477
  Generate a route manifest from the live Spring application rather than supplying controller methods manually:
1436
1478
 
1437
1479
  ```bash
1438
- java -cp "your-app.jar:aiwaf-java-1.3.6.jar" \
1480
+ java -cp "your-app.jar:aiwaf-java-1.3.8.jar" \
1439
1481
  com.aiwaf.cli.AiwafConsole init \
1440
1482
  --app com.example.Application \
1441
1483
  --output .aiwaf/paths.json
@@ -1631,14 +1673,11 @@ python aiwaf_test.py --python-only
1631
1673
  python aiwaf_test.py --rust-only
1632
1674
  python aiwaf_test.py --js-only
1633
1675
  python aiwaf_test.py --wasm-only
1676
+ python aiwaf_test.py --java-only
1634
1677
  ```
1635
1678
 
1636
- Java is tested separately:
1637
-
1638
- ```bash
1639
- cd java
1640
- mvn test
1641
- ```
1679
+ Full runs include the Java suite, which needs a JDK 17 or newer and Maven. Use `--no-java`
1680
+ to skip it on a machine without them, or run it directly with `mvn -f java/pom.xml test`.
1642
1681
 
1643
1682
  ### Direct package commands
1644
1683
 
@@ -1666,11 +1705,11 @@ Release versions and tags must match the relevant manifest.
1666
1705
 
1667
1706
  | Package | Manifest | Tag | Workflow |
1668
1707
  | --- | --- | --- | --- |
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
- | npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.7` | `wasm-publish.yml` |
1673
- | Maven `aiwaf-java` | `java/pom.xml` | `java-v1.3.6` | `java-publish.yml` |
1708
+ | Python `aiwaf` | `pyproject.toml` | `python-v1.2.5` | `python-publish.yml` |
1709
+ | npm `aiwaf` | `js/package.json` | `js-v1.2.4` | `npm-publish.yml` |
1710
+ | PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.12` | `rust-publish.yml` |
1711
+ | npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.9` | `wasm-publish.yml` |
1712
+ | Maven `aiwaf-java` | `java/pom.xml` | `java-v1.3.8` | `java-publish.yml` |
1674
1713
 
1675
1714
  Python and Rust publish to PyPI with trusted publishing. The npm workflows use npm trusted publishing and stage packages for approval. Configure the trusted publisher with organization `aiwaf-project`, repository `aiwaf`, the exact workflow filename, and the environment used by that workflow.
1676
1715
 
@@ -1678,11 +1717,12 @@ Java publishing uses the protected `maven-publish` environment plus `GPG_PRIVATE
1678
1717
 
1679
1718
  Registry releases are immutable. Increment the relevant manifest version before publishing another release.
1680
1719
 
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
1685
- 1.3.6, which is already published.
1720
+ This release is Python `aiwaf 1.2.5`, npm `aiwaf 1.2.4` and Java `aiwaf-java 1.3.8`, with
1721
+ the injection audit changes. Python 1.2.4, Java 1.3.7, `aiwaf-rust 0.2.12` and
1722
+ `aiwaf-wasm 0.2.9` are already published, and the engines are unchanged. Python now requires
1723
+ `aiwaf-rust>=0.2.12` and npm `aiwaf` `aiwaf-wasm ^0.2.9`, so every native feature is available
1724
+ after an install. npm `aiwaf` 1.2.3 was staged but never released, and npm doesn't reuse a
1725
+ version, so npm `aiwaf 1.2.4` also ships the Node.js changes listed under Python 1.2.4.
1686
1726
 
1687
1727
  ## Security and limitations
1688
1728
 
@@ -187,6 +187,12 @@ async function analyzeRecentBehaviorAccelerated(recentData = []) {
187
187
  }
188
188
 
189
189
  module.exports = {
190
+ /** Whether the regular anomaly check would use its model: AIWAF_MIN_AI_LOGS recent logs, counted now. */
191
+ async logsSufficient(opts = {}) {
192
+ const minimum = Number.isFinite(Number(opts.AIWAF_MIN_AI_LOGS)) ? Number(opts.AIWAF_MIN_AI_LOGS) : 10000;
193
+ return minimum <= 0 || await countRecentDbLogs(30) >= minimum;
194
+ },
195
+
190
196
  async init(opts = {}) {
191
197
  minAiLogs = Number.isFinite(Number(opts.AIWAF_MIN_AI_LOGS))
192
198
  ? Number(opts.AIWAF_MIN_AI_LOGS)
package/lib/csvStore.js CHANGED
@@ -66,6 +66,52 @@ function readRows(filePath, headers) {
66
66
  return rows;
67
67
  }
68
68
 
69
+ // The last `limit` rows of an append-only CSV, newest last, read from the end of the file so
70
+ // the cost doesn't grow with the file. Rows are one per line, as appendRow writes them.
71
+ function readTailRows(filePath, headers, limit) {
72
+ if (!fs.existsSync(filePath) || !(limit > 0)) return [];
73
+ const fd = fs.openSync(filePath, 'r');
74
+ try {
75
+ const size = fs.fstatSync(fd).size;
76
+ if (!size) return [];
77
+ const chunk = 64 * 1024;
78
+ // The header row decides the column order.
79
+ const head = Buffer.alloc(Math.min(chunk, size));
80
+ fs.readSync(fd, head, 0, head.length, 0);
81
+ const firstLine = head.toString('utf8').split(/\r?\n/)[0];
82
+ const fileHeader = parseCsvLine(firstLine);
83
+ const hasHeader = fileHeader.some(header => headers.includes(header));
84
+ const sourceHeaders = hasHeader ? fileHeader : headers;
85
+ const headerBytes = hasHeader ? Buffer.byteLength(firstLine) + 1 : 0;
86
+ // Read backwards until enough complete lines are in hand, or the header is reached.
87
+ let position = size;
88
+ let pieces = [];
89
+ let lines = [];
90
+ while (position > headerBytes) {
91
+ const start = Math.max(headerBytes, position - chunk);
92
+ const piece = Buffer.alloc(position - start);
93
+ fs.readSync(fd, piece, 0, piece.length, start);
94
+ pieces.unshift(piece);
95
+ position = start;
96
+ lines = Buffer.concat(pieces).toString('utf8').split(/\r?\n/);
97
+ // The first line may be cut off unless the read reached the header.
98
+ if (position > headerBytes) lines = lines.slice(1);
99
+ if (lines.filter(Boolean).length > limit) break;
100
+ }
101
+ return lines.filter(Boolean).slice(-limit).map(line => {
102
+ const cells = parseCsvLine(line);
103
+ const row = {};
104
+ headers.forEach(header => {
105
+ const index = sourceHeaders.indexOf(header);
106
+ row[header] = index >= 0 ? (cells[index] ?? '') : '';
107
+ });
108
+ return row;
109
+ });
110
+ } finally {
111
+ fs.closeSync(fd);
112
+ }
113
+ }
114
+
69
115
  function writeRows(filePath, headers, rows) {
70
116
  ensureDir(filePath);
71
117
  const lines = [headers.join(',')];
@@ -127,6 +173,7 @@ function nextId(rows) {
127
173
 
128
174
  module.exports = {
129
175
  readRows,
176
+ readTailRows,
130
177
  writeRows,
131
178
  appendRow,
132
179
  updateRows,
@@ -47,7 +47,7 @@ module.exports = {
47
47
  const normalizedLimit = Number(limit) > 0 ? Number(limit) : 1000;
48
48
  if (await initialize()) {
49
49
  try {
50
- return db('dynamic_keywords')
50
+ return await db('dynamic_keywords')
51
51
  .select('*')
52
52
  .orderBy('count', 'desc')
53
53
  .limit(normalizedLimit);
@@ -85,7 +85,7 @@ module.exports = {
85
85
  const normalized = String(ip || '').trim();
86
86
  if (await initialize()) {
87
87
  try {
88
- return db('ip_exemptions').where('ip_address', normalized).del();
88
+ return await db('ip_exemptions').where('ip_address', normalized).del();
89
89
  } catch (err) {
90
90
  dbAvailable = false;
91
91
  }
@@ -100,7 +100,7 @@ module.exports = {
100
100
  async listIps() {
101
101
  if (await initialize()) {
102
102
  try {
103
- return db('ip_exemptions').select('*').orderBy('created_at', 'desc');
103
+ return await db('ip_exemptions').select('*').orderBy('created_at', 'desc');
104
104
  } catch (err) {
105
105
  dbAvailable = false;
106
106
  }
@@ -146,7 +146,7 @@ module.exports = {
146
146
  const normalized = String(pathPrefix || '').trim();
147
147
  if (await initialize()) {
148
148
  try {
149
- return db('path_exemptions').where('path_prefix', normalized).del();
149
+ return await db('path_exemptions').where('path_prefix', normalized).del();
150
150
  } catch (err) {
151
151
  dbAvailable = false;
152
152
  }
@@ -161,7 +161,7 @@ module.exports = {
161
161
  async listPaths() {
162
162
  if (await initialize()) {
163
163
  try {
164
- return db('path_exemptions').select('*').orderBy('created_at', 'desc');
164
+ return await db('path_exemptions').select('*').orderBy('created_at', 'desc');
165
165
  } catch (err) {
166
166
  dbAvailable = false;
167
167
  }
package/lib/geoBlocker.js CHANGED
@@ -92,7 +92,65 @@ function tryLoadMmdbReader(mmdbPath) {
92
92
  }
93
93
  }
94
94
 
95
+ function mmdbPath(opts) {
96
+ const packagedDefault = path.resolve(__dirname, '..', 'geolock', 'ipinfo_lite.mmdb');
97
+ const monorepoDefault = path.resolve(__dirname, '..', '..', 'py', 'aiwaf', 'core', 'geolock', 'ipinfo_lite.mmdb');
98
+ return opts.AIWAF_GEO_MMDB_PATH
99
+ ? path.resolve(opts.AIWAF_GEO_MMDB_PATH)
100
+ : (fs.existsSync(packagedDefault) ? packagedDefault : monorepoDefault);
101
+ }
102
+
103
+ /**
104
+ * A country lookup for the native pipeline, resolving as the regular geo check does: the
105
+ * app's geoResolver when there is one (its promise is returned), otherwise the MMDB database,
106
+ * then the x-country-code header, cached per address for AIWAF_GEO_CACHE_SECONDS.
107
+ */
108
+ function createCountryLookup(opts = {}, trustedProxies, resolver = null) {
109
+ // Opened on the first lookup, so converting options alone doesn't open the database.
110
+ let reader;
111
+ const cacheSeconds = Number.isFinite(Number(opts.AIWAF_GEO_CACHE_SECONDS)) ? Number(opts.AIWAF_GEO_CACHE_SECONDS) : 3600;
112
+ const cache = new Map();
113
+ const remember = (ip, country) => {
114
+ if (!ip || !country || cacheSeconds <= 0) return country;
115
+ // Bounded: a flood of new addresses drops the oldest entries instead of growing forever.
116
+ if (cache.size >= 50000) cache.delete(cache.keys().next().value);
117
+ cache.set(ip, { country, expiresAt: Date.now() + cacheSeconds * 1000 });
118
+ return country;
119
+ };
120
+ return req => {
121
+ const ip = getRequestIp(req, trustedProxies);
122
+ const entry = ip && cache.get(ip);
123
+ if (entry) {
124
+ if (Date.now() <= entry.expiresAt) return entry.country;
125
+ cache.delete(ip);
126
+ }
127
+ if (typeof resolver === 'function') {
128
+ // As the regular check: the app's resolver alone, which may be asynchronous; a failure finds
129
+ // no country.
130
+ const settle = value => remember(ip, normalizeCountry(value));
131
+ try {
132
+ const result = resolver(req);
133
+ return result && typeof result.then === 'function' ? result.then(settle, () => '') : settle(result);
134
+ } catch (_) {
135
+ return '';
136
+ }
137
+ }
138
+ if (reader === undefined) reader = tryLoadMmdbReader(mmdbPath(opts));
139
+ if (reader && ip) {
140
+ try {
141
+ const result = reader.get(ip);
142
+ const country = normalizeCountry(result?.country?.iso_code || result?.registered_country?.iso_code);
143
+ if (country) return remember(ip, country);
144
+ } catch (_) {
145
+ // Fall through to the header, as the regular check does.
146
+ }
147
+ }
148
+ return remember(ip, normalizeCountry(req.headers?.['x-country-code']));
149
+ };
150
+ }
151
+
95
152
  module.exports = {
153
+ createCountryLookup,
96
154
  init(opts = {}) {
97
155
  const packagedDefault = path.resolve(__dirname, '..', 'geolock', 'ipinfo_lite.mmdb');
98
156
  const monorepoDefault = path.resolve(
package/lib/geoStore.js CHANGED
@@ -71,7 +71,7 @@ module.exports = {
71
71
 
72
72
  if (await initialize()) {
73
73
  try {
74
- return db('geo_blocked_countries').where('country_code', normalized).del();
74
+ return await db('geo_blocked_countries').where('country_code', normalized).del();
75
75
  } catch (err) {
76
76
  dbAvailable = false;
77
77
  }
@@ -86,7 +86,7 @@ module.exports = {
86
86
  async listBlockedCountries() {
87
87
  if (await initialize()) {
88
88
  try {
89
- return db('geo_blocked_countries').select('*').orderBy('country_code', 'asc');
89
+ return await db('geo_blocked_countries').select('*').orderBy('country_code', 'asc');
90
90
  } catch (err) {
91
91
  dbAvailable = false;
92
92
  }
@@ -156,17 +156,36 @@ function calculateHeaderQuality(headers) {
156
156
  return score;
157
157
  }
158
158
 
159
+ function toRegexList(items, fallback) {
160
+ if (!items) return fallback;
161
+ if (!Array.isArray(items)) return fallback;
162
+ return items.map(item => {
163
+ if (item instanceof RegExp) return item;
164
+ return new RegExp(String(item), 'i');
165
+ });
166
+ }
167
+
168
+ /**
169
+ * The regular check's verdict on a User-Agent from the app's lists (or the defaults), for the
170
+ * native pipeline: "legitimate", "suspicious:<pattern>" or "" for neither. The app's own
171
+ * RegExps are tested here, in JavaScript, so their flags and syntax mean what they mean in the
172
+ * regular check.
173
+ */
174
+ function userAgentVerdict(opts = {}) {
175
+ const legitimateBots = toRegexList(opts.AIWAF_LEGITIMATE_BOTS, DEFAULT_LEGIT_BOTS);
176
+ const suspiciousUserAgents = toRegexList(opts.AIWAF_SUSPICIOUS_USER_AGENTS, DEFAULT_SUSPICIOUS_UA);
177
+ return userAgent => {
178
+ const ua = String(userAgent || '').toLowerCase();
179
+ if (legitimateBots.length && matchesPattern(legitimateBots, ua)) return 'legitimate';
180
+ const found = suspiciousUserAgents.length ? suspiciousUserAgents.find(pattern => pattern.test(ua)) : null;
181
+ return found ? `suspicious:${found.source}` : '';
182
+ };
183
+ }
184
+
159
185
  module.exports = {
186
+ userAgentVerdict,
160
187
  init(opts = {}) {
161
188
  const requiredHeaders = opts.AIWAF_REQUIRED_HEADERS || [];
162
- const toRegexList = (items, fallback) => {
163
- if (!items) return fallback;
164
- if (!Array.isArray(items)) return fallback;
165
- return items.map(item => {
166
- if (item instanceof RegExp) return item;
167
- return new RegExp(String(item), 'i');
168
- });
169
- };
170
189
  config = {
171
190
  enabled: !!opts.AIWAF_HEADER_VALIDATION,
172
191
  requiredHeaders: Array.isArray(requiredHeaders)
@@ -266,7 +285,8 @@ module.exports = {
266
285
  }
267
286
  return {
268
287
  requiredHeaders: Array.isArray(requiredHeaders) ? requiredHeaders : [],
269
- minScore: (Array.isArray(requiredHeaders) && requiredHeaders.length === 0) ? 0 : config.minScore
288
+ minScore: (Array.isArray(requiredHeaders) && requiredHeaders.length === 0) ? 0 : config.minScore,
289
+ maxUserAgentLength: config.maxUserAgentLength
270
290
  };
271
291
  },
272
292
  isStaticRequest(pathname) {
@@ -0,0 +1 @@
1
+ module.exports = { loginPathPrefixes: Object.freeze(['/admin/login/', '/login/', '/accounts/login/', '/auth/login/', '/signin/']) };
@@ -1,14 +1,10 @@
1
+ const { loginPathPrefixes } = require('./honeypotDefaults');
2
+
1
3
  let config = {
2
4
  field: undefined,
3
5
  minFormTimeMs: 0,
4
6
  maxPageTimeMs: 3600 * 1000,
5
- loginPathPrefixes: [
6
- '/admin/login/',
7
- '/login/',
8
- '/accounts/login/',
9
- '/auth/login/',
10
- '/signin/'
11
- ],
7
+ loginPathPrefixes: [...loginPathPrefixes],
12
8
  postOnlySuffixes: [
13
9
  '/create/',
14
10
  '/submit/',
@@ -42,7 +38,7 @@ module.exports = {
42
38
  field: opts.HONEYPOT_FIELD,
43
39
  minFormTimeMs: Math.max(0, Number(opts.AIWAF_MIN_FORM_TIME || 0) * 1000),
44
40
  maxPageTimeMs: Math.max(0, Number(opts.AIWAF_MAX_PAGE_TIME || 3600) * 1000),
45
- loginPathPrefixes: (opts.AIWAF_LOGIN_PATH_PREFIXES || config.loginPathPrefixes).map(p => String(p)),
41
+ loginPathPrefixes: (opts.AIWAF_LOGIN_PATH_PREFIXES || loginPathPrefixes).map(p => String(p)),
46
42
  postOnlySuffixes: (opts.AIWAF_POST_ONLY_SUFFIXES || config.postOnlySuffixes).map(p => String(p)),
47
43
  allowedMethods: (opts.AIWAF_ALLOWED_METHODS || config.allowedMethods).map(m => String(m).toUpperCase()),
48
44
  methodPolicyEnabled: opts.AIWAF_METHOD_POLICY_ENABLED === true