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,533 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const { normalizePath } = require('./pathRules');
|
|
5
|
+
const { analyzeHandlerAst } = require('./sourceAst');
|
|
6
|
+
|
|
7
|
+
const SCHEMA_VERSION = '1.0';
|
|
8
|
+
const DEFAULT_MANIFEST_PATH = path.join('.aiwaf', 'paths.json');
|
|
9
|
+
const MIDDLEWARE_NAMES = new Set([
|
|
10
|
+
'geo_block',
|
|
11
|
+
'ip_keyword_block',
|
|
12
|
+
'rate_limit',
|
|
13
|
+
'ai_anomaly',
|
|
14
|
+
'honeypot',
|
|
15
|
+
'uuid_tamper',
|
|
16
|
+
'header_validation',
|
|
17
|
+
'logging'
|
|
18
|
+
]);
|
|
19
|
+
|
|
20
|
+
function stableJson(value) {
|
|
21
|
+
if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
|
|
22
|
+
if (value && typeof value === 'object') {
|
|
23
|
+
return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(',')}}`;
|
|
24
|
+
}
|
|
25
|
+
return JSON.stringify(value);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function computeContextHash(value) {
|
|
29
|
+
return crypto.createHash('sha256').update(stableJson(value)).digest('hex');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function nowUtcIso() {
|
|
33
|
+
return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function sourceSignals(handler) {
|
|
37
|
+
const source = typeof handler === 'function' ? Function.prototype.toString.call(handler) : '';
|
|
38
|
+
const lower = source.toLowerCase();
|
|
39
|
+
const signals = [];
|
|
40
|
+
const formSignals = [];
|
|
41
|
+
let requestBody = false;
|
|
42
|
+
let payloadType = '';
|
|
43
|
+
let score = 0;
|
|
44
|
+
let formScore = 0;
|
|
45
|
+
|
|
46
|
+
if (/\bres\.json\s*\(|\breply\.send\s*\(\s*[{[]|\bctx\.body\s*=\s*[{[]/.test(source)) {
|
|
47
|
+
score += 60;
|
|
48
|
+
signals.push('json_response');
|
|
49
|
+
}
|
|
50
|
+
if (/\breq\.body\b|\brequest\.body\b/.test(source)) {
|
|
51
|
+
score += 20;
|
|
52
|
+
requestBody = true;
|
|
53
|
+
payloadType = 'json';
|
|
54
|
+
signals.push('request.body');
|
|
55
|
+
}
|
|
56
|
+
if (/application\/json/.test(lower)) {
|
|
57
|
+
score += 30;
|
|
58
|
+
payloadType = 'json';
|
|
59
|
+
signals.push('content-type:application/json');
|
|
60
|
+
}
|
|
61
|
+
if (/\breq\.file\b|\breq\.files\b|\bformdata\b|\bmultipart\b/.test(lower)) {
|
|
62
|
+
formScore += 45;
|
|
63
|
+
requestBody = true;
|
|
64
|
+
payloadType = 'form';
|
|
65
|
+
formSignals.push('request.form');
|
|
66
|
+
}
|
|
67
|
+
if (/\bres\.render\s*\(|\bctx\.render\s*\(|\bredirect\s*\(/.test(source)) {
|
|
68
|
+
formScore += 40;
|
|
69
|
+
formSignals.push('render_or_redirect');
|
|
70
|
+
if (/\breq\.body\b|\brequest\.body\b/.test(source)) {
|
|
71
|
+
formScore += 45;
|
|
72
|
+
requestBody = true;
|
|
73
|
+
payloadType = 'form';
|
|
74
|
+
formSignals.push('request.body');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
score,
|
|
80
|
+
signals: Array.from(new Set(signals)).sort(),
|
|
81
|
+
requestBody,
|
|
82
|
+
formScore,
|
|
83
|
+
formSignals: Array.from(new Set(formSignals)).sort(),
|
|
84
|
+
payloadType
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function detectApiEndpoint(handler, routePath = '', methods = []) {
|
|
89
|
+
const pathLower = normalizePath(routePath).toLowerCase();
|
|
90
|
+
const signals = [];
|
|
91
|
+
let score = 0;
|
|
92
|
+
|
|
93
|
+
if (pathLower.startsWith('/api/') || pathLower.includes('/api/')) {
|
|
94
|
+
score += 30;
|
|
95
|
+
signals.push('path:/api');
|
|
96
|
+
}
|
|
97
|
+
if (['/graphql', '/token'].includes(pathLower.replace(/\/$/, ''))) {
|
|
98
|
+
score += 30;
|
|
99
|
+
signals.push(`path:${pathLower.replace(/\/$/, '')}`);
|
|
100
|
+
}
|
|
101
|
+
if (pathLower.includes('/webhook') || pathLower.includes('/callback')) {
|
|
102
|
+
score += 25;
|
|
103
|
+
signals.push('path:webhook');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const ast = analyzeHandlerAst(handler);
|
|
107
|
+
const source = ast.available
|
|
108
|
+
? {
|
|
109
|
+
score: ast.apiScore,
|
|
110
|
+
signals: ast.apiSignals,
|
|
111
|
+
requestBody: ast.requestBody,
|
|
112
|
+
formScore: ast.formScore,
|
|
113
|
+
formSignals: ast.formSignals,
|
|
114
|
+
payloadType: ast.payloadType
|
|
115
|
+
}
|
|
116
|
+
: sourceSignals(handler);
|
|
117
|
+
score += source.score;
|
|
118
|
+
signals.push(...source.signals);
|
|
119
|
+
|
|
120
|
+
const isForm = source.formScore >= 50 && source.formScore >= score;
|
|
121
|
+
const isApi = score >= 50 && !isForm;
|
|
122
|
+
return {
|
|
123
|
+
isApi,
|
|
124
|
+
responseType: isApi ? 'json' : (isForm ? 'mixed' : ''),
|
|
125
|
+
payloadType: source.payloadType || (isApi ? 'json' : ''),
|
|
126
|
+
confidence: Math.min(0.99, score / 100),
|
|
127
|
+
signals: Array.from(new Set(signals)).sort(),
|
|
128
|
+
requestBody: source.requestBody || methods.some(method => method !== 'GET'),
|
|
129
|
+
formConfidence: Math.min(0.99, source.formScore / 100),
|
|
130
|
+
formSignals: source.formSignals
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function detectAuthEndpoint(handler, routePath = '') {
|
|
135
|
+
const pathLower = normalizePath(routePath).toLowerCase();
|
|
136
|
+
const ast = analyzeHandlerAst(handler);
|
|
137
|
+
const source = typeof handler === 'function' ? Function.prototype.toString.call(handler).toLowerCase() : '';
|
|
138
|
+
const signals = [];
|
|
139
|
+
let score = 0;
|
|
140
|
+
let action = '';
|
|
141
|
+
|
|
142
|
+
const priorities = { login: 50, token_login: 50, logout: 40, register: 30, token_auth: 20 };
|
|
143
|
+
const getPriority = a => priorities[a] || 0;
|
|
144
|
+
const mergeAction = (curr, cand) => (!curr ? cand : (getPriority(cand) > getPriority(curr) ? cand : curr));
|
|
145
|
+
|
|
146
|
+
if (pathLower.includes('/logout') || pathLower.includes('/signout')) {
|
|
147
|
+
score += 40;
|
|
148
|
+
action = mergeAction(action, 'logout');
|
|
149
|
+
signals.push('path:logout');
|
|
150
|
+
} else if (pathLower.includes('/register') || pathLower.includes('/signup')) {
|
|
151
|
+
score += 40;
|
|
152
|
+
action = mergeAction(action, 'register');
|
|
153
|
+
signals.push('path:register');
|
|
154
|
+
} else if (pathLower.includes('/login') || pathLower.includes('/signin') || pathLower.includes('/token')) {
|
|
155
|
+
score += 40;
|
|
156
|
+
action = mergeAction(action, pathLower.includes('/token') ? 'token_login' : 'login');
|
|
157
|
+
signals.push('path:auth');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (/bcrypt|comparepassword|jsonwebtoken|jwt|passport|login|authenticate|createsession|createaccesstoken/.test(source)) {
|
|
161
|
+
score += 50;
|
|
162
|
+
action = mergeAction(action, 'login');
|
|
163
|
+
signals.push('auth_source_signal');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (ast.available && ast.authScore) {
|
|
167
|
+
score += ast.authScore;
|
|
168
|
+
action = mergeAction(action, ast.authAction);
|
|
169
|
+
signals.push(...ast.authSignals);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
isAuth: score >= 50,
|
|
174
|
+
action: action || 'login',
|
|
175
|
+
confidence: Math.min(0.99, score / 100),
|
|
176
|
+
signals
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function classifyRoute(routePath, { methods = [], metadata = {} } = {}) {
|
|
181
|
+
const normalized = normalizePath(routePath);
|
|
182
|
+
const pathLower = normalized.toLowerCase();
|
|
183
|
+
const methodSet = new Set((methods || []).map(method => String(method).toUpperCase()));
|
|
184
|
+
let category = 'unknown';
|
|
185
|
+
let responseType = 'html';
|
|
186
|
+
let authRequired = !!metadata.auth_required || pathLower.startsWith('/portal/') || pathLower.startsWith('/dashboard/');
|
|
187
|
+
const protections = {
|
|
188
|
+
rate_limit: { requests: 60, window_seconds: 60 },
|
|
189
|
+
header_validation: { enabled: true },
|
|
190
|
+
ip_keyword_block: { enabled: true },
|
|
191
|
+
ai_anomaly: { enabled: true }
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
if (
|
|
195
|
+
pathLower.startsWith('/static/')
|
|
196
|
+
|| pathLower.startsWith('/media/')
|
|
197
|
+
|| pathLower.startsWith('/assets/')
|
|
198
|
+
|| /\.(css|js|png|jpe?g|gif|ico|svg|woff2?|ttf)$/.test(pathLower)
|
|
199
|
+
) {
|
|
200
|
+
category = 'static';
|
|
201
|
+
protections.header_validation = { enabled: false };
|
|
202
|
+
protections.ai_anomaly = { enabled: false };
|
|
203
|
+
protections.honeypot = { enabled: false };
|
|
204
|
+
} else if (pathLower.includes('/admin')) {
|
|
205
|
+
category = 'admin';
|
|
206
|
+
authRequired = true;
|
|
207
|
+
protections.rate_limit = { requests: 30, window_seconds: 60 };
|
|
208
|
+
} else if (metadata.auth_action || metadata.auth_confidence || pathLower.includes('/login') || pathLower.includes('/signin')) {
|
|
209
|
+
category = 'auth';
|
|
210
|
+
protections.rate_limit = { requests: 30, window_seconds: 60 };
|
|
211
|
+
protections.honeypot = { enabled: true };
|
|
212
|
+
} else if (metadata.payload_type === 'form' || metadata.form_confidence) {
|
|
213
|
+
category = 'form';
|
|
214
|
+
responseType = metadata.response_type || 'mixed';
|
|
215
|
+
protections.rate_limit = { requests: 30, window_seconds: 60 };
|
|
216
|
+
protections.honeypot = { enabled: true };
|
|
217
|
+
} else if (metadata.api_confidence || pathLower.startsWith('/api/') || metadata.response_type === 'json') {
|
|
218
|
+
category = 'api';
|
|
219
|
+
responseType = 'json';
|
|
220
|
+
protections.rate_limit = { requests: 120, window_seconds: 60 };
|
|
221
|
+
protections.api_rate_limit = { requests: 120, window_seconds: 60 };
|
|
222
|
+
protections.honeypot = { enabled: false };
|
|
223
|
+
} else if (pathLower.includes('/upload') || pathLower.includes('/files')) {
|
|
224
|
+
category = 'upload';
|
|
225
|
+
protections.rate_limit = { requests: 20, window_seconds: 60 };
|
|
226
|
+
} else if (authRequired) {
|
|
227
|
+
category = 'app';
|
|
228
|
+
protections.rate_limit = { requests: 90, window_seconds: 60 };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (methodSet.has('POST') && !['api', 'upload'].includes(category)) {
|
|
232
|
+
protections.rate_limit = { requests: 30, window_seconds: 60 };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return {
|
|
236
|
+
category,
|
|
237
|
+
response_type: metadata.response_type || responseType,
|
|
238
|
+
auth_required: authRequired,
|
|
239
|
+
protections,
|
|
240
|
+
...(metadata.auth_action ? { auth_action: metadata.auth_action } : {}),
|
|
241
|
+
...(metadata.auth_confidence !== undefined ? { auth_confidence: metadata.auth_confidence } : {}),
|
|
242
|
+
...(metadata.auth_signals ? { auth_signals: metadata.auth_signals } : {}),
|
|
243
|
+
...(metadata.api_confidence !== undefined ? { api_confidence: metadata.api_confidence } : {}),
|
|
244
|
+
...(metadata.api_signals ? { api_signals: metadata.api_signals } : {}),
|
|
245
|
+
...(metadata.payload_type ? { payload_type: metadata.payload_type } : {}),
|
|
246
|
+
...(metadata.form_confidence !== undefined ? { form_confidence: metadata.form_confidence } : {}),
|
|
247
|
+
...(metadata.form_signals ? { form_signals: metadata.form_signals } : {}),
|
|
248
|
+
...(metadata.request_body !== undefined ? { request_body: !!metadata.request_body } : {})
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function buildRouteEntry({ routePath, methods = [], view = '', name = '', metadata = {} }) {
|
|
253
|
+
const normalized = normalizePath(routePath);
|
|
254
|
+
const methodsList = Array.from(new Set(
|
|
255
|
+
(methods || [])
|
|
256
|
+
.map(method => String(method).toUpperCase())
|
|
257
|
+
.filter(method => method && !['HEAD', 'OPTIONS'].includes(method))
|
|
258
|
+
)).sort();
|
|
259
|
+
return [normalized, {
|
|
260
|
+
methods: methodsList,
|
|
261
|
+
view: String(view || ''),
|
|
262
|
+
name: String(name || ''),
|
|
263
|
+
...classifyRoute(normalized, { methods: methodsList, metadata })
|
|
264
|
+
}];
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function buildManifest({ framework, routes, appContext = {} }) {
|
|
268
|
+
const normalizedRoutes = Object.fromEntries(
|
|
269
|
+
Object.entries(routes || {})
|
|
270
|
+
.sort(([left], [right]) => normalizePath(left).localeCompare(normalizePath(right)))
|
|
271
|
+
.map(([routePath, data]) => [normalizePath(routePath), { ...data }])
|
|
272
|
+
);
|
|
273
|
+
const context = { framework, routes: normalizedRoutes, app_context: { ...appContext } };
|
|
274
|
+
return {
|
|
275
|
+
schema_version: SCHEMA_VERSION,
|
|
276
|
+
framework,
|
|
277
|
+
context_hash: computeContextHash(context),
|
|
278
|
+
generated_at: nowUtcIso(),
|
|
279
|
+
routes: normalizedRoutes
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function writeManifest(manifest, outputPath = DEFAULT_MANIFEST_PATH) {
|
|
284
|
+
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
|
285
|
+
fs.writeFileSync(outputPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
|
|
286
|
+
return outputPath;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function loadManifest(manifestPath = DEFAULT_MANIFEST_PATH) {
|
|
290
|
+
try {
|
|
291
|
+
if (!fs.existsSync(manifestPath)) return null;
|
|
292
|
+
const parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
|
293
|
+
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
294
|
+
} catch (err) {
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function rateLimitOverride(config) {
|
|
300
|
+
const override = {};
|
|
301
|
+
if (config.WINDOW !== undefined) override.WINDOW = config.WINDOW;
|
|
302
|
+
if (config.MAX !== undefined) override.MAX = config.MAX;
|
|
303
|
+
if (config.FLOOD !== undefined) override.FLOOD = config.FLOOD;
|
|
304
|
+
if (config.window_seconds !== undefined) override.WINDOW = config.window_seconds;
|
|
305
|
+
if (config.requests !== undefined) override.MAX = config.requests;
|
|
306
|
+
if (config.flood !== undefined) override.FLOOD = config.flood;
|
|
307
|
+
return override;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function compileManifestToPathRules(manifest) {
|
|
311
|
+
if (!manifest || typeof manifest !== 'object' || !manifest.routes || typeof manifest.routes !== 'object') return [];
|
|
312
|
+
return Object.entries(manifest.routes)
|
|
313
|
+
.map(([routePath, entry]) => {
|
|
314
|
+
const protections = entry && typeof entry === 'object' && entry.protections && typeof entry.protections === 'object'
|
|
315
|
+
? entry.protections
|
|
316
|
+
: {};
|
|
317
|
+
const rule = { PREFIX: normalizePath(routePath, true) };
|
|
318
|
+
const disabled = [];
|
|
319
|
+
Object.entries(protections).forEach(([name, config]) => {
|
|
320
|
+
const normalizedName = String(name).trim().toLowerCase();
|
|
321
|
+
if (!MIDDLEWARE_NAMES.has(normalizedName)) return;
|
|
322
|
+
if (config === false || (config && typeof config === 'object' && config.enabled === false)) {
|
|
323
|
+
disabled.push(normalizedName);
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
const rateConfig = protections.rate_limit || protections.api_rate_limit;
|
|
327
|
+
if (rateConfig && typeof rateConfig === 'object') {
|
|
328
|
+
const override = rateLimitOverride(rateConfig);
|
|
329
|
+
if (Object.keys(override).length) rule.RATE_LIMIT = override;
|
|
330
|
+
}
|
|
331
|
+
if (disabled.length) rule.DISABLE = Array.from(new Set(disabled)).sort();
|
|
332
|
+
return rule.DISABLE || rule.RATE_LIMIT ? rule : null;
|
|
333
|
+
})
|
|
334
|
+
.filter(Boolean);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function getEffectivePathRules(explicitRules = [], { manifestPath = DEFAULT_MANIFEST_PATH } = {}) {
|
|
338
|
+
return [...(explicitRules || []), ...compileManifestToPathRules(loadManifest(manifestPath))];
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function methodsFromExpressRoute(route) {
|
|
342
|
+
return Object.entries(route?.methods || {})
|
|
343
|
+
.filter(([, enabled]) => enabled)
|
|
344
|
+
.map(([method]) => method.toUpperCase());
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function inferMethodsFromHandler(handler) {
|
|
348
|
+
return analyzeHandlerAst(handler).methods || [];
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function routeEntryFor({ routePath, methods = [], handler, name = '', view = '' }) {
|
|
352
|
+
const inferredMethods = methods.length ? methods : inferMethodsFromHandler(handler);
|
|
353
|
+
const api = detectApiEndpoint(handler, routePath, inferredMethods);
|
|
354
|
+
const auth = detectAuthEndpoint(handler, routePath);
|
|
355
|
+
const metadata = {
|
|
356
|
+
response_type: api.responseType || undefined,
|
|
357
|
+
payload_type: api.payloadType || undefined,
|
|
358
|
+
api_confidence: api.isApi ? api.confidence : undefined,
|
|
359
|
+
api_signals: api.isApi ? api.signals : undefined,
|
|
360
|
+
form_confidence: api.formConfidence || undefined,
|
|
361
|
+
form_signals: api.formSignals.length ? api.formSignals : undefined,
|
|
362
|
+
request_body: api.requestBody || undefined,
|
|
363
|
+
auth_action: auth.isAuth ? auth.action : undefined,
|
|
364
|
+
auth_confidence: auth.isAuth ? auth.confidence : undefined,
|
|
365
|
+
auth_signals: auth.isAuth ? auth.signals : undefined
|
|
366
|
+
};
|
|
367
|
+
return buildRouteEntry({
|
|
368
|
+
routePath,
|
|
369
|
+
methods: inferredMethods,
|
|
370
|
+
view: view || handler?.name || '',
|
|
371
|
+
name: name || routePath,
|
|
372
|
+
metadata
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function addRoute(routes, routeInfo) {
|
|
377
|
+
if (!routeInfo || !routeInfo.routePath) return;
|
|
378
|
+
const [normalized, entry] = routeEntryFor(routeInfo);
|
|
379
|
+
if (routes[normalized]) {
|
|
380
|
+
const mergedMethods = Array.from(new Set([...(routes[normalized].methods || []), ...(entry.methods || [])])).sort();
|
|
381
|
+
routes[normalized] = {
|
|
382
|
+
...routes[normalized],
|
|
383
|
+
...entry,
|
|
384
|
+
methods: mergedMethods
|
|
385
|
+
};
|
|
386
|
+
} else {
|
|
387
|
+
routes[normalized] = entry;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function extractExpressRoutes(app) {
|
|
392
|
+
const routes = {};
|
|
393
|
+
const stack = app?._router?.stack || [];
|
|
394
|
+
stack.forEach(layer => {
|
|
395
|
+
const route = layer.route;
|
|
396
|
+
if (!route || !route.path) return;
|
|
397
|
+
const routePath = String(route.path);
|
|
398
|
+
const handler = route.stack?.find(item => typeof item.handle === 'function')?.handle;
|
|
399
|
+
const methods = methodsFromExpressRoute(route);
|
|
400
|
+
addRoute(routes, {
|
|
401
|
+
routePath,
|
|
402
|
+
methods,
|
|
403
|
+
handler,
|
|
404
|
+
name: routePath
|
|
405
|
+
});
|
|
406
|
+
});
|
|
407
|
+
return routes;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function normalizeRouteList(routesInput = []) {
|
|
411
|
+
return (Array.isArray(routesInput) ? routesInput : [])
|
|
412
|
+
.map(route => ({
|
|
413
|
+
routePath: route.path || route.url || route.routePath || route.pattern,
|
|
414
|
+
methods: Array.isArray(route.methods)
|
|
415
|
+
? route.methods
|
|
416
|
+
: (route.method ? [route.method] : []),
|
|
417
|
+
handler: route.handler || route.handle || route.endpoint,
|
|
418
|
+
name: route.name || route.id || route.path || route.url || '',
|
|
419
|
+
view: route.view || ''
|
|
420
|
+
}))
|
|
421
|
+
.filter(route => route.routePath);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function extractFastifyRoutes(fastify, routesInput = null) {
|
|
425
|
+
const routes = {};
|
|
426
|
+
normalizeRouteList(routesInput || fastify?.aiwafRoutes || fastify?.routes || [])
|
|
427
|
+
.forEach(route => addRoute(routes, route));
|
|
428
|
+
if (Object.keys(routes).length) return routes;
|
|
429
|
+
|
|
430
|
+
if (typeof fastify?.printRoutes === 'function') {
|
|
431
|
+
const printed = String(fastify.printRoutes() || '');
|
|
432
|
+
const routePattern = /(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+([^\s]+)/gi;
|
|
433
|
+
let match;
|
|
434
|
+
while ((match = routePattern.exec(printed)) !== null) {
|
|
435
|
+
addRoute(routes, { routePath: match[2], methods: [match[1].toUpperCase()] });
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
return routes;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function extractHapiRoutes(server, routesInput = null) {
|
|
442
|
+
const routes = {};
|
|
443
|
+
const sourceRoutes = routesInput || (typeof server?.table === 'function' ? server.table() : server?.routes);
|
|
444
|
+
normalizeRouteList((sourceRoutes || []).map(route => ({
|
|
445
|
+
path: route.path,
|
|
446
|
+
method: route.method,
|
|
447
|
+
handler: route.settings?.handler || route.handler,
|
|
448
|
+
name: route.settings?.id || route.path
|
|
449
|
+
}))).forEach(route => addRoute(routes, route));
|
|
450
|
+
return routes;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function extractKoaRoutes(_app, routesInput = []) {
|
|
454
|
+
const routes = {};
|
|
455
|
+
normalizeRouteList(routesInput).forEach(route => addRoute(routes, route));
|
|
456
|
+
return routes;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function extractNextRoutes(handlers = []) {
|
|
460
|
+
const routes = {};
|
|
461
|
+
normalizeRouteList(handlers).forEach(route => addRoute(routes, route));
|
|
462
|
+
return routes;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function extractNestRoutes(app, routesInput = null) {
|
|
466
|
+
if (routesInput) {
|
|
467
|
+
const routes = {};
|
|
468
|
+
normalizeRouteList(routesInput).forEach(route => addRoute(routes, route));
|
|
469
|
+
return routes;
|
|
470
|
+
}
|
|
471
|
+
try {
|
|
472
|
+
const httpServer = typeof app?.getHttpServer === 'function' ? app.getHttpServer() : app;
|
|
473
|
+
const expressApp = httpServer?._events?.request || httpServer?.app || app;
|
|
474
|
+
return extractExpressRoutes(expressApp);
|
|
475
|
+
} catch (err) {
|
|
476
|
+
return {};
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function generateExpressManifest(app, outputPath = DEFAULT_MANIFEST_PATH) {
|
|
481
|
+
const manifest = buildManifest({ framework: 'express', routes: extractExpressRoutes(app) });
|
|
482
|
+
writeManifest(manifest, outputPath);
|
|
483
|
+
return manifest;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function generateFrameworkManifest(framework, app, outputPath = DEFAULT_MANIFEST_PATH, options = {}) {
|
|
487
|
+
const normalized = String(framework || '').toLowerCase();
|
|
488
|
+
const extractors = {
|
|
489
|
+
express: () => options.routes ? extractNextRoutes(options.routes) : extractExpressRoutes(app),
|
|
490
|
+
sails: () => options.routes ? extractNextRoutes(options.routes) : extractExpressRoutes(app),
|
|
491
|
+
fastify: () => extractFastifyRoutes(app, options.routes),
|
|
492
|
+
hapi: () => extractHapiRoutes(app, options.routes),
|
|
493
|
+
koa: () => extractKoaRoutes(app, options.routes),
|
|
494
|
+
next: () => extractNextRoutes(options.routes || app),
|
|
495
|
+
nest: () => extractNestRoutes(app, options.routes),
|
|
496
|
+
adonis: () => extractNextRoutes(options.routes || [])
|
|
497
|
+
};
|
|
498
|
+
const extractor = extractors[normalized];
|
|
499
|
+
if (!extractor) {
|
|
500
|
+
throw new Error(`Unsupported manifest framework: ${framework}`);
|
|
501
|
+
}
|
|
502
|
+
const manifest = buildManifest({
|
|
503
|
+
framework: normalized,
|
|
504
|
+
routes: extractor(),
|
|
505
|
+
appContext: options.appContext || {}
|
|
506
|
+
});
|
|
507
|
+
writeManifest(manifest, outputPath);
|
|
508
|
+
return manifest;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
module.exports = {
|
|
512
|
+
DEFAULT_MANIFEST_PATH,
|
|
513
|
+
SCHEMA_VERSION,
|
|
514
|
+
computeContextHash,
|
|
515
|
+
classifyRoute,
|
|
516
|
+
buildRouteEntry,
|
|
517
|
+
buildManifest,
|
|
518
|
+
writeManifest,
|
|
519
|
+
loadManifest,
|
|
520
|
+
compileManifestToPathRules,
|
|
521
|
+
getEffectivePathRules,
|
|
522
|
+
routeEntryFor,
|
|
523
|
+
extractExpressRoutes,
|
|
524
|
+
extractFastifyRoutes,
|
|
525
|
+
extractHapiRoutes,
|
|
526
|
+
extractKoaRoutes,
|
|
527
|
+
extractNextRoutes,
|
|
528
|
+
extractNestRoutes,
|
|
529
|
+
generateExpressManifest,
|
|
530
|
+
generateFrameworkManifest,
|
|
531
|
+
detectApiEndpoint,
|
|
532
|
+
detectAuthEndpoint
|
|
533
|
+
};
|