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.
- package/INSTALLATION.md +144 -0
- package/LICENSE +21 -0
- package/README.md +621 -0
- package/bin/aiwaf.js +349 -0
- package/index.js +62 -0
- package/lib/adonisMiddleware.js +82 -0
- package/lib/anomalyDetector.js +221 -0
- package/lib/blacklistManager.js +134 -0
- package/lib/blockResponses.js +25 -0
- package/lib/csvStore.js +84 -0
- package/lib/dynamicKeyword.js +42 -0
- package/lib/dynamicKeywordStore.js +169 -0
- package/lib/exemptionStore.js +204 -0
- package/lib/exemptions.js +56 -0
- package/lib/fastifyPlugin.js +49 -0
- package/lib/featureUtils.js +183 -0
- package/lib/geoBlocker.js +159 -0
- package/lib/geoPolicy.js +42 -0
- package/lib/geoStore.js +111 -0
- package/lib/hapiPlugin.js +92 -0
- package/lib/headerValidation.js +275 -0
- package/lib/honeypotDetector.js +91 -0
- package/lib/isolationForest.js +117 -0
- package/lib/keywordDetector.js +5 -0
- package/lib/keywordFallbackStore.js +39 -0
- package/lib/koaMiddleware.js +68 -0
- package/lib/middlewareLogger.js +123 -0
- package/lib/middlewarePlan.js +72 -0
- package/lib/modelSecurity.js +17 -0
- package/lib/modelStore.js +129 -0
- package/lib/nestMiddleware.js +12 -0
- package/lib/nextMiddleware.js +78 -0
- package/lib/pathManifest.js +533 -0
- package/lib/pathRules.js +184 -0
- package/lib/rateLimiter.js +153 -0
- package/lib/redisClient.js +35 -0
- package/lib/requestLogStore.js +167 -0
- package/lib/runtimeUtils.js +166 -0
- package/lib/settingsCompat.js +140 -0
- package/lib/sourceAst.js +294 -0
- package/lib/trainingLogic.js +87 -0
- package/lib/uuidDetector.js +46 -0
- package/lib/wafMiddleware.js +459 -0
- package/lib/wasmAdapter.js +480 -0
- package/lib/whois.js +38 -0
- package/package.json +85 -0
- package/resources/model.json +9536 -0
- package/train.js +595 -0
- package/utils/cache.js +3 -0
- package/utils/db.js +11 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
|
|
4
|
+
class KeywordFallbackStore {
|
|
5
|
+
constructor(storagePath) {
|
|
6
|
+
this.storagePath = storagePath;
|
|
7
|
+
this.keywords = {};
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
load() {
|
|
11
|
+
if (!fs.existsSync(this.storagePath)) {
|
|
12
|
+
this.keywords = {};
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
this.keywords = JSON.parse(fs.readFileSync(this.storagePath, 'utf8'));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
save() {
|
|
19
|
+
fs.mkdirSync(path.dirname(this.storagePath), { recursive: true });
|
|
20
|
+
fs.writeFileSync(this.storagePath, JSON.stringify(this.keywords, null, 2), 'utf8');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
add(keyword, count = 1) {
|
|
24
|
+
this.load();
|
|
25
|
+
const normalized = String(keyword || '');
|
|
26
|
+
if (!normalized) return;
|
|
27
|
+
this.keywords[normalized] = Number(this.keywords[normalized] || 0) + Number(count || 1);
|
|
28
|
+
this.save();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
top(limit = 10) {
|
|
32
|
+
this.load();
|
|
33
|
+
return Object.entries(this.keywords)
|
|
34
|
+
.sort((a, b) => b[1] - a[1])
|
|
35
|
+
.slice(0, Number(limit || 10));
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
module.exports = KeywordFallbackStore;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
const createExpressMiddleware = require('./wafMiddleware');
|
|
2
|
+
|
|
3
|
+
function createExpressLikeResponse(ctx) {
|
|
4
|
+
const res = {
|
|
5
|
+
locals: {},
|
|
6
|
+
on: (...args) => ctx.res.on(...args),
|
|
7
|
+
get statusCode() {
|
|
8
|
+
return ctx.status;
|
|
9
|
+
},
|
|
10
|
+
set statusCode(code) {
|
|
11
|
+
ctx.status = code;
|
|
12
|
+
},
|
|
13
|
+
status(code) {
|
|
14
|
+
ctx.status = code;
|
|
15
|
+
res._handled = true;
|
|
16
|
+
return res;
|
|
17
|
+
},
|
|
18
|
+
json(payload) {
|
|
19
|
+
ctx.type = 'application/json';
|
|
20
|
+
ctx.body = payload;
|
|
21
|
+
res._handled = true;
|
|
22
|
+
return res;
|
|
23
|
+
},
|
|
24
|
+
send(payload) {
|
|
25
|
+
ctx.body = payload;
|
|
26
|
+
res._handled = true;
|
|
27
|
+
return res;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
return res;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = function createKoaMiddleware(opts = {}) {
|
|
34
|
+
const middleware = createExpressMiddleware(opts);
|
|
35
|
+
|
|
36
|
+
return async (ctx, next) => {
|
|
37
|
+
const res = createExpressLikeResponse(ctx);
|
|
38
|
+
const req = ctx.req; // Raw Node.js http.IncomingMessage - already has headers
|
|
39
|
+
|
|
40
|
+
// Only set these if not already available
|
|
41
|
+
if (!req.path) req.path = ctx.path;
|
|
42
|
+
if (!req.url) req.url = ctx.url;
|
|
43
|
+
if (!req.ip) req.ip = ctx.ip;
|
|
44
|
+
|
|
45
|
+
// Don't override headers - use what's already on the raw request
|
|
46
|
+
// ctx.headers is Koa's parsed version, but req.headers from Node.js has the originals
|
|
47
|
+
|
|
48
|
+
await new Promise(resolve => {
|
|
49
|
+
let resolved = false;
|
|
50
|
+
const finish = () => {
|
|
51
|
+
if (resolved) return;
|
|
52
|
+
resolved = true;
|
|
53
|
+
resolve();
|
|
54
|
+
};
|
|
55
|
+
const maybePromise = middleware(req, res, finish);
|
|
56
|
+
if (res._handled) {
|
|
57
|
+
finish();
|
|
58
|
+
}
|
|
59
|
+
Promise.resolve(maybePromise).then(finish).catch(finish);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
if (ctx.body !== undefined) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
await next();
|
|
67
|
+
};
|
|
68
|
+
};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const requestLogStore = require('./requestLogStore');
|
|
4
|
+
|
|
5
|
+
let enabled = false;
|
|
6
|
+
let outputPath = 'logs/aiwaf-requests.jsonl';
|
|
7
|
+
let logToDb = false;
|
|
8
|
+
let logToCsv = false;
|
|
9
|
+
let csvPath = 'logs/aiwaf-requests.csv';
|
|
10
|
+
let csvHeaderWritten = false;
|
|
11
|
+
|
|
12
|
+
function escapeCsv(value) {
|
|
13
|
+
const str = String(value ?? '');
|
|
14
|
+
if (str.includes('"') || str.includes(',') || str.includes('\n')) {
|
|
15
|
+
return `"${str.replace(/"/g, '""')}"`;
|
|
16
|
+
}
|
|
17
|
+
return str;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function csvLineFromEvent(event) {
|
|
21
|
+
const cells = [
|
|
22
|
+
event.timestamp || '',
|
|
23
|
+
event.ip || '',
|
|
24
|
+
event.method || '',
|
|
25
|
+
event.path || '',
|
|
26
|
+
event.status || '',
|
|
27
|
+
event.responseTime || '',
|
|
28
|
+
event.blocked ? '1' : '0',
|
|
29
|
+
event.reason || '',
|
|
30
|
+
event.country || '',
|
|
31
|
+
event.userAgent || ''
|
|
32
|
+
];
|
|
33
|
+
return `${cells.map(escapeCsv).join(',')}\n`;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function writeCsvEvent(event) {
|
|
37
|
+
if (!logToCsv) return;
|
|
38
|
+
try {
|
|
39
|
+
ensureDirectoryExists(csvPath);
|
|
40
|
+
if (!csvHeaderWritten && !fs.existsSync(csvPath)) {
|
|
41
|
+
fs.appendFileSync(csvPath, 'timestamp,ip,method,path,status,response_time,blocked,reason,country,user_agent\n');
|
|
42
|
+
csvHeaderWritten = true;
|
|
43
|
+
}
|
|
44
|
+
fs.appendFileSync(csvPath, csvLineFromEvent(event), 'utf8');
|
|
45
|
+
} catch (err) {
|
|
46
|
+
// CSV logging should never take down request handling.
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function ensureDirectoryExists(filePath) {
|
|
51
|
+
const dir = path.dirname(filePath);
|
|
52
|
+
if (!fs.existsSync(dir)) {
|
|
53
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function writeEvent(event) {
|
|
58
|
+
if (!enabled) return;
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
ensureDirectoryExists(outputPath);
|
|
62
|
+
fs.appendFileSync(outputPath, `${JSON.stringify(event)}\n`, 'utf8');
|
|
63
|
+
} catch (err) {
|
|
64
|
+
// Logging should never take down request handling.
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
writeCsvEvent(event);
|
|
68
|
+
|
|
69
|
+
if (logToDb) {
|
|
70
|
+
requestLogStore.insert(event).catch(() => {
|
|
71
|
+
// Keep a durable non-DB copy when DB storage fails.
|
|
72
|
+
if (!logToCsv) {
|
|
73
|
+
logToCsv = true;
|
|
74
|
+
}
|
|
75
|
+
writeCsvEvent(event);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = {
|
|
81
|
+
init(opts = {}) {
|
|
82
|
+
enabled = !!opts.AIWAF_MIDDLEWARE_LOGGING;
|
|
83
|
+
outputPath = opts.AIWAF_MIDDLEWARE_LOG_PATH || outputPath;
|
|
84
|
+
logToDb = !!opts.AIWAF_MIDDLEWARE_LOG_DB;
|
|
85
|
+
logToCsv = !!opts.AIWAF_MIDDLEWARE_LOG_CSV || logToDb;
|
|
86
|
+
csvPath = opts.AIWAF_MIDDLEWARE_LOG_CSV_PATH || csvPath;
|
|
87
|
+
csvHeaderWritten = false;
|
|
88
|
+
if (logToDb) {
|
|
89
|
+
requestLogStore.initialize().catch(() => {});
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
|
|
93
|
+
attach(req, res, context) {
|
|
94
|
+
if (!enabled) return;
|
|
95
|
+
|
|
96
|
+
const start = Date.now();
|
|
97
|
+
res.on('finish', () => {
|
|
98
|
+
const decision = res.locals?.aiwafDecision || {};
|
|
99
|
+
|
|
100
|
+
writeEvent({
|
|
101
|
+
timestamp: new Date().toISOString(),
|
|
102
|
+
ip: context.ip,
|
|
103
|
+
method: req.method,
|
|
104
|
+
path: req.path || req.url,
|
|
105
|
+
status: res.statusCode,
|
|
106
|
+
responseTime: Date.now() - start,
|
|
107
|
+
blocked: !!decision.blocked,
|
|
108
|
+
reason: decision.reason || '',
|
|
109
|
+
country: decision.country || '',
|
|
110
|
+
userAgent: req.headers?.['user-agent'] || ''
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
markBlocked(res, reason, country = '') {
|
|
116
|
+
if (!res.locals) res.locals = {};
|
|
117
|
+
res.locals.aiwafDecision = {
|
|
118
|
+
blocked: true,
|
|
119
|
+
reason,
|
|
120
|
+
country
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
};
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const AUTO_SENTINELS = new Set(['all', 'auto', 'aiwaf.all']);
|
|
2
|
+
|
|
3
|
+
function toList(value) {
|
|
4
|
+
if (value === undefined || value === null) return null;
|
|
5
|
+
if (Array.isArray(value)) return value;
|
|
6
|
+
if (typeof value === 'string') {
|
|
7
|
+
return value.split(',').map(item => item.trim()).filter(Boolean);
|
|
8
|
+
}
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function isAutoSelection(requested) {
|
|
13
|
+
const list = toList(requested);
|
|
14
|
+
if (!list) return false;
|
|
15
|
+
return list.some(item => AUTO_SENTINELS.has(String(item).trim().toLowerCase()));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function shouldEnableLogging(accessLog) {
|
|
19
|
+
return !String(accessLog || '').trim();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function shouldEnableGeo({ geoEnabledFlag, staticBlockCountries, dynamicBlockCountries }) {
|
|
23
|
+
if (geoEnabledFlag) return true;
|
|
24
|
+
if ((staticBlockCountries || []).some(country => String(country || '').trim())) return true;
|
|
25
|
+
if ((dynamicBlockCountries || []).some(country => String(country || '').trim())) return true;
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function shouldEnableUuidTamper({ hasUuidRoutes }) {
|
|
30
|
+
if (hasUuidRoutes === undefined || hasUuidRoutes === null) return true;
|
|
31
|
+
return !!hasUuidRoutes;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function planEnabledMiddlewares({
|
|
35
|
+
orderedAvailable,
|
|
36
|
+
requested,
|
|
37
|
+
disabled,
|
|
38
|
+
accessLog,
|
|
39
|
+
geoEnabledFlag,
|
|
40
|
+
staticBlockCountries,
|
|
41
|
+
dynamicBlockCountries,
|
|
42
|
+
hasUuidRoutes
|
|
43
|
+
}) {
|
|
44
|
+
const available = new Set(orderedAvailable);
|
|
45
|
+
const requestedList = toList(requested);
|
|
46
|
+
const disabledSet = new Set((toList(disabled) || []).filter(name => available.has(name)));
|
|
47
|
+
let enabled;
|
|
48
|
+
|
|
49
|
+
if (!requestedList) {
|
|
50
|
+
enabled = new Set(available);
|
|
51
|
+
} else if (isAutoSelection(requestedList)) {
|
|
52
|
+
enabled = new Set(available);
|
|
53
|
+
if (!shouldEnableLogging(accessLog)) enabled.delete('logging');
|
|
54
|
+
if (!shouldEnableGeo({ geoEnabledFlag, staticBlockCountries, dynamicBlockCountries })) {
|
|
55
|
+
enabled.delete('geo_block');
|
|
56
|
+
}
|
|
57
|
+
if (!shouldEnableUuidTamper({ hasUuidRoutes })) enabled.delete('uuid_tamper');
|
|
58
|
+
} else {
|
|
59
|
+
enabled = new Set(requestedList.filter(name => available.has(name)));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
disabledSet.forEach(name => enabled.delete(name));
|
|
63
|
+
return enabled;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
module.exports = {
|
|
67
|
+
isAutoSelection,
|
|
68
|
+
shouldEnableLogging,
|
|
69
|
+
shouldEnableGeo,
|
|
70
|
+
shouldEnableUuidTamper,
|
|
71
|
+
planEnabledMiddlewares
|
|
72
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const path = require('path');
|
|
2
|
+
|
|
3
|
+
function isTrustedModelPath(modelPath, { defaultPath = null, allowCustom = false } = {}) {
|
|
4
|
+
if (!modelPath) return false;
|
|
5
|
+
if (allowCustom) return true;
|
|
6
|
+
if (!defaultPath) return false;
|
|
7
|
+
|
|
8
|
+
try {
|
|
9
|
+
return path.resolve(modelPath) === path.resolve(defaultPath);
|
|
10
|
+
} catch (err) {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = {
|
|
16
|
+
isTrustedModelPath
|
|
17
|
+
};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const db = require('../utils/db');
|
|
4
|
+
|
|
5
|
+
const cache = new Map();
|
|
6
|
+
|
|
7
|
+
function getCacheKey(opts) {
|
|
8
|
+
return opts.AIWAF_MODEL_CACHE_KEY || 'aiwaf:model';
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function getModelPath(opts) {
|
|
12
|
+
return opts.AIWAF_MODEL_PATH || path.join(__dirname, '..', 'resources', 'model.json');
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function ensureDb() {
|
|
16
|
+
const hasTable = await db.schema.hasTable('model_artifacts');
|
|
17
|
+
if (!hasTable) {
|
|
18
|
+
await db.schema.createTable('model_artifacts', table => {
|
|
19
|
+
table.increments('id').primary();
|
|
20
|
+
table.timestamp('created_at').defaultTo(db.fn.now());
|
|
21
|
+
table.string('storage').defaultTo('db');
|
|
22
|
+
table.text('payload');
|
|
23
|
+
table.text('metadata');
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function cacheGet(key) {
|
|
29
|
+
const entry = cache.get(key);
|
|
30
|
+
if (!entry) return null;
|
|
31
|
+
if (entry.expiresAt && Date.now() > entry.expiresAt) {
|
|
32
|
+
cache.delete(key);
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
return entry.value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function cacheSet(key, value, ttlSeconds) {
|
|
39
|
+
const ttl = Number(ttlSeconds) > 0 ? Number(ttlSeconds) : 0;
|
|
40
|
+
const expiresAt = ttl > 0 ? Date.now() + ttl * 1000 : null;
|
|
41
|
+
cache.set(key, { value, expiresAt });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function loadFromFile(opts) {
|
|
45
|
+
const modelPath = getModelPath(opts);
|
|
46
|
+
if (!fs.existsSync(modelPath)) return null;
|
|
47
|
+
const raw = fs.readFileSync(modelPath, 'utf8');
|
|
48
|
+
return JSON.parse(raw);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function saveToFile(opts, payload) {
|
|
52
|
+
const modelPath = getModelPath(opts);
|
|
53
|
+
fs.mkdirSync(path.dirname(modelPath), { recursive: true });
|
|
54
|
+
fs.writeFileSync(modelPath, JSON.stringify(payload, null, 2), 'utf8');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function loadFromDb() {
|
|
58
|
+
await ensureDb();
|
|
59
|
+
const row = await db('model_artifacts').select('*').orderBy('created_at', 'desc').first();
|
|
60
|
+
if (!row || !row.payload) return null;
|
|
61
|
+
return JSON.parse(row.payload);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function saveToDb(payload, metadata) {
|
|
65
|
+
await ensureDb();
|
|
66
|
+
await db('model_artifacts').insert({
|
|
67
|
+
payload: JSON.stringify(payload),
|
|
68
|
+
metadata: JSON.stringify(metadata || {})
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
module.exports = {
|
|
73
|
+
async load(opts = {}) {
|
|
74
|
+
const storage = opts.AIWAF_MODEL_STORAGE || 'file';
|
|
75
|
+
const fallback = opts.AIWAF_MODEL_STORAGE_FALLBACK || 'file';
|
|
76
|
+
const cacheKey = getCacheKey(opts);
|
|
77
|
+
|
|
78
|
+
if (storage === 'cache') {
|
|
79
|
+
const cached = cacheGet(cacheKey);
|
|
80
|
+
if (cached) return cached;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
if (storage === 'file') return await loadFromFile(opts);
|
|
85
|
+
if (storage === 'db') return await loadFromDb();
|
|
86
|
+
if (storage === 'cache') return null;
|
|
87
|
+
} catch (err) {
|
|
88
|
+
// fallthrough to fallback
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (fallback && fallback !== storage) {
|
|
92
|
+
try {
|
|
93
|
+
if (fallback === 'file') return await loadFromFile(opts);
|
|
94
|
+
if (fallback === 'db') return await loadFromDb();
|
|
95
|
+
} catch (err) {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return null;
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
async save(opts = {}, payload, metadata = {}) {
|
|
104
|
+
const storage = opts.AIWAF_MODEL_STORAGE || 'file';
|
|
105
|
+
const fallback = opts.AIWAF_MODEL_STORAGE_FALLBACK || 'file';
|
|
106
|
+
const cacheKey = getCacheKey(opts);
|
|
107
|
+
const cacheTtl = opts.AIWAF_MODEL_CACHE_TTL || 0;
|
|
108
|
+
|
|
109
|
+
if (storage === 'cache') {
|
|
110
|
+
cacheSet(cacheKey, payload, cacheTtl);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
try {
|
|
115
|
+
if (storage === 'file') return await saveToFile(opts, payload);
|
|
116
|
+
if (storage === 'db') return await saveToDb(payload, metadata);
|
|
117
|
+
} catch (err) {
|
|
118
|
+
// fallthrough to fallback
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (fallback && fallback !== storage) {
|
|
122
|
+
if (fallback === 'file') return saveToFile(opts, payload);
|
|
123
|
+
if (fallback === 'db') return saveToDb(payload, metadata);
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
cacheGet,
|
|
128
|
+
cacheSet
|
|
129
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
const createExpressMiddleware = require('./wafMiddleware');
|
|
2
|
+
|
|
3
|
+
module.exports = function createNestMiddleware(opts = {}) {
|
|
4
|
+
const middleware = createExpressMiddleware(opts);
|
|
5
|
+
|
|
6
|
+
return class AIWAFNestMiddleware {
|
|
7
|
+
use(req, res, next) {
|
|
8
|
+
// Express middleware - req/res already have headers set by Express itself
|
|
9
|
+
return middleware(req, res, next);
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
const createExpressMiddleware = require('./wafMiddleware');
|
|
2
|
+
|
|
3
|
+
function createExpressLikeResponse(res) {
|
|
4
|
+
const wrapped = {
|
|
5
|
+
locals: {},
|
|
6
|
+
on: (...args) => res.on(...args),
|
|
7
|
+
get statusCode() {
|
|
8
|
+
return res.statusCode;
|
|
9
|
+
},
|
|
10
|
+
set statusCode(code) {
|
|
11
|
+
res.statusCode = code;
|
|
12
|
+
},
|
|
13
|
+
status(code) {
|
|
14
|
+
res.statusCode = code;
|
|
15
|
+
wrapped._handled = true;
|
|
16
|
+
return wrapped;
|
|
17
|
+
},
|
|
18
|
+
json(payload) {
|
|
19
|
+
if (typeof res.setHeader === 'function') {
|
|
20
|
+
res.setHeader('content-type', 'application/json');
|
|
21
|
+
}
|
|
22
|
+
res.end(JSON.stringify(payload));
|
|
23
|
+
wrapped._handled = true;
|
|
24
|
+
return wrapped;
|
|
25
|
+
},
|
|
26
|
+
send(payload) {
|
|
27
|
+
if (payload !== undefined && typeof payload !== 'string' && !Buffer.isBuffer(payload)) {
|
|
28
|
+
if (typeof res.setHeader === 'function') {
|
|
29
|
+
res.setHeader('content-type', 'application/json');
|
|
30
|
+
}
|
|
31
|
+
res.end(JSON.stringify(payload));
|
|
32
|
+
} else {
|
|
33
|
+
res.end(payload);
|
|
34
|
+
}
|
|
35
|
+
wrapped._handled = true;
|
|
36
|
+
return wrapped;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
return wrapped;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function wrapHandler(handler, opts) {
|
|
43
|
+
const middleware = createExpressMiddleware(opts);
|
|
44
|
+
|
|
45
|
+
return async (req, res) => {
|
|
46
|
+
const handled = await new Promise(resolve => {
|
|
47
|
+
let done = false;
|
|
48
|
+
const finish = () => {
|
|
49
|
+
if (done) return;
|
|
50
|
+
done = true;
|
|
51
|
+
resolve(wrappedRes._handled === true);
|
|
52
|
+
};
|
|
53
|
+
res.on('finish', finish);
|
|
54
|
+
res.on('close', finish);
|
|
55
|
+
const wrappedRes = createExpressLikeResponse(res);
|
|
56
|
+
const maybePromise = middleware(req, wrappedRes, () => finish());
|
|
57
|
+
if (wrappedRes._handled) {
|
|
58
|
+
finish();
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
Promise.resolve(maybePromise).then(finish).catch(finish);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
if (handled) return;
|
|
65
|
+
if (res.writableEnded || res.headersSent) return;
|
|
66
|
+
if (res.finished) return;
|
|
67
|
+
return handler(req, res);
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
module.exports = function createNextHandler(handlerOrOpts, maybeOpts) {
|
|
72
|
+
if (typeof handlerOrOpts === 'function') {
|
|
73
|
+
return wrapHandler(handlerOrOpts, maybeOpts || {});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const opts = handlerOrOpts || {};
|
|
77
|
+
return (handler) => wrapHandler(handler, opts);
|
|
78
|
+
};
|