aiwaf 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/INSTALLATION.md +144 -0
  2. package/LICENSE +21 -0
  3. package/README.md +621 -0
  4. package/bin/aiwaf.js +349 -0
  5. package/index.js +62 -0
  6. package/lib/adonisMiddleware.js +82 -0
  7. package/lib/anomalyDetector.js +221 -0
  8. package/lib/blacklistManager.js +134 -0
  9. package/lib/blockResponses.js +25 -0
  10. package/lib/csvStore.js +84 -0
  11. package/lib/dynamicKeyword.js +42 -0
  12. package/lib/dynamicKeywordStore.js +169 -0
  13. package/lib/exemptionStore.js +204 -0
  14. package/lib/exemptions.js +56 -0
  15. package/lib/fastifyPlugin.js +49 -0
  16. package/lib/featureUtils.js +183 -0
  17. package/lib/geoBlocker.js +159 -0
  18. package/lib/geoPolicy.js +42 -0
  19. package/lib/geoStore.js +111 -0
  20. package/lib/hapiPlugin.js +92 -0
  21. package/lib/headerValidation.js +275 -0
  22. package/lib/honeypotDetector.js +91 -0
  23. package/lib/isolationForest.js +117 -0
  24. package/lib/keywordDetector.js +5 -0
  25. package/lib/keywordFallbackStore.js +39 -0
  26. package/lib/koaMiddleware.js +68 -0
  27. package/lib/middlewareLogger.js +123 -0
  28. package/lib/middlewarePlan.js +72 -0
  29. package/lib/modelSecurity.js +17 -0
  30. package/lib/modelStore.js +129 -0
  31. package/lib/nestMiddleware.js +12 -0
  32. package/lib/nextMiddleware.js +78 -0
  33. package/lib/pathManifest.js +533 -0
  34. package/lib/pathRules.js +184 -0
  35. package/lib/rateLimiter.js +153 -0
  36. package/lib/redisClient.js +35 -0
  37. package/lib/requestLogStore.js +167 -0
  38. package/lib/runtimeUtils.js +166 -0
  39. package/lib/settingsCompat.js +140 -0
  40. package/lib/sourceAst.js +294 -0
  41. package/lib/trainingLogic.js +87 -0
  42. package/lib/uuidDetector.js +46 -0
  43. package/lib/wafMiddleware.js +459 -0
  44. package/lib/wasmAdapter.js +480 -0
  45. package/lib/whois.js +38 -0
  46. package/package.json +85 -0
  47. package/resources/model.json +9536 -0
  48. package/train.js +595 -0
  49. package/utils/cache.js +3 -0
  50. package/utils/db.js +11 -0
@@ -0,0 +1,221 @@
1
+ const { IsolationForest } = require('./isolationForest');
2
+ const { createIsolationForest, getWasmStatus } = require('./wasmAdapter');
3
+ const modelStore = require('./modelStore');
4
+ const requestLogStore = require('./requestLogStore');
5
+ const { STATIC_KW } = require('./featureUtils');
6
+ const dynamicKeyword = require('./dynamicKeyword');
7
+ const exemptions = require('./exemptions');
8
+ const trainingLogic = require('./trainingLogic');
9
+
10
+ let model;
11
+ let trained = false;
12
+ let modelMetadata = null;
13
+ let loadStarted = false;
14
+ let minAiLogs = 0;
15
+ let aiLogsSufficient = true;
16
+ let aiLogCount = null;
17
+ let wasmStatus = { loaded: false, error: null };
18
+
19
+ async function loadModel(opts = {}) {
20
+ if (loadStarted) return;
21
+ loadStarted = true;
22
+ try {
23
+ const modelData = await modelStore.load(opts);
24
+ if (!modelData) return;
25
+
26
+ if (modelData.metadata) {
27
+ modelMetadata = modelData.metadata;
28
+ model = IsolationForest.fromJSON(modelData);
29
+ trained = true;
30
+ console.log(`Pretrained anomaly model loaded (${modelMetadata.samplesCount} samples, created: ${modelMetadata.createdAt})`);
31
+ return;
32
+ }
33
+
34
+ model = IsolationForest.fromJSON(modelData);
35
+ trained = true;
36
+ console.log('Pretrained anomaly model loaded (legacy format)');
37
+ } catch (err) {
38
+ console.warn('Failed to load pretrained model:', err.message);
39
+ }
40
+ }
41
+
42
+ async function countRecentDbLogs(days = 30) {
43
+ try {
44
+ const rows = await requestLogStore.recent(20000);
45
+ const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
46
+ return rows.filter(row => {
47
+ const ts = row.created_at ? new Date(row.created_at).getTime() : 0;
48
+ return ts >= cutoff;
49
+ }).length;
50
+ } catch (err) {
51
+ return 0;
52
+ }
53
+ }
54
+
55
+ async function checkAiLogSufficiency() {
56
+ if (minAiLogs <= 0) {
57
+ aiLogCount = null;
58
+ aiLogsSufficient = true;
59
+ return;
60
+ }
61
+
62
+ const dbCount = await countRecentDbLogs(30);
63
+ aiLogCount = dbCount;
64
+ aiLogsSufficient = dbCount >= minAiLogs;
65
+ }
66
+
67
+ const { isScanningPath } = trainingLogic;
68
+
69
+ function analyzeRecentBehavior(recentData = []) {
70
+ const recentKwHits = [];
71
+ let recent404s = 0;
72
+ const recentBurstCounts = [];
73
+
74
+ for (const entry of recentData) {
75
+ const entryTime = entry.timestamp || 0;
76
+ const entryPath = String(entry.path || '');
77
+ const entryStatus = entry.status;
78
+
79
+ let entryKwHits = 0;
80
+ if (!exemptions.shouldSkipKeyword('', entryPath)) {
81
+ entryKwHits = STATIC_KW.reduce(
82
+ (count, kw) => count + (entryPath.toLowerCase().includes(kw) ? 1 : 0),
83
+ 0
84
+ );
85
+ }
86
+ recentKwHits.push(entryKwHits);
87
+
88
+ if (entryStatus === 404) {
89
+ recent404s += 1;
90
+ }
91
+
92
+ const entryBurst = recentData.filter(item => Math.abs(entryTime - (item.timestamp || 0)) <= 10000).length;
93
+ recentBurstCounts.push(entryBurst);
94
+ }
95
+
96
+ const avgKwHits = recentKwHits.length
97
+ ? recentKwHits.reduce((sum, v) => sum + v, 0) / recentKwHits.length
98
+ : 0;
99
+ const max404s = recent404s;
100
+ const avgBurst = recentBurstCounts.length
101
+ ? recentBurstCounts.reduce((sum, v) => sum + v, 0) / recentBurstCounts.length
102
+ : 0;
103
+ const totalRequests = recentData.length;
104
+ const scanning404s = recentData.filter(entry => entry.status === 404 && isScanningPath(entry.path)).length;
105
+ const legitimate404s = Math.max(max404s - scanning404s, 0);
106
+
107
+ let shouldBlock = true;
108
+ if (max404s === 0 && avgKwHits === 0 && scanning404s === 0) {
109
+ shouldBlock = false;
110
+ } else if (
111
+ avgKwHits < 3
112
+ && scanning404s < 5
113
+ && legitimate404s < 20
114
+ && avgBurst < 25
115
+ && totalRequests < 150
116
+ ) {
117
+ shouldBlock = false;
118
+ }
119
+
120
+ return {
121
+ avg_kw_hits: avgKwHits,
122
+ max_404s: max404s,
123
+ avg_burst: avgBurst,
124
+ total_requests: totalRequests,
125
+ scanning_404s: scanning404s,
126
+ legitimate_404s: legitimate404s,
127
+ should_block: shouldBlock
128
+ };
129
+ }
130
+
131
+ module.exports = {
132
+ async init(opts = {}) {
133
+ minAiLogs = Number.isFinite(Number(opts.AIWAF_MIN_AI_LOGS))
134
+ ? Number(opts.AIWAF_MIN_AI_LOGS)
135
+ : 10000; // Default: require 10k training samples
136
+ await checkAiLogSufficiency();
137
+ await loadModel(opts);
138
+ if (!model) {
139
+ model = await createIsolationForest({
140
+ nTrees: opts.nTrees || 100,
141
+ sampleSize: opts.sampleSize || 256,
142
+ threshold: opts.threshold || 0.5
143
+ });
144
+ wasmStatus = getWasmStatus();
145
+ }
146
+
147
+ if (model && !aiLogsSufficient) {
148
+ model = null;
149
+ trained = false;
150
+ if (aiLogCount !== null) {
151
+ console.log(`AIWAF AI model disabled due to insufficient logs (${aiLogCount}/${minAiLogs}). Require at least ${minAiLogs} logs before using AI detection.`);
152
+ } else {
153
+ console.log(`AIWAF AI model disabled due to insufficient logs (unknown/${minAiLogs}). Require at least ${minAiLogs} logs before using AI detection.`);
154
+ }
155
+ }
156
+ },
157
+
158
+ train(data) {
159
+ model.fit(data);
160
+ trained = true;
161
+ },
162
+
163
+ hasModel() {
164
+ return !!model && trained;
165
+ },
166
+
167
+ isModelSufficientlyTrained() {
168
+ // Model must exist AND have enough training data
169
+ return !!model && trained && aiLogsSufficient;
170
+ },
171
+
172
+ // Expects a feature vector: [pathLen, kwHits, statusIdx, responseTime, burst, total404]
173
+ isAnomalous(features, threshold = 0.5) {
174
+ if (!trained || !model) {
175
+ return false;
176
+ }
177
+
178
+ try {
179
+ return model.isAnomaly(features, threshold);
180
+ } catch (err) {
181
+ console.warn('Error in anomaly detection:', err.message);
182
+ return false;
183
+ }
184
+ },
185
+
186
+ analyzeRecentBehavior,
187
+ isScanningPath,
188
+
189
+ maybeLearnKeyword(path, statusCode, opts = {}) {
190
+ if (!opts.AIWAF_ENABLE_KEYWORD_LEARNING) return;
191
+ if (statusCode !== 404) return;
192
+ const pathLower = String(path || '').toLowerCase();
193
+ if (!pathLower || exemptions.shouldSkipKeyword('', pathLower)) return;
194
+
195
+ const segments = pathLower.split(/\W+/).filter(seg => seg.length > 3);
196
+ if (segments.length === 0) return;
197
+
198
+ const suspicious = segments.some(seg => {
199
+ if (STATIC_KW.includes(seg)) return false;
200
+ if (pathLower.includes('../') || pathLower.includes('..\\')) return true;
201
+ if (pathLower.includes('%2e%2e') || pathLower.includes('%252e') || pathLower.includes('%c0%ae')) return true;
202
+ if (pathLower.includes(seg) && isScanningPath(pathLower)) return true;
203
+ return false;
204
+ });
205
+
206
+ if (!suspicious) return;
207
+ dynamicKeyword.learnSegments(segments);
208
+ },
209
+
210
+ getModelInfo() {
211
+ return {
212
+ trained,
213
+ metadata: modelMetadata,
214
+ threshold: 0.5,
215
+ minAiLogs,
216
+ aiLogsSufficient,
217
+ aiLogCount,
218
+ wasm: wasmStatus
219
+ };
220
+ }
221
+ };
@@ -0,0 +1,134 @@
1
+ const path = require('path');
2
+ const db = require('../utils/db');
3
+ const csvStore = require('./csvStore');
4
+
5
+ const headers = ['id', 'ip_address', 'reason', 'blocked_at'];
6
+ const csvPath = process.env.AIWAF_BLOCKED_IPS_CSV_PATH || path.join('logs', 'storage', 'blocked_ips.csv');
7
+
8
+ let initialized = false;
9
+ let dbAvailable = true;
10
+
11
+ async function initialize() {
12
+ if (initialized) return dbAvailable;
13
+
14
+ try {
15
+ const exists = await db.schema.hasTable('blocked_ips');
16
+ if (!exists) {
17
+ await db.schema.createTable('blocked_ips', table => {
18
+ table.increments('id').primary();
19
+ table.string('ip_address').unique().notNullable();
20
+ table.string('reason').defaultTo('WAF blocked');
21
+ table.timestamp('blocked_at').defaultTo(db.fn.now());
22
+ });
23
+ }
24
+ dbAvailable = true;
25
+ } catch (err) {
26
+ dbAvailable = false;
27
+ }
28
+
29
+ if (!dbAvailable) {
30
+ const existing = csvStore.readRows(csvPath, headers);
31
+ csvStore.writeRows(csvPath, headers, existing);
32
+ }
33
+
34
+ initialized = true;
35
+ return dbAvailable;
36
+ }
37
+
38
+ function csvRows() {
39
+ return csvStore.readRows(csvPath, headers);
40
+ }
41
+
42
+ module.exports = {
43
+ async isBlocked(ip) {
44
+ const normalizedIp = String(ip || '').trim();
45
+ const useDb = await initialize();
46
+ if (useDb) {
47
+ try {
48
+ const row = await db('blocked_ips').where('ip_address', normalizedIp).first();
49
+ return !!row;
50
+ } catch (err) {
51
+ dbAvailable = false;
52
+ }
53
+ }
54
+
55
+ return csvRows().some(row => String(row.ip_address) === normalizedIp);
56
+ },
57
+
58
+ async block(ip, reason = 'WAF blocked') {
59
+ const normalizedIp = String(ip || '').trim();
60
+ if (!normalizedIp) return false;
61
+
62
+ const useDb = await initialize();
63
+ if (useDb) {
64
+ try {
65
+ await db('blocked_ips').insert({ ip_address: normalizedIp, reason }).onConflict('ip_address').ignore();
66
+ return true;
67
+ } catch (err) {
68
+ dbAvailable = false;
69
+ }
70
+ }
71
+
72
+ const rows = csvRows();
73
+ if (rows.some(row => String(row.ip_address) === normalizedIp)) return true;
74
+
75
+ rows.push({
76
+ id: csvStore.nextId(rows),
77
+ ip_address: normalizedIp,
78
+ reason,
79
+ blocked_at: new Date().toISOString()
80
+ });
81
+ csvStore.writeRows(csvPath, headers, rows);
82
+ return true;
83
+ },
84
+
85
+ async unblock(ip) {
86
+ const normalizedIp = String(ip || '').trim();
87
+ const useDb = await initialize();
88
+ if (useDb) {
89
+ try {
90
+ const deleted = await db('blocked_ips').where('ip_address', normalizedIp).del();
91
+ return deleted > 0;
92
+ } catch (err) {
93
+ dbAvailable = false;
94
+ }
95
+ }
96
+
97
+ const rows = csvRows();
98
+ const filtered = rows.filter(row => String(row.ip_address) !== normalizedIp);
99
+ csvStore.writeRows(csvPath, headers, filtered);
100
+ return filtered.length !== rows.length;
101
+ },
102
+
103
+ async getBlockedIPs() {
104
+ const useDb = await initialize();
105
+ if (useDb) {
106
+ try {
107
+ return await db('blocked_ips').select('*').orderBy('blocked_at', 'desc');
108
+ } catch (err) {
109
+ dbAvailable = false;
110
+ }
111
+ }
112
+
113
+ return csvRows().sort((a, b) => String(b.blocked_at).localeCompare(String(a.blocked_at)));
114
+ },
115
+
116
+ async clear() {
117
+ const useDb = await initialize();
118
+ if (useDb) {
119
+ try {
120
+ return await db('blocked_ips').del();
121
+ } catch (err) {
122
+ dbAvailable = false;
123
+ }
124
+ }
125
+
126
+ const rows = csvRows();
127
+ csvStore.writeRows(csvPath, headers, []);
128
+ return rows.length;
129
+ },
130
+
131
+ async initialize() {
132
+ return initialize();
133
+ }
134
+ };
@@ -0,0 +1,25 @@
1
+ function blockedPayload(message = null) {
2
+ const payload = { error: 'blocked' };
3
+ if (message) payload.message = String(message);
4
+ return payload;
5
+ }
6
+
7
+ function blockedResponse(message = null, statusCode = 403) {
8
+ return {
9
+ payload: blockedPayload(message),
10
+ statusCode: Number(statusCode || 403)
11
+ };
12
+ }
13
+
14
+ function throttleResponse() {
15
+ return {
16
+ payload: { error: 'too_many_requests' },
17
+ statusCode: 429
18
+ };
19
+ }
20
+
21
+ module.exports = {
22
+ blockedPayload,
23
+ blockedResponse,
24
+ throttleResponse
25
+ };
@@ -0,0 +1,84 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ function ensureDir(filePath) {
5
+ const dir = path.dirname(filePath);
6
+ if (!fs.existsSync(dir)) {
7
+ fs.mkdirSync(dir, { recursive: true });
8
+ }
9
+ }
10
+
11
+ function escapeCsv(value) {
12
+ const str = String(value ?? '');
13
+ if (str.includes('"') || str.includes(',') || str.includes('\n')) {
14
+ return `"${str.replace(/"/g, '""')}"`;
15
+ }
16
+ return str;
17
+ }
18
+
19
+ function parseCsvLine(line) {
20
+ return (line.match(/("([^"]|"")*"|[^,]+)/g) || []).map(part => {
21
+ const trimmed = String(part || '').trim();
22
+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
23
+ return trimmed.slice(1, -1).replace(/""/g, '"');
24
+ }
25
+ return trimmed;
26
+ });
27
+ }
28
+
29
+ function readRows(filePath, headers) {
30
+ if (!fs.existsSync(filePath)) return [];
31
+
32
+ const raw = fs.readFileSync(filePath, 'utf8').split(/\r?\n/).filter(Boolean);
33
+ if (raw.length === 0) return [];
34
+
35
+ const fileHeader = parseCsvLine(raw[0]);
36
+ const startIndex = fileHeader.join(',') === headers.join(',') ? 1 : 0;
37
+ const rows = [];
38
+
39
+ for (let i = startIndex; i < raw.length; i += 1) {
40
+ const cells = parseCsvLine(raw[i]);
41
+ if (cells.length === 0) continue;
42
+ const row = {};
43
+ headers.forEach((header, index) => {
44
+ row[header] = cells[index] ?? '';
45
+ });
46
+ rows.push(row);
47
+ }
48
+
49
+ return rows;
50
+ }
51
+
52
+ function writeRows(filePath, headers, rows) {
53
+ ensureDir(filePath);
54
+ const lines = [headers.join(',')];
55
+ for (const row of rows) {
56
+ lines.push(headers.map(header => escapeCsv(row[header] ?? '')).join(','));
57
+ }
58
+ fs.writeFileSync(filePath, `${lines.join('\n')}\n`, 'utf8');
59
+ }
60
+
61
+ function appendRow(filePath, headers, row) {
62
+ ensureDir(filePath);
63
+ if (!fs.existsSync(filePath)) {
64
+ fs.writeFileSync(filePath, `${headers.join(',')}\n`, 'utf8');
65
+ }
66
+ const line = headers.map(header => escapeCsv(row[header] ?? '')).join(',');
67
+ fs.appendFileSync(filePath, `${line}\n`, 'utf8');
68
+ }
69
+
70
+ function nextId(rows) {
71
+ let max = 0;
72
+ for (const row of rows) {
73
+ const value = Number(row.id || 0);
74
+ if (Number.isFinite(value) && value > max) max = value;
75
+ }
76
+ return max + 1;
77
+ }
78
+
79
+ module.exports = {
80
+ readRows,
81
+ writeRows,
82
+ appendRow,
83
+ nextId
84
+ };
@@ -0,0 +1,42 @@
1
+ // lib/dynamicKeyword.js
2
+ const dynamicKeywordStore = require('./dynamicKeywordStore');
3
+
4
+ let opts, counts;
5
+
6
+ module.exports = {
7
+ init(o = {}) {
8
+ // normalize option name
9
+ const topN = o.dynamicTopN ?? o.DYNAMIC_TOP_N ?? 10;
10
+ opts = { dynamicTopN: topN };
11
+ counts = {};
12
+ dynamicKeywordStore.initialize().catch(() => {});
13
+ dynamicKeywordStore.list(2000).then(rows => {
14
+ rows.forEach(row => {
15
+ counts[row.keyword] = Number(row.count || 0);
16
+ });
17
+ }).catch(() => {});
18
+ },
19
+
20
+ learnSegments(segments = []) {
21
+ segments.forEach(s => {
22
+ const key = String(s).toLowerCase();
23
+ if (!key) return;
24
+ counts[key] = (counts[key] || 0) + 1;
25
+ dynamicKeywordStore.increment(key).catch(() => {});
26
+ });
27
+ },
28
+
29
+ learn(path) {
30
+ const segments = String(path || '').split('/').filter(s => s.length > 3);
31
+ module.exports.learnSegments(segments);
32
+ },
33
+
34
+ check(path) {
35
+ // only block segments whose count exceeds the threshold
36
+ const pathLower = String(path || '').toLowerCase();
37
+ return Object.entries(counts)
38
+ .find(([seg, cnt]) => cnt > opts.dynamicTopN && pathLower.includes(seg))
39
+ ?. [0] // return the segment string
40
+ || null;
41
+ }
42
+ };
@@ -0,0 +1,169 @@
1
+ const path = require('path');
2
+ const db = require('../utils/db');
3
+ const csvStore = require('./csvStore');
4
+
5
+ const headers = ['id', 'keyword', 'count', 'updated_at'];
6
+ const csvPath = process.env.AIWAF_DYNAMIC_KEYWORDS_CSV_PATH || path.join('logs', 'storage', 'dynamic_keywords.csv');
7
+
8
+ let initialized = false;
9
+ let dbAvailable = true;
10
+
11
+ async function initialize() {
12
+ if (initialized) return dbAvailable;
13
+
14
+ try {
15
+ const hasTable = await db.schema.hasTable('dynamic_keywords');
16
+ if (!hasTable) {
17
+ await db.schema.createTable('dynamic_keywords', table => {
18
+ table.increments('id').primary();
19
+ table.string('keyword').notNullable().unique();
20
+ table.integer('count').notNullable().defaultTo(0);
21
+ table.timestamp('updated_at').defaultTo(db.fn.now());
22
+ });
23
+ }
24
+ dbAvailable = true;
25
+ } catch (err) {
26
+ dbAvailable = false;
27
+ }
28
+
29
+ if (!dbAvailable) {
30
+ csvStore.writeRows(csvPath, headers, csvStore.readRows(csvPath, headers));
31
+ }
32
+
33
+ initialized = true;
34
+ return dbAvailable;
35
+ }
36
+
37
+ function rows() {
38
+ return csvStore.readRows(csvPath, headers);
39
+ }
40
+
41
+ module.exports = {
42
+ async initialize() {
43
+ await initialize();
44
+ },
45
+
46
+ async list(limit = 1000) {
47
+ const normalizedLimit = Number(limit) > 0 ? Number(limit) : 1000;
48
+ if (await initialize()) {
49
+ try {
50
+ return db('dynamic_keywords')
51
+ .select('*')
52
+ .orderBy('count', 'desc')
53
+ .limit(normalizedLimit);
54
+ } catch (err) {
55
+ dbAvailable = false;
56
+ }
57
+ }
58
+
59
+ return rows()
60
+ .map(row => ({ ...row, count: Number(row.count || 0) }))
61
+ .sort((a, b) => b.count - a.count)
62
+ .slice(0, normalizedLimit);
63
+ },
64
+
65
+ async increment(keyword) {
66
+ const normalized = String(keyword || '').toLowerCase();
67
+ if (!normalized) return;
68
+
69
+ if (await initialize()) {
70
+ try {
71
+ const existing = await db('dynamic_keywords').where('keyword', normalized).first();
72
+ if (existing) {
73
+ await db('dynamic_keywords')
74
+ .where('keyword', normalized)
75
+ .update({ count: existing.count + 1, updated_at: db.fn.now() });
76
+ } else {
77
+ await db('dynamic_keywords').insert({ keyword: normalized, count: 1 });
78
+ }
79
+ return;
80
+ } catch (err) {
81
+ dbAvailable = false;
82
+ }
83
+ }
84
+
85
+ const current = rows();
86
+ const match = current.find(row => String(row.keyword) === normalized);
87
+ if (match) {
88
+ match.count = Number(match.count || 0) + 1;
89
+ match.updated_at = new Date().toISOString();
90
+ } else {
91
+ current.push({
92
+ id: csvStore.nextId(current),
93
+ keyword: normalized,
94
+ count: 1,
95
+ updated_at: new Date().toISOString()
96
+ });
97
+ }
98
+ csvStore.writeRows(csvPath, headers, current);
99
+ },
100
+
101
+ async add(keyword, count = 1) {
102
+ const normalized = String(keyword || '').toLowerCase();
103
+ if (!normalized) return;
104
+
105
+ const normalizedCount = Number(count) > 0 ? Number(count) : 1;
106
+
107
+ if (await initialize()) {
108
+ try {
109
+ const existing = await db('dynamic_keywords').where('keyword', normalized).first();
110
+ if (existing) {
111
+ await db('dynamic_keywords')
112
+ .where('keyword', normalized)
113
+ .update({ count: normalizedCount, updated_at: db.fn.now() });
114
+ } else {
115
+ await db('dynamic_keywords').insert({ keyword: normalized, count: normalizedCount });
116
+ }
117
+ return;
118
+ } catch (err) {
119
+ dbAvailable = false;
120
+ }
121
+ }
122
+
123
+ const current = rows();
124
+ const match = current.find(row => String(row.keyword) === normalized);
125
+ if (match) {
126
+ match.count = normalizedCount;
127
+ match.updated_at = new Date().toISOString();
128
+ } else {
129
+ current.push({
130
+ id: csvStore.nextId(current),
131
+ keyword: normalized,
132
+ count: normalizedCount,
133
+ updated_at: new Date().toISOString()
134
+ });
135
+ }
136
+ csvStore.writeRows(csvPath, headers, current);
137
+ },
138
+
139
+ async remove(keyword) {
140
+ const normalized = String(keyword || '').toLowerCase();
141
+ if (!normalized) return;
142
+
143
+ if (await initialize()) {
144
+ try {
145
+ await db('dynamic_keywords').where('keyword', normalized).del();
146
+ return;
147
+ } catch (err) {
148
+ dbAvailable = false;
149
+ }
150
+ }
151
+
152
+ const current = rows().filter(row => String(row.keyword) !== normalized);
153
+ csvStore.writeRows(csvPath, headers, current);
154
+ },
155
+
156
+ async clear() {
157
+ if (await initialize()) {
158
+ try {
159
+ return await db('dynamic_keywords').del();
160
+ } catch (err) {
161
+ dbAvailable = false;
162
+ }
163
+ }
164
+
165
+ const current = rows();
166
+ csvStore.writeRows(csvPath, headers, []);
167
+ return current.length;
168
+ }
169
+ };