routeguard-cli 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +135 -2
- package/bin/cli.js +90 -0
- package/package.json +45 -4
- package/src/flow.js +217 -0
- package/src/mapper.js +714 -0
- package/src/rules/bfla.js +51 -0
- package/src/rules/bola.js +69 -0
- package/src/rules/businessFlow.js +50 -0
- package/src/rules/consumption.js +164 -0
- package/src/rules/dataExposure.js +107 -0
- package/src/rules/handler.js +159 -0
- package/src/rules/inventory.js +84 -0
- package/src/rules/massAssignment.js +99 -0
- package/src/rules/misconfig.js +205 -0
- package/src/rules/rateLimit.js +53 -0
- package/src/rules/ssrf.js +57 -0
- package/src/sarif.js +45 -0
- package/src/spec.js +43 -0
package/src/mapper.js
ADDED
|
@@ -0,0 +1,714 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, existsSync, statSync } from "node:fs"
|
|
2
|
+
import path from "node:path"
|
|
3
|
+
import { parse } from "@babel/parser"
|
|
4
|
+
|
|
5
|
+
// objects that register routes: router, app, api, apiRouter, server (not cache.get or map.get)
|
|
6
|
+
const ROUTER_OWNER = /router|^app$|app\b|^api|route|server/i
|
|
7
|
+
const METHODS = new Set(["get", "post", "put", "patch", "delete", "all", "options", "head"])
|
|
8
|
+
// static and frontend code holds no Express routes; juice-shop keeps challenge snippets in data/static
|
|
9
|
+
const SKIP_DIRS = new Set([
|
|
10
|
+
"node_modules", "dist", "build", "coverage", "client", "frontend", "public", "static",
|
|
11
|
+
"test", "tests", "__tests__", "e2e", "cypress", "playwright", "mocks", "__mocks__", "stubs", "examples", "example", "storybook"
|
|
12
|
+
])
|
|
13
|
+
// bundles and vendored releases (.yarn/releases/yarn-4.cjs) are not the app's code
|
|
14
|
+
const MAX_SOURCE_BYTES = 512 * 1024
|
|
15
|
+
const SOURCE = /\.(c|m)?(j|t)s$/
|
|
16
|
+
|
|
17
|
+
// role checks first: "adminAuth" is a role check, not just an auth check
|
|
18
|
+
// isAuthorized() only checks login; authorize(ADMIN) with an argument names a role
|
|
19
|
+
// isAccounting(), isStaff(): an "is" check that is not about being signed in
|
|
20
|
+
// requireGroupMemberManagement, ensureProjectAccess, checkOwner: a named check on a right, not on login
|
|
21
|
+
const ROLE =
|
|
22
|
+
/admin|role|permission|owner|rbac|acl|can[A-Z]|scope|^is_?(?!auth|logged|signed|valid|verified)[a-z]+$|^(require|ensure|check|assert|verify)_?\w*(manag|access|member|owner|permission|role|staff|privilege|collaborat)/i
|
|
23
|
+
// auth('manageUsers'), permit('editor'): a guard called with the right it demands
|
|
24
|
+
const PERMISSION_CALL = /(^|\.)(auth|authori[sz]e|permit|allow|can|requires?|guard)\((?!\))/i
|
|
25
|
+
// matched against a function's own name: isAuthenticated, checkAuth, auth.jwt, verifyToken, apiAuth
|
|
26
|
+
// but not jwtChallenges or updateAuthenticatedUsers
|
|
27
|
+
const AUTH =
|
|
28
|
+
/^((is|ensure|require|check|verify|validate)_?)?((api_?)?auth\w*|jwt|token|api_?key|log(ged)?_?in|protect(ed)?|guard)$|auth$/i
|
|
29
|
+
// auth.required, passport.check: the last segment says little, so the whole name decides
|
|
30
|
+
const GENERIC = /^(required|check|ensure|verify|middleware|guard|protect|handler|validate)$/i
|
|
31
|
+
// present in the chain but enforces nothing
|
|
32
|
+
// authLimiter is rate limiting, not authentication
|
|
33
|
+
const NOT_ENFORCED = /optional|initialize|session\(|limit|throttle/i
|
|
34
|
+
|
|
35
|
+
export function listSourceFiles(root) {
|
|
36
|
+
const files = []
|
|
37
|
+
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
38
|
+
if (SKIP_DIRS.has(entry.name) || entry.name.startsWith(".")) continue
|
|
39
|
+
const full = path.join(root, entry.name)
|
|
40
|
+
if (entry.isDirectory()) files.push(...listSourceFiles(full))
|
|
41
|
+
else if (SOURCE.test(entry.name) && !/\.(d|test|spec|min)\.(j|t)s$/.test(entry.name) && statSync(full).size <= MAX_SOURCE_BYTES) files.push(full)
|
|
42
|
+
}
|
|
43
|
+
return files
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function parseFile(file) {
|
|
47
|
+
try {
|
|
48
|
+
return parse(readFileSync(file, "utf8"), {
|
|
49
|
+
sourceType: "unambiguous",
|
|
50
|
+
errorRecovery: true,
|
|
51
|
+
plugins: ["jsx", "typescript", "decorators-legacy"]
|
|
52
|
+
})
|
|
53
|
+
} catch {
|
|
54
|
+
return null
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function walk(node, visit) {
|
|
59
|
+
if (!node || typeof node.type !== "string") return
|
|
60
|
+
visit(node)
|
|
61
|
+
for (const key of Object.keys(node)) {
|
|
62
|
+
if (key === "loc" || key === "start" || key === "end") continue
|
|
63
|
+
const child = node[key]
|
|
64
|
+
if (Array.isArray(child)) child.forEach(c => walk(c, visit))
|
|
65
|
+
else if (child && typeof child.type === "string") walk(child, visit)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// a.b and a?.b, a() and a?.()
|
|
70
|
+
export const isMemberNode = node => node?.type === "MemberExpression" || node?.type === "OptionalMemberExpression"
|
|
71
|
+
export const isCallNode = node => node?.type === "CallExpression" || node?.type === "OptionalCallExpression"
|
|
72
|
+
const isMember = (node, objectName) => isMemberNode(node) && node.object.type === "Identifier" && node.object.name === objectName
|
|
73
|
+
const isFunctionNode = node => ["ArrowFunctionExpression", "FunctionExpression", "FunctionDeclaration", "ObjectMethod", "ClassMethod"].includes(node?.type)
|
|
74
|
+
|
|
75
|
+
// package.json "imports": { "#*": "./src/*" } lets code import "#modules/x.js"
|
|
76
|
+
let subpathImports = { root: "", map: {} }
|
|
77
|
+
|
|
78
|
+
// monorepo packages by name: "@verdaccio/middleware" → packages/middleware
|
|
79
|
+
let workspacePackages = new Map()
|
|
80
|
+
|
|
81
|
+
function findPackages(dir, depth = 0, out = new Map()) {
|
|
82
|
+
if (depth > 4) return out
|
|
83
|
+
let entries
|
|
84
|
+
try {
|
|
85
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
86
|
+
} catch {
|
|
87
|
+
return out
|
|
88
|
+
}
|
|
89
|
+
for (const entry of entries) {
|
|
90
|
+
if (entry.isDirectory() && !SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) findPackages(path.join(dir, entry.name), depth + 1, out)
|
|
91
|
+
if (entry.name === "package.json" && depth > 0) {
|
|
92
|
+
try {
|
|
93
|
+
const pkg = JSON.parse(readFileSync(path.join(dir, entry.name), "utf8"))
|
|
94
|
+
if (pkg.name) out.set(pkg.name, dir)
|
|
95
|
+
} catch {}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return out
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function resolvePackage(spec) {
|
|
102
|
+
const name = [...workspacePackages.keys()].filter(n => spec === n || spec.startsWith(`${n}/`)).sort((a, b) => b.length - a.length)[0]
|
|
103
|
+
if (!name) return null
|
|
104
|
+
const dir = workspacePackages.get(name)
|
|
105
|
+
const sub = spec.slice(name.length + 1)
|
|
106
|
+
if (sub) return path.join(dir, sub)
|
|
107
|
+
for (const entry of ["src/index.ts", "src/index.js", "index.ts", "index.js", "lib/index.js"])
|
|
108
|
+
if (existsSync(path.join(dir, entry))) return path.join(dir, entry)
|
|
109
|
+
return null
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function loadSubpathImports(root) {
|
|
113
|
+
workspacePackages = findPackages(root)
|
|
114
|
+
try {
|
|
115
|
+
const pkg = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8"))
|
|
116
|
+
subpathImports = { root, map: pkg.imports ?? {} }
|
|
117
|
+
} catch {
|
|
118
|
+
subpathImports = { root, map: {} }
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function resolveSubpath(spec) {
|
|
123
|
+
for (const [key, value] of Object.entries(subpathImports.map)) {
|
|
124
|
+
const target = typeof value === "string" ? value : (value?.node ?? value?.import ?? value?.default)
|
|
125
|
+
if (typeof target !== "string") continue
|
|
126
|
+
const star = key.indexOf("*")
|
|
127
|
+
if (star === -1 && key === spec) return path.resolve(subpathImports.root, target)
|
|
128
|
+
if (star !== -1 && spec.startsWith(key.slice(0, star)) && spec.endsWith(key.slice(star + 1)))
|
|
129
|
+
return path.resolve(subpathImports.root, target.replace("*", spec.slice(star, spec.length - (key.length - star - 1))))
|
|
130
|
+
}
|
|
131
|
+
return null
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function resolveModule(fromFile, spec) {
|
|
135
|
+
if (!spec) return null
|
|
136
|
+
const base = spec.startsWith("#")
|
|
137
|
+
? resolveSubpath(spec)
|
|
138
|
+
: spec.startsWith(".")
|
|
139
|
+
? path.resolve(path.dirname(fromFile), spec)
|
|
140
|
+
: resolvePackage(spec)
|
|
141
|
+
if (!base) return null
|
|
142
|
+
for (const ext of ["", ".js", ".ts", ".mjs", ".cjs", "/index.js", "/index.ts"]) {
|
|
143
|
+
const candidate = base + ext
|
|
144
|
+
if (existsSync(candidate) && statSync(candidate).isFile()) return candidate
|
|
145
|
+
}
|
|
146
|
+
return null
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function stringValue(node) {
|
|
150
|
+
if (!node) return null
|
|
151
|
+
if (node.type === "StringLiteral") return node.value
|
|
152
|
+
if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked
|
|
153
|
+
return null
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function nameOf(node) {
|
|
157
|
+
if (isMemberNode(node)) return `${nameOf(node.object)}.${node.property.name ?? "?"}`
|
|
158
|
+
if (isCallNode(node)) {
|
|
159
|
+
const args = node.arguments.map(a => stringValue(a) ?? nameOf(a) ?? "…")
|
|
160
|
+
return `${nameOf(node.callee)}(${args.join(", ")})`
|
|
161
|
+
}
|
|
162
|
+
if (node?.type === "Identifier") return node.name
|
|
163
|
+
if (isFunctionNode(node)) return "<inline>"
|
|
164
|
+
return null
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// catchAsync(async (req, res) => {}) and asyncHandler(getUser) wrap the real handler
|
|
168
|
+
function unwrapHandler(node) {
|
|
169
|
+
if (isCallNode(node)) {
|
|
170
|
+
// asyncHandler(retrieveBasket()): the inner call is a factory, keep it for the resolver
|
|
171
|
+
const inner = node.arguments.find(a => isFunctionNode(a) || a.type === "Identifier" || isMemberNode(a) || isCallNode(a))
|
|
172
|
+
return inner ? unwrapHandler(inner) : node
|
|
173
|
+
}
|
|
174
|
+
return node
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// plumbing, not access control
|
|
178
|
+
const NOISE = /^(cors|vhost|morgan|compression|helmet|cookieParser|bodyParser|express\.(json|urlencoded|static|text|raw))\b/
|
|
179
|
+
|
|
180
|
+
// [auth, admin] and auth, admin both mean two middlewares
|
|
181
|
+
function flattenMiddleware(args) {
|
|
182
|
+
return args
|
|
183
|
+
.flatMap(a => (a.type === "ArrayExpression" ? a.elements : [a]))
|
|
184
|
+
.map(nameOf)
|
|
185
|
+
.filter(name => name && !NOISE.test(name))
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// router.route("/x").get(…).post(…): the path sits on .route(), down the chain
|
|
189
|
+
function routeChainPath(object) {
|
|
190
|
+
let node = object
|
|
191
|
+
while (isCallNode(node) && isMemberNode(node.callee)) {
|
|
192
|
+
const prop = node.callee.property.name
|
|
193
|
+
if (prop === "route") return stringValue(node.arguments[0])
|
|
194
|
+
if (!METHODS.has(prop)) return null
|
|
195
|
+
node = node.callee.object
|
|
196
|
+
}
|
|
197
|
+
return null
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Router().use(a).use(b) and router.route("/x").get(…): the object at the root of the chain
|
|
201
|
+
function chainRootNode(object) {
|
|
202
|
+
let node = object
|
|
203
|
+
while (isCallNode(node) && isMemberNode(node.callee) && /^(use|route|get|post|put|patch|delete|all)$/.test(node.callee.property.name))
|
|
204
|
+
node = node.callee.object
|
|
205
|
+
return node
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function scanFile(file) {
|
|
209
|
+
const ast = parseFile(file)
|
|
210
|
+
const result = {
|
|
211
|
+
file,
|
|
212
|
+
requires: new Map(),
|
|
213
|
+
named: new Map(),
|
|
214
|
+
mounts: [],
|
|
215
|
+
localMounts: new Map(),
|
|
216
|
+
routes: [],
|
|
217
|
+
uses: [],
|
|
218
|
+
pathUses: [],
|
|
219
|
+
// const PREFIX = "/api", const ENDPOINTS = { list: "/stage" }, enum ENDPOINTS { list = "/stage" }
|
|
220
|
+
constants: new Map(),
|
|
221
|
+
reexportAll: [],
|
|
222
|
+
reexportNamed: new Map(),
|
|
223
|
+
// module.exports = router / export default router: which router a plain import gets
|
|
224
|
+
defaultExport: null,
|
|
225
|
+
createsApp: false,
|
|
226
|
+
functions: new Map()
|
|
227
|
+
}
|
|
228
|
+
if (!ast) return result
|
|
229
|
+
|
|
230
|
+
// const api = Router().use(a).use(b): calls on that chain belong to "api", not to "Router()"
|
|
231
|
+
const chainOwners = new Map()
|
|
232
|
+
walk(ast, node => {
|
|
233
|
+
if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && isCallNode(node.init))
|
|
234
|
+
chainOwners.set(chainRootNode(node.init), node.id.name)
|
|
235
|
+
})
|
|
236
|
+
// const routes = [{ path: "/auth", route: authRoute }, …]: for routes.forEach(r => router.use(r.path, r.route))
|
|
237
|
+
const arrays = new Map()
|
|
238
|
+
walk(ast, node => {
|
|
239
|
+
if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init?.type === "ArrayExpression")
|
|
240
|
+
arrays.set(node.id.name, node.init.elements)
|
|
241
|
+
})
|
|
242
|
+
const chainRoot = object => {
|
|
243
|
+
const root = chainRootNode(object)
|
|
244
|
+
return chainOwners.get(root) ?? nameOf(root)
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
walk(ast, node => {
|
|
248
|
+
// named handlers: function getBook() {}, const getBook = () => {}, const getBook = catchAsync(() => {})
|
|
249
|
+
if (node.type === "FunctionDeclaration" && node.id) result.functions.set(node.id.name, node)
|
|
250
|
+
if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
|
|
251
|
+
const fn = unwrapHandler(node.init)
|
|
252
|
+
if (isFunctionNode(fn)) result.functions.set(node.id.name, fn)
|
|
253
|
+
}
|
|
254
|
+
if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
|
|
255
|
+
let init = node.init
|
|
256
|
+
while (["TSAsExpression", "TSSatisfiesExpression"].includes(init.type) || (isCallNode(init) && nameOf(init.callee) === "Object.freeze")) init = init.expression ?? init.arguments[0]
|
|
257
|
+
if (["StringLiteral", "TemplateLiteral", "ObjectExpression", "BinaryExpression"].includes(init?.type)) result.constants.set(node.id.name, init)
|
|
258
|
+
}
|
|
259
|
+
if (node.type === "TSEnumDeclaration")
|
|
260
|
+
result.constants.set(node.id.name, { type: "Enum", members: new Map(node.members.map(m => [m.id.name ?? m.id.value, m.initializer])) })
|
|
261
|
+
if (node.type === "ExportAllDeclaration") {
|
|
262
|
+
const target = resolveModule(file, node.source.value)
|
|
263
|
+
if (target) result.reexportAll.push(target)
|
|
264
|
+
}
|
|
265
|
+
if (node.type === "ExportNamedDeclaration" && node.source) {
|
|
266
|
+
const target = resolveModule(file, node.source.value)
|
|
267
|
+
if (target) for (const sp of node.specifiers) if (sp.local) result.reexportNamed.set(sp.exported.name ?? sp.exported.value, { file: target, name: sp.local.name })
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
if (node.type === "AssignmentExpression" && nameOf(node.left) === "module.exports" && node.right.type === "Identifier")
|
|
271
|
+
result.defaultExport = node.right.name
|
|
272
|
+
if (node.type === "ExportDefaultDeclaration")
|
|
273
|
+
result.defaultExport = node.declaration.type === "Identifier" ? node.declaration.name : isCallNode(node.declaration) ? chainRoot(node.declaration) : null
|
|
274
|
+
if (isCallNode(node) && (node.callee.name === "express" || (isMemberNode(node.callee) && node.callee.property.name === "listen")))
|
|
275
|
+
result.createsApp = true
|
|
276
|
+
|
|
277
|
+
// const Controller = { getMessages(req, res) {…}, list: async (req, res) => {…} }; export default Controller
|
|
278
|
+
if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init?.type === "ObjectExpression") {
|
|
279
|
+
for (const prop of node.init.properties) {
|
|
280
|
+
const key = prop.key?.name ?? prop.key?.value
|
|
281
|
+
if (!key) continue
|
|
282
|
+
if (prop.type === "ObjectMethod") result.functions.set(key, prop)
|
|
283
|
+
else if (prop.type === "ObjectProperty") {
|
|
284
|
+
const fn = unwrapHandler(prop.value)
|
|
285
|
+
if (isFunctionNode(fn) && !result.functions.has(key)) result.functions.set(key, fn)
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// exports.getBook = () => {} and module.exports.getBook = () => {}
|
|
291
|
+
if (node.type === "AssignmentExpression" && isMemberNode(node.left) && /^(module\.)?exports\./.test(nameOf(node.left))) {
|
|
292
|
+
const fn = unwrapHandler(node.right)
|
|
293
|
+
if (isFunctionNode(fn)) result.functions.set(node.left.property.name, fn)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// const users = require("./users") and const { getUser } = require("./users")
|
|
297
|
+
if (node.type === "VariableDeclarator" && isCallNode(node.init) && node.init.callee.name === "require") {
|
|
298
|
+
const target = resolveModule(file, stringValue(node.init.arguments[0]))
|
|
299
|
+
if (target && node.id.type === "Identifier") result.requires.set(node.id.name, target)
|
|
300
|
+
if (target && node.id.type === "ObjectPattern")
|
|
301
|
+
for (const p of node.id.properties)
|
|
302
|
+
if (p.value?.type === "Identifier") result.named.set(p.value.name, { file: target, name: p.key.name })
|
|
303
|
+
}
|
|
304
|
+
// import users from "./users" and import { getUser } from "./users"
|
|
305
|
+
if (node.type === "ImportDeclaration") {
|
|
306
|
+
const target = resolveModule(file, node.source.value)
|
|
307
|
+
if (!target) return
|
|
308
|
+
for (const s of node.specifiers) {
|
|
309
|
+
if (s.type === "ImportDefaultSpecifier" || s.type === "ImportNamespaceSpecifier") result.requires.set(s.local.name, target)
|
|
310
|
+
if (s.type === "ImportSpecifier") result.named.set(s.local.name, { file: target, name: s.imported.name ?? s.imported.value })
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
if (!isCallNode(node) || !isMemberNode(node.callee)) return
|
|
315
|
+
const method = node.callee.property.name
|
|
316
|
+
|
|
317
|
+
if (method === "forEach" && node.callee.object.type === "Identifier" && arrays.has(node.callee.object.name)) {
|
|
318
|
+
const callback = node.arguments[0]
|
|
319
|
+
const item = callback?.params?.[0]?.name
|
|
320
|
+
if (!item) return
|
|
321
|
+
walk(callback.body, inner => {
|
|
322
|
+
if (!isCallNode(inner) || !isMemberNode(inner.callee) || inner.callee.property.name !== "use") return
|
|
323
|
+
const [pathArg, routerArg] = inner.arguments
|
|
324
|
+
if (!isMember(pathArg, item) || !isMember(routerArg, item)) return
|
|
325
|
+
for (const element of arrays.get(node.callee.object.name)) {
|
|
326
|
+
if (element?.type !== "ObjectExpression") continue
|
|
327
|
+
const field = key => element.properties.find(p => p.key?.name === key)?.value
|
|
328
|
+
const prefix = stringValue(field(pathArg.property.name))
|
|
329
|
+
const target = field(routerArg.property.name)
|
|
330
|
+
if (prefix !== null && target?.type === "Identifier")
|
|
331
|
+
result.mounts.push({ owner: chainRoot(inner.callee.object), prefix, target: target.name, middleware: [], allMiddleware: [], line: inner.loc.start.line })
|
|
332
|
+
}
|
|
333
|
+
})
|
|
334
|
+
return
|
|
335
|
+
}
|
|
336
|
+
const owner = chainRoot(node.callee.object)
|
|
337
|
+
const line = node.loc.start.line
|
|
338
|
+
const [first, ...rest] = node.arguments
|
|
339
|
+
const routePath = stringValue(first)
|
|
340
|
+
|
|
341
|
+
// router.get(ENDPOINTS.list, …), app.use(`${PREFIX}/users`, users): resolved once every file is read
|
|
342
|
+
const pathExpression =
|
|
343
|
+
routePath === null && ["Identifier", "MemberExpression", "TemplateLiteral", "BinaryExpression"].includes(first?.type) && ROUTER_OWNER.test(owner ?? "")
|
|
344
|
+
? first
|
|
345
|
+
: null
|
|
346
|
+
|
|
347
|
+
if (method === "use") {
|
|
348
|
+
if (routePath !== null || (pathExpression && rest.length > 0 && !isFunctionNode(rest.at(-1)) && !isCallNode(rest.at(-1)) && rest.at(-1)?.type === "Identifier" && first.type !== "Identifier")) {
|
|
349
|
+
// app.use("/api/users", auth, users): the last identifier is the mounted router
|
|
350
|
+
const last = rest.at(-1)
|
|
351
|
+
const target = last?.type === "Identifier" ? last.name : null
|
|
352
|
+
result.mounts.push({
|
|
353
|
+
owner,
|
|
354
|
+
prefix: routePath,
|
|
355
|
+
prefixNode: routePath === null ? first : null,
|
|
356
|
+
target,
|
|
357
|
+
middleware: flattenMiddleware(rest.slice(0, -1)),
|
|
358
|
+
// app.use("/rest/basket", isAuthorized()): no router, so every argument is middleware
|
|
359
|
+
allMiddleware: flattenMiddleware(rest),
|
|
360
|
+
line
|
|
361
|
+
})
|
|
362
|
+
} else {
|
|
363
|
+
// app.use(auth) is middleware, app.use(usersRouter) mounts at "", sorted out once every file is read
|
|
364
|
+
const idents = node.arguments.filter(a => a.type === "Identifier").map(a => a.name)
|
|
365
|
+
result.uses.push({ owner, middleware: flattenMiddleware(node.arguments), idents, line })
|
|
366
|
+
}
|
|
367
|
+
return
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
if (!METHODS.has(method)) return
|
|
371
|
+
if (routePath !== null && rest.length > 0) {
|
|
372
|
+
result.routes.push(routeEntry(owner, method, routePath, rest, line))
|
|
373
|
+
return
|
|
374
|
+
}
|
|
375
|
+
if (pathExpression && rest.length > 0 && rest.some(a => isFunctionNode(a) || a.type === "Identifier" || isMemberNode(a) || isCallNode(a))) {
|
|
376
|
+
result.routes.push({ ...routeEntry(owner, method, null, rest, line), pathNode: first })
|
|
377
|
+
return
|
|
378
|
+
}
|
|
379
|
+
const chainPath = routeChainPath(node.callee.object)
|
|
380
|
+
if (chainPath !== null && node.arguments.length > 0) result.routes.push(routeEntry(owner, method, chainPath, node.arguments, line))
|
|
381
|
+
})
|
|
382
|
+
return result
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function routeEntry(owner, method, routePath, args, line) {
|
|
386
|
+
return {
|
|
387
|
+
owner,
|
|
388
|
+
method: method.toUpperCase(),
|
|
389
|
+
path: routePath,
|
|
390
|
+
middleware: flattenMiddleware(args.slice(0, -1)),
|
|
391
|
+
handler: nameOf(args.at(-1)) ?? "?",
|
|
392
|
+
handlerNode: args.at(-1),
|
|
393
|
+
line
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function joinPath(prefix, routePath) {
|
|
398
|
+
const joined = `${prefix}/${routePath}`.replace(/\/+/g, "/")
|
|
399
|
+
return joined.length > 1 ? joined.replace(/\/$/, "") : joined
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// auth.featureAccess and helpers.verify are not auth checks: judge the function's own name,
|
|
403
|
+
// falling back to the whole name only when that is generic (auth.required)
|
|
404
|
+
// asyncHandler(auth.jwt): the check is the wrapped argument, not the wrapper
|
|
405
|
+
function matches(pattern, middleware) {
|
|
406
|
+
const open = middleware.indexOf("(")
|
|
407
|
+
const base = open === -1 ? middleware : middleware.slice(0, open)
|
|
408
|
+
const segments = base.split(".")
|
|
409
|
+
const last = segments.at(-1)
|
|
410
|
+
if (pattern.test(last) || (GENERIC.test(last) && segments.length > 1 && pattern.test(segments.at(-2)))) return true
|
|
411
|
+
// only async wrappers: validate(authValidation.login) is a validator, not a login check
|
|
412
|
+
if (!/async|wrap|catch|handler/i.test(last)) return false
|
|
413
|
+
const inner = open === -1 ? "" : middleware.slice(open + 1, middleware.lastIndexOf(")"))
|
|
414
|
+
return inner.split(",").some(arg => /^[\w.]+$/.test(arg.trim()) && matches(pattern, arg.trim()))
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export function classify(middleware) {
|
|
418
|
+
const enforced = middleware.filter(m => !NOT_ENFORCED.test(m))
|
|
419
|
+
const role = enforced.some(m => matches(ROLE, m) || PERMISSION_CALL.test(m))
|
|
420
|
+
const auth = role || enforced.some(m => matches(AUTH, m))
|
|
421
|
+
return { auth, role }
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// "// routeguard-ignore BOLA" (or every rule, with no names) in the three lines above a route
|
|
425
|
+
const IGNORE = /routeguard-ignore(?:\s+([A-Z_, ]+))?/
|
|
426
|
+
const fileLines = new Map()
|
|
427
|
+
|
|
428
|
+
function ignoredRules(file, line) {
|
|
429
|
+
if (!fileLines.has(file)) fileLines.set(file, readFileSync(file, "utf8").split("\n"))
|
|
430
|
+
const above = fileLines.get(file).slice(Math.max(0, line - 4), line).join("\n")
|
|
431
|
+
const match = above.match(IGNORE)
|
|
432
|
+
if (!match) return null
|
|
433
|
+
return match[1] ? new Set(match[1].split(/[\s,]+/).filter(Boolean)) : "all"
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
export function mapRoutes(root) {
|
|
437
|
+
loadSubpathImports(root)
|
|
438
|
+
const scans = listSourceFiles(root).map(scanFile)
|
|
439
|
+
const byFile = new Map(scans.map(s => [s.file, s]))
|
|
440
|
+
const isRouterFile = file => byFile.get(file)?.routes.length > 0 || byFile.get(file)?.mounts.length > 0
|
|
441
|
+
|
|
442
|
+
// a constant exported from `file` under `name`, following export * and export { x } from
|
|
443
|
+
function exportedConstant(file, name, depth = 0) {
|
|
444
|
+
const scan = byFile.get(file)
|
|
445
|
+
if (!scan || depth > 4) return null
|
|
446
|
+
if (scan.constants.has(name)) return { file, node: scan.constants.get(name) }
|
|
447
|
+
const named = scan.reexportNamed.get(name)
|
|
448
|
+
if (named) return exportedConstant(named.file, named.name, depth + 1)
|
|
449
|
+
for (const next of scan.reexportAll) {
|
|
450
|
+
const found = exportedConstant(next, name, depth + 1)
|
|
451
|
+
if (found) return found
|
|
452
|
+
}
|
|
453
|
+
return null
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function lookup(file, name) {
|
|
457
|
+
const scan = byFile.get(file)
|
|
458
|
+
if (!scan) return null
|
|
459
|
+
if (scan.constants.has(name)) return { file, node: scan.constants.get(name) }
|
|
460
|
+
const named = scan.named.get(name)
|
|
461
|
+
if (named) return exportedConstant(named.file, named.name)
|
|
462
|
+
const module = scan.requires.get(name)
|
|
463
|
+
if (module) return { file: module, module: true }
|
|
464
|
+
return null
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// ENDPOINTS, Constants.API: an object (or enum, or module) whose properties can be read
|
|
468
|
+
function evaluateObject(file, node, depth = 0) {
|
|
469
|
+
if (depth > 6 || !node) return null
|
|
470
|
+
if (node.type === "Identifier") {
|
|
471
|
+
const found = lookup(file, node.name)
|
|
472
|
+
if (!found) return null
|
|
473
|
+
if (found.module) return { file: found.file, module: true }
|
|
474
|
+
return evaluateObject(found.file, found.node, depth + 1)
|
|
475
|
+
}
|
|
476
|
+
if (node.type === "Enum") return { file, get: key => node.members.get(key) }
|
|
477
|
+
if (node.type === "ObjectExpression")
|
|
478
|
+
return { file, get: key => node.properties.find(p => (p.key?.name ?? p.key?.value) === key)?.value }
|
|
479
|
+
if (isMemberNode(node)) {
|
|
480
|
+
const owner = evaluateObject(file, node.object, depth + 1)
|
|
481
|
+
const key = node.computed ? stringValue(node.property) : node.property.name
|
|
482
|
+
if (!owner || key == null) return null
|
|
483
|
+
if (owner.module) {
|
|
484
|
+
const found = exportedConstant(owner.file, key)
|
|
485
|
+
return found ? evaluateObject(found.file, found.node, depth + 1) : null
|
|
486
|
+
}
|
|
487
|
+
return evaluateObject(owner.file, owner.get(key), depth + 1)
|
|
488
|
+
}
|
|
489
|
+
return null
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function evaluateString(file, node, depth = 0) {
|
|
493
|
+
if (!node || depth > 6) return null
|
|
494
|
+
const literal = stringValue(node)
|
|
495
|
+
if (literal !== null) return literal
|
|
496
|
+
if (node.type === "TemplateLiteral") {
|
|
497
|
+
const parts = node.expressions.map(e => evaluateString(file, e, depth + 1))
|
|
498
|
+
if (parts.some(p => p === null)) return null
|
|
499
|
+
return node.quasis.map((q, i) => q.value.cooked + (parts[i] ?? "")).join("")
|
|
500
|
+
}
|
|
501
|
+
if (node.type === "BinaryExpression" && node.operator === "+") {
|
|
502
|
+
const left = evaluateString(file, node.left, depth + 1)
|
|
503
|
+
const right = evaluateString(file, node.right, depth + 1)
|
|
504
|
+
return left === null || right === null ? null : left + right
|
|
505
|
+
}
|
|
506
|
+
if (node.type === "Identifier") {
|
|
507
|
+
const found = lookup(file, node.name)
|
|
508
|
+
return found && !found.module ? evaluateString(found.file, found.node, depth + 1) : null
|
|
509
|
+
}
|
|
510
|
+
if (isMemberNode(node)) {
|
|
511
|
+
const owner = evaluateObject(file, node.object)
|
|
512
|
+
const key = node.computed ? stringValue(node.property) : node.property.name
|
|
513
|
+
if (!owner || key == null) return null
|
|
514
|
+
if (owner.module) {
|
|
515
|
+
const found = exportedConstant(owner.file, key)
|
|
516
|
+
return found ? evaluateString(found.file, found.node, depth + 1) : null
|
|
517
|
+
}
|
|
518
|
+
return evaluateString(owner.file, owner.get(key), depth + 1)
|
|
519
|
+
}
|
|
520
|
+
return null
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// paths written as constants; one that cannot be worked out stays visible as <NAME>
|
|
524
|
+
for (const scan of scans) {
|
|
525
|
+
for (const route of scan.routes)
|
|
526
|
+
if (route.path === null) route.path = evaluateString(scan.file, route.pathNode) ?? `<${nameOf(route.pathNode) ?? "path"}>`
|
|
527
|
+
for (const mount of scan.mounts)
|
|
528
|
+
if (mount.prefix === null) mount.prefix = evaluateString(scan.file, mount.prefixNode) ?? `<${nameOf(mount.prefixNode) ?? "prefix"}>`
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// which router object an identifier imports: users → "routes/users.js#router", { learnerRouter } → "…#learnerRouter".
|
|
532
|
+
// "*" when the file's default export is not a plain name, so the mount applies to every router in it
|
|
533
|
+
function mountKey(scan, ident) {
|
|
534
|
+
// only files that define routes: { authLimiter } from middlewares/rateLimiter.js is middleware
|
|
535
|
+
const file = scan.requires.get(ident)
|
|
536
|
+
if (file && isRouterFile(file)) return { file, key: `${file}#${byFile.get(file).defaultExport ?? "*"}` }
|
|
537
|
+
const named = scan.named.get(ident)
|
|
538
|
+
if (named && isRouterFile(named.file)) return { file: named.file, key: `${named.file}#${named.name}` }
|
|
539
|
+
return null
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// who mounts each file, with what prefix and mount-level middleware
|
|
543
|
+
const mountedBy = new Map()
|
|
544
|
+
const addMount = (target, mount) => {
|
|
545
|
+
if (!mountedBy.has(target)) mountedBy.set(target, [])
|
|
546
|
+
mountedBy.get(target).push(mount)
|
|
547
|
+
}
|
|
548
|
+
for (const scan of scans) {
|
|
549
|
+
for (const mount of scan.mounts) {
|
|
550
|
+
const target = mount.target && mountKey(scan, mount.target)
|
|
551
|
+
if (target) addMount(target.key, { parent: scan.file, ...mount })
|
|
552
|
+
// app.use("/api", api) where api is a router built in this file
|
|
553
|
+
else if (mount.target && !scan.requires.has(mount.target) && !scan.named.has(mount.target) && !scan.functions.has(mount.target))
|
|
554
|
+
scan.localMounts.set(mount.target, mount)
|
|
555
|
+
else scan.pathUses.push({ owner: mount.owner, prefix: mount.prefix, middleware: mount.allMiddleware, line: mount.line })
|
|
556
|
+
}
|
|
557
|
+
for (const use of scan.uses) {
|
|
558
|
+
const routers = use.idents.filter(id => isRouterFile(mountKey(scan, id)?.file))
|
|
559
|
+
for (const id of routers)
|
|
560
|
+
addMount(mountKey(scan, id).key, { parent: scan.file, owner: use.owner, prefix: "", middleware: [], line: use.line })
|
|
561
|
+
// a mounted router is not middleware: authController must not count as an auth check
|
|
562
|
+
use.middleware = use.middleware.filter(m => !routers.includes(m))
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// the prefix a router built in this file sits under: api → "/api" when app.use("/api", api)
|
|
567
|
+
function localContext(scan, owner, seen = new Set()) {
|
|
568
|
+
const mount = scan.localMounts.get(owner)
|
|
569
|
+
if (!mount || seen.has(owner)) return { prefix: "", middleware: [], owner }
|
|
570
|
+
seen.add(owner)
|
|
571
|
+
const outer = localContext(scan, mount.owner, seen)
|
|
572
|
+
return {
|
|
573
|
+
prefix: joinPath(outer.prefix, mount.prefix),
|
|
574
|
+
middleware: [...outer.middleware, ...inheritedUses(scan, mount.owner, mount.line), ...mount.middleware],
|
|
575
|
+
owner: outer.owner
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// a router can be mounted at several prefixes, through nested routers. anchored: the chain
|
|
580
|
+
// reaches a file that creates the app, so the full path is known
|
|
581
|
+
function contexts(file, owner, seen = new Set()) {
|
|
582
|
+
const key = `${file}#${owner}`
|
|
583
|
+
const parents = [...(mountedBy.get(key) ?? []), ...(mountedBy.get(`${file}#*`) ?? [])]
|
|
584
|
+
// a root is known when it creates the app or assembles other routers (startup/routes.js);
|
|
585
|
+
// a router built in a factory and mounted by call has no known prefix
|
|
586
|
+
const root = byFile.get(file)
|
|
587
|
+
if (parents.length === 0 || seen.has(key)) return [{ prefix: "", middleware: [], anchored: Boolean(root?.createsApp || root?.mounts.length), rootFile: file }]
|
|
588
|
+
seen.add(key)
|
|
589
|
+
return parents.flatMap(m => {
|
|
590
|
+
const local = localContext(byFile.get(m.parent), m.owner)
|
|
591
|
+
return contexts(m.parent, local.owner, new Set(seen)).map(ctx => {
|
|
592
|
+
return {
|
|
593
|
+
anchored: ctx.anchored,
|
|
594
|
+
rootFile: ctx.rootFile,
|
|
595
|
+
prefix: joinPath(joinPath(ctx.prefix, local.prefix), m.prefix),
|
|
596
|
+
middleware: [
|
|
597
|
+
...ctx.middleware,
|
|
598
|
+
...local.middleware,
|
|
599
|
+
...inheritedUses(byFile.get(m.parent), m.owner, m.line),
|
|
600
|
+
...m.middleware
|
|
601
|
+
]
|
|
602
|
+
}
|
|
603
|
+
})
|
|
604
|
+
})
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// router.use(auth) applies to routes registered after it on the same object
|
|
608
|
+
function inheritedUses(scan, owner, line) {
|
|
609
|
+
return scan.uses.filter(u => u.owner === owner && u.line < line).flatMap(u => u.middleware)
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const covers = (prefix, fullPath) => {
|
|
613
|
+
const pattern = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\:\w+|:\w+/g, "[^/]+")}(/|$)`, "i")
|
|
614
|
+
return pattern.test(fullPath)
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// app.use("/rest/basket", isAuthorized()) guards /rest/basket and everything under it
|
|
618
|
+
function pathScopedUses(scan, route) {
|
|
619
|
+
return scan.pathUses
|
|
620
|
+
.filter(u => u.owner === route.owner && u.line <= route.line && covers(u.prefix, route.path))
|
|
621
|
+
.flatMap(u => u.middleware)
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
// app.use("/v1/auth", authLimiter) in app.js covers routes defined in routes/auth.route.js
|
|
625
|
+
const outerPathUses = scans.flatMap(scan =>
|
|
626
|
+
scan.pathUses.flatMap(u => contexts(scan.file, localContext(scan, u.owner).owner).map(ctx => ({ file: scan.file, prefix: joinPath(ctx.prefix, u.prefix), middleware: u.middleware })))
|
|
627
|
+
)
|
|
628
|
+
const crossFileUses = (file, fullPath) =>
|
|
629
|
+
outerPathUses.filter(u => u.file !== file && covers(u.prefix, fullPath)).flatMap(u => u.middleware)
|
|
630
|
+
|
|
631
|
+
// the handler's function node and file, following controllers into the files they come from
|
|
632
|
+
function resolveHandler(scan, node) {
|
|
633
|
+
const target = unwrapHandler(node)
|
|
634
|
+
// retrieveBasket(): a factory whose returned function is the handler
|
|
635
|
+
if (isCallNode(target) && target.arguments.length === 0) {
|
|
636
|
+
const factory = resolveHandler(scan, target.callee)
|
|
637
|
+
let returned = null
|
|
638
|
+
walk(factory?.fn?.body, n => {
|
|
639
|
+
if (!returned && n.type === "ReturnStatement" && isFunctionNode(n.argument)) returned = n.argument
|
|
640
|
+
})
|
|
641
|
+
return returned ? { fn: returned, file: factory.file } : null
|
|
642
|
+
}
|
|
643
|
+
if (isFunctionNode(target)) return { fn: target, file: scan.file }
|
|
644
|
+
if (target?.type === "Identifier") {
|
|
645
|
+
if (scan.functions.has(target.name)) return { fn: scan.functions.get(target.name), file: scan.file }
|
|
646
|
+
const imported = scan.named.get(target.name)
|
|
647
|
+
const fn = byFile.get(imported?.file)?.functions.get(imported.name)
|
|
648
|
+
return fn ? { fn, file: imported.file } : null
|
|
649
|
+
}
|
|
650
|
+
if (isMemberNode(target) && target.object.type === "Identifier") {
|
|
651
|
+
const file = scan.requires.get(target.object.name) ?? scan.named.get(target.object.name)?.file
|
|
652
|
+
// HistoryController.remove, with the controller defined in this file
|
|
653
|
+
if (!file) return scan.functions.has(target.property.name) ? { fn: scan.functions.get(target.property.name), file: scan.file } : null
|
|
654
|
+
const fn = byFile.get(file)?.functions.get(target.property.name)
|
|
655
|
+
return fn ? { fn, file } : null
|
|
656
|
+
}
|
|
657
|
+
return null
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
// the file an identifier in `file` was imported from: User → models/user.js
|
|
661
|
+
function importedFile(file, name) {
|
|
662
|
+
const scan = byFile.get(file)
|
|
663
|
+
return scan?.requires.get(name) ?? scan?.named.get(name)?.file ?? null
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// the function a call in `file` names: getCourseShares(...), courseService.getCourse(...)
|
|
667
|
+
function resolveCallee(file, callee) {
|
|
668
|
+
const scan = byFile.get(file)
|
|
669
|
+
if (!scan || !callee) return null
|
|
670
|
+
const found = resolveHandler(scan, callee)
|
|
671
|
+
return found?.fn?.body ? found : null
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
const routes = []
|
|
675
|
+
for (const scan of scans) {
|
|
676
|
+
for (const route of scan.routes) {
|
|
677
|
+
const handler = resolveHandler(scan, route.handlerNode)
|
|
678
|
+
const local = localContext(scan, route.owner)
|
|
679
|
+
for (const ctx of contexts(scan.file, local.owner)) {
|
|
680
|
+
const middleware = [
|
|
681
|
+
...ctx.middleware,
|
|
682
|
+
...local.middleware,
|
|
683
|
+
...inheritedUses(scan, route.owner, route.line),
|
|
684
|
+
...pathScopedUses(scan, route),
|
|
685
|
+
...route.middleware
|
|
686
|
+
]
|
|
687
|
+
const fullPath = joinPath(joinPath(ctx.prefix, local.prefix), route.path)
|
|
688
|
+
middleware.unshift(...crossFileUses(scan.file, fullPath))
|
|
689
|
+
const entry = {
|
|
690
|
+
method: route.method,
|
|
691
|
+
path: fullPath,
|
|
692
|
+
middleware,
|
|
693
|
+
handler: route.handler,
|
|
694
|
+
...classify(middleware),
|
|
695
|
+
file: path.relative(root, scan.file),
|
|
696
|
+
line: route.line
|
|
697
|
+
}
|
|
698
|
+
// kept off JSON output: rules read the handler's AST
|
|
699
|
+
Object.defineProperty(entry, "fn", { value: handler?.fn?.body ? handler.fn : null })
|
|
700
|
+
Object.defineProperty(entry, "fnFile", { value: path.relative(root, handler?.file ?? scan.file) })
|
|
701
|
+
Object.defineProperty(entry, "fnPath", { value: handler?.file ?? scan.file })
|
|
702
|
+
// lets rules follow a call from the handler into the function it names
|
|
703
|
+
Object.defineProperty(entry, "resolve", { value: resolveCallee })
|
|
704
|
+
Object.defineProperty(entry, "importedFile", { value: importedFile })
|
|
705
|
+
Object.defineProperty(entry, "root", { value: root })
|
|
706
|
+
Object.defineProperty(entry, "anchored", { value: ctx.anchored })
|
|
707
|
+
Object.defineProperty(entry, "rootFile", { value: ctx.rootFile })
|
|
708
|
+
Object.defineProperty(entry, "ignored", { value: ignoredRules(scan.file, route.line) })
|
|
709
|
+
routes.push(entry)
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return routes.sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method))
|
|
714
|
+
}
|