aiwaf 1.1.3 → 1.1.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,16 +39,16 @@ 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.1.5, Rust/Python 0.2.4, Node.js 1.1.3, WASM 0.2.3, and Java 1.3.3 are local release candidates; see the
42
+ Python 1.1.6, Rust/Python 0.2.5, Node.js 1.1.4, WASM 0.2.4, and Java 1.3.4 are local release candidates; see the
43
43
  [upgrade notes](docs/releases/2026-10-elv2.md).
44
44
 
45
45
  | Runtime | Package | Repository version | Primary use |
46
46
  | --- | --- | ---: | --- |
47
- | Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.1.5` | Django, Flask, and FastAPI protection |
48
- | Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.1.3` | Express and Node framework middleware |
49
- | Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.4` | Native Python acceleration and JSON model inference |
50
- | WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.3` | Rust detection and model primitives for JavaScript |
51
- | Java | `io.github.aiwaf-project:aiwaf-java` | `1.3.3` | Spring MVC and Jakarta Servlet protection |
47
+ | Python | [`aiwaf`](https://pypi.org/project/aiwaf/) | `1.1.6` | Django, Flask, and FastAPI protection |
48
+ | Node.js | [`aiwaf`](https://www.npmjs.com/package/aiwaf) | `1.1.4` | Express and Node framework middleware |
49
+ | Rust/Python | [`aiwaf-rust`](https://pypi.org/project/aiwaf-rust/) | `0.2.5` | Native Python acceleration and JSON model inference |
50
+ | WebAssembly | [`aiwaf-wasm`](https://www.npmjs.com/package/aiwaf-wasm) | `0.2.4` | Rust detection and model primitives for JavaScript |
51
+ | Java | `io.github.aiwaf-project:aiwaf-java` | `1.3.4` | Spring MVC and Jakarta Servlet protection |
52
52
 
53
53
  Supported framework integrations include Django, Flask, FastAPI, Express, Fastify, Hapi, Koa, NestJS, Next.js API routes, AdonisJS, Sails.js, Spring MVC, and Jakarta Servlet.
54
54
 
@@ -97,7 +97,7 @@ pip install "aiwaf[django]"
97
97
  pip install "aiwaf[flask]"
98
98
  pip install "aiwaf[fastapi]"
99
99
 
100
- # Backward-compatible alias; Python 1.1.5 already installs aiwaf-rust
100
+ # Backward-compatible alias; Python 1.1.6 already installs aiwaf-rust
101
101
  pip install "aiwaf[rust]"
102
102
 
103
103
  # Node.js middleware
@@ -107,13 +107,13 @@ npm install aiwaf
107
107
  npm install aiwaf-wasm
108
108
  ```
109
109
 
110
- Java 1.3.3, after it is published to Maven Central:
110
+ Java 1.3.4, after it is published to Maven Central:
111
111
 
112
112
  ```xml
113
113
  <dependency>
114
114
  <groupId>io.github.aiwaf-project</groupId>
115
115
  <artifactId>aiwaf-java</artifactId>
116
- <version>1.3.3</version>
116
+ <version>1.3.4</version>
117
117
  </dependency>
118
118
  ```
119
119
 
@@ -121,7 +121,7 @@ Java 1.3.3, after it is published to Maven Central:
121
121
 
122
122
  The Python package requires Python 3.10 or newer. Framework dependencies are optional, so install only the extra needed by the application.
123
123
 
124
- Python 1.1.5 requires `aiwaf-rust>=0.2.4`; the `rust` extra remains an installation
124
+ Python 1.1.6 requires `aiwaf-rust>=0.2.5`; the `rust` extra remains an installation
125
125
  alias. Publish the matching Rust wheel with `NativeCSVPipeline` support before
126
126
  the Python release. The Rust release workflow builds Linux x86_64/aarch64,
127
127
  musl x86_64, macOS x86_64/arm64 and Windows x86_64 wheels and checks the native
@@ -426,7 +426,7 @@ When `aiwaf_rust` is importable, supported acceleration paths are selected autom
426
426
 
427
427
  ### Rust-backed CSV runtime and training
428
428
 
429
- The Python 1.1.5 and `aiwaf-rust` 0.2.4 release candidates add native CSV storage,
429
+ The Python package and `aiwaf-rust` provide native CSV storage,
430
430
  shared policy evaluation, and training preparation for Django, Flask, and FastAPI.
431
431
  Install matching Python and Rust builds and reload application workers to activate
432
432
  the new capabilities. Older extensions retain the compatible Python fallback.
@@ -1028,7 +1028,7 @@ cp -R ../licenses crates/aiwaf_wasm/pkg/
1028
1028
 
1029
1029
  ## Java package
1030
1030
 
1031
- AIWAF Java 1.3.3 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.
1031
+ AIWAF Java 1.3.4 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.
1032
1032
 
1033
1033
  ### Core engine
1034
1034
 
@@ -1117,7 +1117,7 @@ UUID protection uses Python-compatible weighted signals: malformed input, valid
1117
1117
  Generate a route manifest from the live Spring application rather than supplying controller methods manually:
1118
1118
 
1119
1119
  ```bash
1120
- java -cp "your-app.jar:aiwaf-java-1.3.3.jar" \
1120
+ java -cp "your-app.jar:aiwaf-java-1.3.4.jar" \
1121
1121
  com.aiwaf.cli.AiwafConsole init \
1122
1122
  --app com.example.Application \
1123
1123
  --output .aiwaf/paths.json
@@ -1188,6 +1188,76 @@ mvn -Dgpg.skip=true package
1188
1188
 
1189
1189
  The build produces the main, source, and Javadoc JARs under `java/target/`. The main JAR embeds the root license as `META-INF/LICENSE`. FastR training is optional and falls back to the Java trainer when R or `jsonlite` is unavailable.
1190
1190
 
1191
+ ### Python training replay protection
1192
+
1193
+ Python 1.1.6 with aiwaf-rust 0.2.5 records the evidence used by offline training
1194
+ to block each IP. Rust computes SHA-256 receipts, locks concurrent trainers,
1195
+ and persists `training_evidence.json` in the policy data directory. Flask,
1196
+ FastAPI, and Django continue fitting models and learning keywords from history,
1197
+ but block decisions use requests that have not already been handled for that IP.
1198
+ Replaying old logs cannot extend an active block or recreate one after expiry
1199
+ or manual removal. Fresh traffic must independently satisfy the blocking rules.
1200
+
1201
+ CLI listing filters expired blocks for display without rewriting its snapshot
1202
+ back to the blacklist. This prevents concurrent training updates from being
1203
+ erased by an older cleanup snapshot. Default first blocks last 900 seconds.
1204
+
1205
+ Keep the receipt file across restarts, log rotation, and blacklist clearing.
1206
+ Receipts do not expire and grow with the distinct requests used in block
1207
+ decisions. `AIWAF_TRAINING_STATE_DIR` can select a durable shared directory;
1208
+ trainers sharing a blacklist must also share this directory. Missing native
1209
+ capabilities or corrupt receipt state stop training visibly. A crash between
1210
+ writing a block and committing its receipt can still require recovery; the two
1211
+ writes are not a single transaction.
1212
+
1213
+ Receipts start with the first training run on this version. Requests processed
1214
+ by older versions have no receipts, so previous enforcement cannot be inferred
1215
+ retroactively. This change does not alter block durations or diagnose a block
1216
+ disappearing before its expiry.
1217
+
1218
+ ### JavaScript training replay protection
1219
+
1220
+ Node.js 1.1.4 with aiwaf-wasm 0.2.4 uses the same Rust receipt algorithm as
1221
+ Python. The shared trainer applies this protection across JavaScript framework
1222
+ adapters. The WASM `NativeTrainingEvidence` API hashes and filters evidence;
1223
+ Node persists `node_training_evidence.json` in the blacklist CSV directory, or
1224
+ the directory selected by `AIWAF_TRAINING_STATE_DIR`. Preserve this file across
1225
+ expiry, unblocking, blacklist clearing, and log rotation. Sharing a blacklist
1226
+ also requires sharing the evidence directory. Model fitting and keyword learning
1227
+ still use full history; 404 and anomaly enforcement use fresh evidence only.
1228
+ Log records without a valid stable timestamp are excluded from training.
1229
+
1230
+ The Node host serializes trainers with an exclusive lock directory. A crashed
1231
+ trainer may leave `node_training_evidence.lock`; subsequent training fails
1232
+ visibly rather than bypassing that lock. Remove that lock directory only after
1233
+ confirming its trainer has stopped. Receipt snapshots are written and synced
1234
+ before atomic replacement. As in Python, block writes and receipt commits are
1235
+ separate operations, so a crash between them can still require recovery.
1236
+
1237
+ The CLI exits with failure for missing WASM receipt support, corrupt state, or
1238
+ storage errors. Programmatic callers can await `require('aiwaf/train')()`.
1239
+ Publish the matching WASM package before the Node package; `test:wasm-real`
1240
+ checks receipt restoration against the installed dependency, not just a fixture.
1241
+
1242
+ Java's `train-model` operation fits and saves a model without adding blacklist
1243
+ entries. Servlet and Spring use that shared Java core. Retraining alone therefore
1244
+ cannot extend or recreate their runtime blocks; a regression test verifies this.
1245
+
1246
+ Blacklist expiry is also protected against concurrent updates. Node request
1247
+ checks and listings do not delete expired snapshots. Explicit cleanup checks
1248
+ expiry in the database DELETE, or inside the CSV mutation lock after reading
1249
+ the current rows. CSV blacklist writers use the same lock and atomically replace
1250
+ the file. A crashed writer can leave `<blacklist CSV path>.lock`; stop its owner
1251
+ before removing that lock directory. Lock acquisition times out after 60 seconds
1252
+ and reports an error rather than proceeding without protection.
1253
+
1254
+ Java CSV and file storage reload current data under a shared JVM and OS sidecar
1255
+ lock for each operation. Reads filter expiry without rewriting disk; writes
1256
+ preserve other instances' updates. OS locks release when a process exits; the
1257
+ sidecar lock file stays in place and must not be removed while workers run.
1258
+ File storage now incurs a reload for each operation. Restart all old workers
1259
+ when upgrading so every writer participates in the locking protocol.
1260
+
1191
1261
  ## Shared training schema
1192
1262
 
1193
1263
  New training paths use these six features in this order:
@@ -1328,11 +1398,11 @@ Release versions and tags must match the relevant manifest.
1328
1398
 
1329
1399
  | Package | Manifest | Tag | Workflow |
1330
1400
  | --- | --- | --- | --- |
1331
- | Python `aiwaf` | `pyproject.toml` | `python-v1.1.5` | `python-publish.yml` |
1332
- | npm `aiwaf` | `js/package.json` | `js-v1.1.3` | `npm-publish.yml` |
1333
- | PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.4` | `rust-publish.yml` |
1334
- | npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.3` | `wasm-publish.yml` |
1335
- | Maven `aiwaf-java` | `java/pom.xml` | `java-v1.3.3` | `java-publish.yml` |
1401
+ | Python `aiwaf` | `pyproject.toml` | `python-v1.1.6` | `python-publish.yml` |
1402
+ | npm `aiwaf` | `js/package.json` | `js-v1.1.4` | `npm-publish.yml` |
1403
+ | PyPI `aiwaf-rust` | `rust/pyproject.toml` + `rust/Cargo.toml` | `rust-v0.2.5` | `rust-publish.yml` |
1404
+ | npm `aiwaf-wasm` | `rust/crates/aiwaf_wasm/Cargo.toml` | `wasm-v0.2.4` | `wasm-publish.yml` |
1405
+ | Maven `aiwaf-java` | `java/pom.xml` | `java-v1.3.4` | `java-publish.yml` |
1336
1406
 
1337
1407
  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.
1338
1408
 
@@ -1340,6 +1410,12 @@ Java publishing uses the protected `maven-publish` environment plus `GPG_PRIVATE
1340
1410
 
1341
1411
  Registry releases are immutable. Increment the relevant manifest version before publishing another release.
1342
1412
 
1413
+ For the replay fix, publish `aiwaf-rust 0.2.5` before Python `aiwaf 1.1.6`, and
1414
+ `aiwaf-wasm 0.2.4` before npm `aiwaf 1.1.4`. After WASM publication, refresh the
1415
+ npm lockfile against the registry to record the actual companion checksum, then
1416
+ run `npm ci` and the release checks. The prepared future WASM lock entry has no
1417
+ integrity checksum; it cannot be installed until that package is published.
1418
+
1343
1419
  ## Security and limitations
1344
1420
 
1345
1421
  - Deterministic controls can produce false positives when legitimate routes resemble common probes; use narrow route exemptions and regression tests.
@@ -103,11 +103,6 @@ async function initialize() {
103
103
  dbAvailable = false;
104
104
  }
105
105
 
106
- if (!dbAvailable) {
107
- const existing = csvStore.readRows(csvPath, headers);
108
- csvStore.writeRows(csvPath, headers, existing);
109
- }
110
-
111
106
  initialized = true;
112
107
  return dbAvailable;
113
108
  }
@@ -140,22 +135,21 @@ async function saveRow(row) {
140
135
  dbAvailable = false;
141
136
  }
142
137
  }
143
- const rows = csvRows();
144
- const index = rows.findIndex(item => item.ip_address === row.ip_address);
145
- const stored = { ...row, id: index >= 0 ? rows[index].id : csvStore.nextId(rows) };
146
- if (index >= 0) rows[index] = stored;
147
- else rows.push(stored);
148
- csvStore.writeRows(csvPath, headers, rows.map(serializeRow));
138
+ await csvStore.updateRows(csvPath, headers, current => {
139
+ const rows = current.map(normalizeRow);
140
+ const index = rows.findIndex(item => item.ip_address === row.ip_address);
141
+ const stored = { ...row, id: index >= 0 ? rows[index].id : csvStore.nextId(rows) };
142
+ if (index >= 0) rows[index] = stored;
143
+ else rows.push(stored);
144
+ return { rows: rows.map(serializeRow) };
145
+ });
149
146
  }
150
147
 
151
148
  module.exports = {
152
149
  async isBlocked(ip) {
153
150
  const row = await rawRow(ip);
154
- if (!isActive(row)) {
155
- if (row) await this.unblock(ip);
156
- return false;
157
- }
158
- return true;
151
+ // An expired snapshot is not authority to delete a concurrent refresh.
152
+ return isActive(row);
159
153
  },
160
154
 
161
155
  async block(ip, reason = 'WAF blocked', options = {}) {
@@ -212,10 +206,11 @@ module.exports = {
212
206
  }
213
207
  }
214
208
 
215
- const rows = csvRows();
216
- const filtered = rows.filter(row => String(row.ip_address) !== normalizedIp);
217
- csvStore.writeRows(csvPath, headers, filtered.map(serializeRow));
218
- return filtered.length !== rows.length;
209
+ return csvStore.updateRows(csvPath, headers, current => {
210
+ const rows = current.map(normalizeRow);
211
+ const filtered = rows.filter(row => row.ip_address !== normalizedIp);
212
+ return { rows: filtered.map(serializeRow), result: filtered.length !== rows.length };
213
+ });
219
214
  },
220
215
 
221
216
  async getBlockedIPs({ activeOnly = true } = {}) {
@@ -237,10 +232,21 @@ module.exports = {
237
232
  },
238
233
 
239
234
  async cleanupExpired(now = Date.now() / 1000) {
240
- const rows = await this.getBlockedIPs({ activeOnly: false });
241
- const expired = rows.filter(row => !row.permanent && row.expires_at && row.expires_at <= now);
242
- for (const row of expired) await this.unblock(row.ip_address);
243
- return expired.length;
235
+ if (await initialize()) {
236
+ try {
237
+ // Evaluate expiry in the DELETE itself, against the current row.
238
+ return await db('blocked_ips').where('permanent', false)
239
+ .whereNotNull('reputation_reason').whereNot('reputation_reason', '')
240
+ .where('expires_at', '>', 0).where('expires_at', '<=', now).del();
241
+ } catch (err) {
242
+ dbAvailable = false;
243
+ }
244
+ }
245
+ return csvStore.updateRows(csvPath, headers, current => {
246
+ const rows = current.map(normalizeRow);
247
+ const active = rows.filter(row => isActive(row, now));
248
+ return { rows: active.map(serializeRow), result: rows.length - active.length };
249
+ });
244
250
  },
245
251
 
246
252
  async getStatistics() {
@@ -343,9 +349,7 @@ module.exports = {
343
349
  }
344
350
  }
345
351
 
346
- const rows = csvRows();
347
- csvStore.writeRows(csvPath, headers, []);
348
- return rows.length;
352
+ return csvStore.updateRows(csvPath, headers, rows => ({ rows: [], result: rows.length }));
349
353
  },
350
354
 
351
355
  async initialize() {
package/lib/csvStore.js CHANGED
@@ -72,7 +72,39 @@ function writeRows(filePath, headers, rows) {
72
72
  for (const row of rows) {
73
73
  lines.push(headers.map(header => escapeCsv(row[header] ?? '')).join(','));
74
74
  }
75
- fs.writeFileSync(filePath, `${lines.join('\n')}\n`, 'utf8');
75
+ const temp = `${filePath}.${process.pid}.${require('crypto').randomUUID()}.tmp`;
76
+ try {
77
+ fs.writeFileSync(temp, `${lines.join('\n')}\n`, 'utf8');
78
+ fs.renameSync(temp, filePath);
79
+ } finally {
80
+ if (fs.existsSync(temp)) fs.unlinkSync(temp);
81
+ }
82
+ }
83
+
84
+ // All blacklist mutations use this lock and read the current file inside it.
85
+ // A crash leaves the lock in place; recovery must first stop the owning writer.
86
+ async function updateRows(filePath, headers, update, timeoutMs = 60000) {
87
+ filePath = path.resolve(filePath);
88
+ ensureDir(filePath);
89
+ const lock = `${filePath}.lock`;
90
+ const deadline = Date.now() + timeoutMs;
91
+ for (;;) {
92
+ try {
93
+ fs.mkdirSync(lock);
94
+ break;
95
+ } catch (error) {
96
+ if (error.code !== 'EEXIST') throw error;
97
+ if (Date.now() >= deadline) throw new Error(`CSV mutation lock timeout: ${lock}`);
98
+ await new Promise(resolve => setTimeout(resolve, 25));
99
+ }
100
+ }
101
+ try {
102
+ const { rows, result } = update(readRows(filePath, headers));
103
+ writeRows(filePath, headers, rows);
104
+ return result;
105
+ } finally {
106
+ fs.rmdirSync(lock);
107
+ }
76
108
  }
77
109
 
78
110
  function appendRow(filePath, headers, row) {
@@ -97,5 +129,6 @@ module.exports = {
97
129
  readRows,
98
130
  writeRows,
99
131
  appendRow,
132
+ updateRows,
100
133
  nextId
101
134
  };
@@ -0,0 +1,59 @@
1
+ // WASM owns receipt identity and decisions; Node owns durable filesystem I/O.
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { createTrainingEvidence } = require('./wasmAdapter');
5
+
6
+ async function acquire(directory, timeoutMs = 60000) {
7
+ fs.mkdirSync(directory, { recursive: true });
8
+ const lock = path.join(directory, 'node_training_evidence.lock');
9
+ const deadline = Date.now() + timeoutMs;
10
+ for (;;) {
11
+ try { fs.mkdirSync(lock); break; } catch (error) {
12
+ if (error.code !== 'EEXIST') throw error;
13
+ if (Date.now() >= deadline) throw new Error(`Training evidence is locked: ${lock}. If a trainer crashed, confirm it has stopped before removing this lock directory.`);
14
+ await new Promise(resolve => setTimeout(resolve, 100));
15
+ }
16
+ }
17
+ return () => fs.rmdirSync(lock);
18
+ }
19
+
20
+ function persist(file, state) {
21
+ const temporary = `${file}.tmp`;
22
+ const fd = fs.openSync(temporary, 'w');
23
+ try { fs.writeFileSync(fd, state); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
24
+ fs.renameSync(temporary, file);
25
+ if (process.platform !== 'win32') {
26
+ const directory = fs.openSync(path.dirname(file), 'r');
27
+ try { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }
28
+ }
29
+ }
30
+
31
+ async function withTrainingEvidence(directory, action, timeoutMs) {
32
+ const release = await acquire(path.resolve(directory), timeoutMs);
33
+ let native;
34
+ try {
35
+ const file = path.join(path.resolve(directory), 'node_training_evidence.json');
36
+ let state;
37
+ try { state = fs.readFileSync(file, 'utf8'); } catch (error) {
38
+ if (error.code !== 'ENOENT') throw error;
39
+ state = '{"version":1,"ips":{}}';
40
+ }
41
+ native = await createTrainingEvidence(state);
42
+ return await action({
43
+ fresh(records) {
44
+ const fields = records.map(row => [row.ip, row.timestamp.toISOString(), row.path, String(row.status)]);
45
+ return JSON.parse(native.fresh_indices(JSON.stringify(fields))).map(index => records[index]);
46
+ },
47
+ async block(ip, perform) {
48
+ if (!native.can_block(ip) || await perform() === false) return false;
49
+ persist(file, native.committed_state(ip));
50
+ native.commit(ip);
51
+ return true;
52
+ }
53
+ });
54
+ } finally {
55
+ try { if (native) native.free(); } finally { release(); }
56
+ }
57
+ }
58
+
59
+ module.exports = { withTrainingEvidence };
@@ -46,7 +46,8 @@ async function loadWasmFromDisk() {
46
46
  rust_payload_from_records: bg.rust_payload_from_records,
47
47
  python_feature_from_record: bg.python_feature_from_record,
48
48
  python_features_batched: bg.python_features_batched,
49
- NativeRequestPipeline: bg.NativeRequestPipeline
49
+ NativeRequestPipeline: bg.NativeRequestPipeline,
50
+ NativeTrainingEvidence: bg.NativeTrainingEvidence
50
51
  };
51
52
  }
52
53
 
@@ -544,7 +545,16 @@ async function createRequestPipeline(profile = {}, model = null) {
544
545
  return { native, setModel };
545
546
  }
546
547
 
548
+ async function createTrainingEvidence(state) {
549
+ const mod = await loadWasm();
550
+ if (!mod || typeof mod.NativeTrainingEvidence !== 'function') {
551
+ throw new Error('Training replay protection requires aiwaf-wasm>=0.2.4 with NativeTrainingEvidence; install the matching build');
552
+ }
553
+ return new mod.NativeTrainingEvidence(state);
554
+ }
555
+
547
556
  module.exports = {
557
+ createTrainingEvidence,
548
558
  createRequestPipeline,
549
559
  createIsolationForest,
550
560
  createIsolationForestFromJSON,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiwaf",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "AIWAF Web Application Firewall for JavaScript applications and major Node.js frameworks",
5
5
  "main": "index.js",
6
6
  "files": [
@@ -36,7 +36,7 @@
36
36
  },
37
37
  "dependencies": {
38
38
  "@babel/parser": "^7.29.2",
39
- "aiwaf-wasm": "^0.2.3",
39
+ "aiwaf-wasm": "^0.2.4",
40
40
  "express": "^4.21.2",
41
41
  "glob": "^13.0.6",
42
42
  "knex": "^2.4.2",
@@ -66,7 +66,11 @@
66
66
  "transform": {
67
67
  "^.+\\.m?js$": [
68
68
  "babel-jest",
69
- { "plugins": ["@babel/plugin-transform-modules-commonjs"] }
69
+ {
70
+ "plugins": [
71
+ "@babel/plugin-transform-modules-commonjs"
72
+ ]
73
+ }
70
74
  ]
71
75
  },
72
76
  "transformIgnorePatterns": [
package/train.js CHANGED
@@ -8,6 +8,9 @@ const requestLogStore = require('./lib/requestLogStore');
8
8
  const modelStore = require('./lib/modelStore');
9
9
  const blacklistManager = require('./lib/blacklistManager');
10
10
  const { calculateTrainingFeatures } = require('./lib/trainingFeatures');
11
+ const { withTrainingEvidence } = require('./lib/trainingEvidence');
12
+ const TRAINING_STATE_DIR = process.env.AIWAF_TRAINING_STATE_DIR
13
+ || path.dirname(process.env.AIWAF_BLOCKED_IPS_CSV_PATH || path.join('logs', 'storage', 'blocked_ips.csv'));
11
14
 
12
15
  const STATIC_KW = [
13
16
  '.php', '.xmlrpc', 'wp-', '.env', '.git', '.bak',
@@ -337,7 +340,7 @@ function parseLogLine(line) {
337
340
  const status = match[4];
338
341
  const rt = match[5] ? parseFloat(match[5]) : 0.0;
339
342
 
340
- let timestamp = new Date();
343
+ let timestamp = new Date(NaN);
341
344
  try {
342
345
  const cleanTimestamp = timestampStr.split(' ')[0];
343
346
  const monthMap = {
@@ -349,12 +352,16 @@ function parseLogLine(line) {
349
352
  const parts = cleanTimestamp.split(/[/:\s]/);
350
353
  if (parts.length >= 6) {
351
354
  const [day, monthText, year, hour, minute, second] = parts;
352
- const month = monthMap[monthText] || '01';
353
- timestamp = new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`);
355
+ const month = monthMap[monthText];
356
+ if (!month) return null;
357
+ const offset = timestampStr.trim().split(/\s+/)[1] || '+0000';
358
+ if (!/^[+-]\d{4}$/.test(offset)) return null;
359
+ timestamp = new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}${offset.slice(0, 3)}:${offset.slice(3)}`);
354
360
  }
355
361
  } catch (err) {
356
- timestamp = new Date();
362
+ return null;
357
363
  }
364
+ if (!Number.isFinite(timestamp.getTime())) return null;
358
365
 
359
366
  return {
360
367
  ip,
@@ -367,29 +374,33 @@ function parseLogLine(line) {
367
374
 
368
375
  function parseMiddlewareEvent(event) {
369
376
  if (!event || !event.path || !event.ip) return null;
377
+ const timestamp = new Date(event.timestamp);
378
+ if (!event.timestamp || !Number.isFinite(timestamp.getTime())) return null;
370
379
 
371
380
  return {
372
381
  ip: String(event.ip),
373
382
  path: String(event.path).split('?')[0],
374
383
  status: String(event.status || 200),
375
384
  responseTime: Number(event.responseTime || 0),
376
- timestamp: event.timestamp ? new Date(event.timestamp) : new Date()
385
+ timestamp
377
386
  };
378
387
  }
379
388
 
380
389
  function parseDbEvent(event) {
381
390
  if (!event || !event.path || !event.ip) return null;
391
+ const timestamp = new Date(event.timestamp);
392
+ if (!event.timestamp || !Number.isFinite(timestamp.getTime())) return null;
382
393
  return {
383
394
  ip: String(event.ip),
384
395
  path: String(event.path).split('?')[0],
385
396
  status: String(event.status || 200),
386
397
  responseTime: Number(event.responseTime || 0),
387
- timestamp: event.timestamp ? new Date(event.timestamp) : new Date()
398
+ timestamp
388
399
  };
389
400
  }
390
401
 
391
- (async () => {
392
- try {
402
+ async function train() {
403
+ return withTrainingEvidence(TRAINING_STATE_DIR, async evidence => {
393
404
  const rawAccessLines = await readAccessLogLines();
394
405
  let parsedRequests = rawAccessLines.map(parseLogLine).filter(Boolean);
395
406
 
@@ -423,12 +434,15 @@ function parseDbEvent(event) {
423
434
  return;
424
435
  }
425
436
 
437
+ // Unstable/missing timestamps cannot establish fresh evidence on a replay.
438
+ parsedRequests = parsedRequests.filter(record => Number.isFinite(record.timestamp.getTime()));
439
+ const freshRequests = evidence.fresh(parsedRequests);
426
440
  await unblockExemptIps();
427
441
 
428
442
  const ip404Counts = new Map();
429
443
  const ip404LoginCounts = new Map();
430
444
  const ipTimes = new Map();
431
- for (const record of parsedRequests) {
445
+ for (const record of freshRequests) {
432
446
  const ts = record.timestamp instanceof Date ? record.timestamp.getTime() : new Date(record.timestamp).getTime();
433
447
  if (!ipTimes.has(record.ip)) ipTimes.set(record.ip, []);
434
448
  ipTimes.get(record.ip).push(ts);
@@ -444,7 +458,7 @@ function parseDbEvent(event) {
444
458
  if (count >= 6) {
445
459
  const loginCount = ip404LoginCounts.get(ip) || 0;
446
460
  if (count > loginCount) {
447
- await blacklistManager.block(ip, `Excessive 404s (non-login ${count}/${count + loginCount})`);
461
+ await evidence.block(ip, () => blacklistManager.block(ip, `Excessive 404s (non-login ${count}/${count + loginCount})`));
448
462
  }
449
463
  }
450
464
  }
@@ -487,8 +501,9 @@ function parseDbEvent(event) {
487
501
 
488
502
  // Identify anomalous IPs and optionally block if suspicious.
489
503
  const anomaliesByIp = new Map();
490
- parsedRequests.forEach((record, idx) => {
491
- const feature = features[idx];
504
+ const enforcementFeatures = freshRequests.length ? await calculateTrainingFeatures(freshRequests, STATIC_KW, STATUS_IDX) : [];
505
+ freshRequests.forEach((record, idx) => {
506
+ const feature = enforcementFeatures[idx];
492
507
  if (!feature) return;
493
508
  const isAnomaly = model.isAnomaly(feature, 0.5);
494
509
  if (!isAnomaly) return;
@@ -519,7 +534,7 @@ function parseDbEvent(event) {
519
534
  if (avgKwHits < 2 && max404s < 10 && avgBurst < 15 && totalRequests < 100) {
520
535
  continue;
521
536
  }
522
- await blacklistManager.block(ip, `AI anomaly + suspicious patterns (kw:${avgKwHits.toFixed(1)}, 404s:${max404s}, burst:${avgBurst.toFixed(1)})`);
537
+ await evidence.block(ip, () => blacklistManager.block(ip, `AI anomaly + suspicious patterns (kw:${avgKwHits.toFixed(1)}, 404s:${max404s}, burst:${avgBurst.toFixed(1)})`));
523
538
  }
524
539
  } else {
525
540
  console.log(`AI training skipped: ${parsedRequests.length} logs < ${MIN_AI_LOGS}`);
@@ -558,7 +573,18 @@ function parseDbEvent(event) {
558
573
  } catch (err) {
559
574
  // ignore
560
575
  }
561
- } catch (err) {
562
- console.error('Training failed:', err);
576
+ });
577
+ }
578
+
579
+ module.exports = train;
580
+ async function runCLI() {
581
+ try {
582
+ await train();
583
+ process.exitCode = 0;
584
+ } catch (error) {
585
+ console.error('Training failed:', error);
586
+ process.exitCode = 1;
563
587
  }
564
- })();
588
+ }
589
+ module.exports.runCLI = runCLI;
590
+ if (require.main === module) runCLI();