Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) + [Semantic Ver
## [Unreleased]

### Added
- Express routers defined in one file and mounted in another now get their
mount prefix and mount middleware: `app.use("/p", mw, importedRouter)`
with relative ESM or CommonJS imports (`./x.js`, `./x`, `./dir`), nested
across files, and one route per prefix when a router is mounted twice.
`parserCapabilities.express.crossFileMountPrefix` is now `true`.
- NestJS global guards: `{ provide: APP_GUARD, useClass|useExisting: X }`
providers and `useGlobalGuards(new X())` calls add the guard class name as
an auth marker to every Nest endpoint in the scan. An endpoint is GUARDED
Expand All @@ -24,11 +29,18 @@ Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) + [Semantic Ver
matrix runs Node 20, 22, 24 and 26.
- Bumped `acorn` to 8.19 and `yaml` to 2.9.1. Dev tooling moved to ESLint 10,
`@eslint/js` 10 and `globals` 17; `npm audit` is clean again.
- An exported `Router()` that no resolved mount reaches (alias or package
imports, mounts in `.ts/.tsx` files, scans of a sub-directory, factory
exports, mount cycles) is now `UNRESOLVED` with the new reason
`mount-prefix-cross-file` instead of a resolved bare path. An `express()`
app stays a root.
- `parserCapabilities.nest.globalGuardDetection` is now `true`, with new keys
`globalGuardRules`, `globalPrefix` and `publicDecorators`. The report
limitation about global guards describes what is and is not detected.

### Fixed
- Endpoint sorting is a total order when unresolved endpoints (path `null`)
are mixed with resolved ones, so output no longer depends on input order.
- Nest: decorators on the same line before `@Get(...)` are now read, and a
method declared on the anchor line (`@Get() list() {}`) no longer takes the
decorators of the next method.
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ The bounded scan builds one sorted candidate-file index and shares it across all

| Framework | Detection |
|------------|--------------------------------------------------------------------------------------------------------------------------|
| **Express** | acorn AST for `.js/.mjs/.cjs`; regex fallback for `.ts/.tsx`. Resolves `app.use('/prefix', router)` mounts in same file. AST files also track any variable assigned from `express()` / `express.Router()` / `Router()` whatever its name, and parse `app.route('/x').get(...).post(...)` chains. Path-less `router.use(requireAuth)` guards routes registered on that router after it only when `router` is a `const/let/var` declared once from a router factory, never reassigned, and the `use()` is a plain statement in the same block as the declaration. These `use()` calls are ignored (routes stay OPEN): `this.router.use(...)`, a router received as a parameter, a `use()` inside `if` or a helper function, `X.use(someCall(), auth)`, and wrappers like `jwt(...).unless(...)`. Not resolved: routers imported from another file, path-less `app.use(auth)` flowing into routers mounted on `app`, `route('/x').all(auth)` guarding the other verbs of the chain, and all of the above in `.ts/.tsx` files. Routers created in factory functions or received as parameters are parsed (routes and mounts), with the `use()` limits above. |
| **Express** | acorn AST for `.js/.mjs/.cjs`; regex fallback for `.ts/.tsx`. Resolves `app.use('/prefix', router)` mounts in the same file and across files: `app.use('/p', mw, importedRouter)` (the last argument is the router) follows relative imports (`./x.js`, `./x`, `./dir` to `dir/index.js`; ESM default, named and namespace imports; CommonJS `require`) to a router the file exports (`export default r`, `export { r }`, `export const r`, `module.exports = r`, `module.exports = { r }`, `exports.x = r`), including routers that mount other routers in other files. Mount middleware is added to the route's auth markers, and a router mounted twice yields one route per prefix. An exported `Router()` that no resolved mount reaches (alias or package imports such as `@/routes/x`, mounts in `.ts/.tsx` files, scans of a sub-directory, factory exports like `module.exports = function build() {...}`, cycles, more than 64 prefixes, routers nested inside a mounted file, a router mounted both in its own file and from another file, a router whose mount owner is nested on another local Router(), a router whose same-file owner sits on an `express()` app that is itself mounted) is `UNRESOLVED` with reason `mount-prefix-cross-file`; an `express()` app stays a root. A path-less mount middleware must be a function defined in the mounting file, otherwise the prefix counts as dynamic. `.ts/.tsx` files are never rewritten across files, so their routers keep their own path. AST files also track any variable assigned from `express()` / `express.Router()` / `Router()` whatever its name, and parse `app.route('/x').get(...).post(...)` chains. Path-less `router.use(requireAuth)` guards routes registered on that router after it only when `router` is a `const/let/var` declared once from a router factory, never reassigned, and the `use()` is a plain statement in the same block as the declaration. These `use()` calls are ignored (routes stay OPEN): `this.router.use(...)`, a router received as a parameter, a `use()` inside `if` or a helper function, `X.use(someCall(), auth)`, and wrappers like `jwt(...).unless(...)`. Not resolved: re-export barrels, aliases and package imports (see above), path-less `app.use(auth)` flowing into routers mounted on `app`, `route('/x').all(auth)` guarding the other verbs of the chain, and all of the above in `.ts/.tsx` files. Routers created in factory functions or received as parameters are parsed (routes and mounts), with the `use()` limits above. |
| **Fastify** | acorn AST for `.js/.mjs/.cjs`; regex extractor for `.ts/.mts/.cts` (no TypeScript dependency, `fastify.delete<{ Params: ... }>(...)` generics are skipped). Handles `fastify.<method>(...)` and `fastify.route({ method, url, preHandler })`. |
| **NestJS** | Decorator extraction over `.ts/.js`. Pairs `@Controller(...)` with method decorators `@Get / @Post / @Put / @Patch / @Delete / @Options / @Head / @All`. Captures class- and method-level guards (`@UseGuards`, `@Auth`, `@Roles`, `@ApiBearerAuth`), global guards (`APP_GUARD` providers, `useGlobalGuards`) and a literal `setGlobalPrefix()`; see [NestJS global guards and prefix](#nestjs-global-guards-and-prefix). |
| **OpenAPI** | Parses `*.yaml`/`*.yml`/`*.json` with `swagger:` (2.0) or `openapi:` (3.x) root. Honors operation-level `security` and root inheritance. |
Expand Down Expand Up @@ -505,7 +505,7 @@ Each run writes:
"frameworksDetected": ["express", "openapi"],
"specsDetected": ["openapi.yaml"],
"parserCapabilities": {
"express": { "sameFileMountPrefix": true, "crossFileMountPrefix": false, "dynamicMountPrefix": "UNRESOLVED", "routeChains": "AST files: ...", "routerLevelMiddleware": "AST files: ..." },
"express": { "sameFileMountPrefix": true, "crossFileMountPrefix": true, "dynamicMountPrefix": "UNRESOLVED", "routeChains": "AST files: ...", "routerLevelMiddleware": "AST files: ..." },
"fastify": { "registerPrefixPropagation": false, "routeOptionsParsed": true },
"nest": { "controllerObjectArg": "path field only", "classLevelGuards": true },
"openapi": { "missingSecurity": "UNKNOWN (conservative)", "operationSecurityEmptyArray": "OPEN" }
Expand Down
4 changes: 3 additions & 1 deletion lib/capabilities.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ export const PARSER_CAPABILITIES = Object.freeze({
language: "js, mjs, cjs (AST) · ts, tsx (regex fallback)",
httpMethods: "get/post/put/delete/patch/head/options/all",
sameFileMountPrefix: true,
crossFileMountPrefix: false,
crossFileMountPrefix: true,
crossFileMounts: "AST files: X.use([prefix, ...mw,] importedRouter) where the LAST argument is the router, imported by a relative specifier (./x.js, ./x, ./dir -> dir/index.js) through ESM default/named/namespace import or CommonJS require, and the file exports it as `export default r`, `export { r }`, `export const r`, `module.exports = r`, `module.exports = { r }`, `module.exports.x = r` or `exports.x = r`. Nesting across files works, a router mounted twice yields one route per prefix, and mount middleware (identifiers between prefix and router, same rules as router-level use) is added to the route markers. A path-less mount middleware must be a function defined in the mounting file, otherwise the prefix counts as dynamic. An exported Router() that no resolved mount reaches (alias or package imports, mounts in .ts/.tsx files, scans of a sub-directory), a mount chain with a cycle or over 64 prefixes, a mount target whose export is not a Router() binding (factories, re-exports, `export default makeRouter()`) routers nested inside a mounted file and a router mounted both in its own file and from another file, a router whose mount owner is itself nested on another local Router(), and a router whose same-file owner sits on an express() app that is itself mounted (in its own file or from another file) are UNRESOLVED (mount-prefix-cross-file); a dynamic prefix keeps mount-prefix-not-static. An express() app stays a root. Parameter or this.app owners are treated as roots. .ts/.tsx files (regex fallback) are never rewritten, so their routers keep their own path",
routerVariableTracking: "AST files: any same-file name assigned from express() / express.Router() / Router() (renamed imports included); the name heuristic (app, server, router, api, r, *router, *app) also applies, and is the only rule in the .ts/.tsx regex fallback",
routeChains: "AST files: X.route(path).get(...).post(...) with per-method middleware; route(path).all(mw) is its own ALL endpoint and does not guard the other verbs of the chain; not in the .ts/.tsx regex fallback",
routerLevelMiddleware: "AST files: path-less X.use(mw) adds markers to routes registered on X later, only when X is a const/let/var declared once from a router factory and never reassigned, the use() is an unconditional statement in the block that declares X, and the route is in that block outside nested functions; markers come from the direct argument or its callee only. Ignored (routes stay OPEN): this.router, parameters, use() inside if/loops/helper functions, X.use(<call or unknown>, mw), skip wrappers (.unless/.optional/.skip/...). Not propagated into routers mounted on X",
Expand Down Expand Up @@ -82,6 +83,7 @@ export const KNOWN_UNRESOLVED_REASONS = Object.freeze([
"global-prefix-not-static-string",
"method-or-url-missing",
"method-path-not-static-string",
"mount-prefix-cross-file",
"mount-prefix-not-static",
"path-not-static-string",
"route-opts-not-object-literal"
Expand Down
214 changes: 214 additions & 0 deletions lib/parsers/express-modules.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
import path from "path";

/**
* Cross-file Express mount resolution. Pure graph code: it never touches an
* AST. `parseExpress` extracts, per file, the exported router bindings and the
* `X.use(prefix, ...mw, importedRouter)` calls; this module links them by
* module specifier and rewrites route paths with the mount prefixes found.
*
* Results depend only on complete maps keyed by absolute path, never on file
* order, so forward and reversed candidate lists give the same output.
*/

const SPEC_EXTS = [".js", ".mjs", ".cjs", ".ts", ".tsx"];
const MAX_CHAINS = 64;
export const REASON_CROSS_FILE = "mount-prefix-cross-file";
export const REASON_NOT_STATIC = "mount-prefix-not-static";

const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);

export function joinPath(prefix, suffix) {
if (!prefix) return suffix || "/";
if (!suffix || suffix === "/") return prefix.replace(/\/$/, "") || "/";
const a = prefix.replace(/\/$/, "");
const b = suffix.startsWith("/") ? suffix : "/" + suffix;
const joined = a + b;
return joined || "/";
}

/** Join two mount prefixes where an empty one means "no prefix". */
function composePrefix(a, b) {
if (!a) return b;
if (!b) return a;
return joinPath(a, b);
}

function unionMarkers(a, b) {
return [...new Set([...a, ...b])].sort();
}

/**
* Absolute path of the scanned file a relative specifier points at, or null.
* Tries the path as written, then each extension, then `<dir>/index<ext>`,
* in a fixed order. Package names and aliases are never resolved.
*/
export function resolveSpecifier(fromAbs, spec, fileSet) {
if (typeof spec !== "string") return null;
if (!(spec.startsWith("./") || spec.startsWith("../") || spec === "." || spec === "..")) return null;
const base = path.resolve(path.dirname(fromAbs), spec);
if (SPEC_EXTS.includes(path.extname(base).toLowerCase()) && fileSet.has(base)) return base;
for (const ext of SPEC_EXTS) if (fileSet.has(base + ext)) return base + ext;
for (const ext of SPEC_EXTS) {
const idx = path.join(base, "index" + ext);
if (fileSet.has(idx)) return idx;
}
return null;
}

function createResolver(modules, fileSet) {
const incoming = new Map();
const mountTargets = new Set();
const tainted = new Set();

for (const abs of [...modules.keys()].sort()) {
const mod = modules.get(abs);
for (const m of [...mod.mounts].sort((x, y) => x.start - y.start)) {
const targetAbs = resolveSpecifier(abs, m.spec, fileSet);
if (!targetAbs) continue;
mountTargets.add(targetAbs);
const id = targetAbs + "\0" + m.key;
if (!incoming.has(id)) incoming.set(id, []);
incoming.get(id).push(m);
const target = modules.get(targetAbs);
if (target && (target.isTs || !target.exports.has(m.key))) tainted.add(targetAbs);
}
}

const fail = (reason) => ({ fail: reason });

// Chains `{prefix, markers}` for routes owned by the exported binding
// `name` of `abs`; null when nothing mounts it; `{fail}` when the prefix
// cannot be composed (all-or-nothing, never a partial path).
const chainsFor = (abs, name, visiting = new Set()) => {
const mod = modules.get(abs);
const mounts = [];
for (const [key, bound] of mod.exports) {
if (bound === name) mounts.push(...(incoming.get(abs + "\0" + key) || []));
}
if (mounts.length === 0) return null;
mounts.sort((x, y) => (x.file < y.file ? -1 : x.file > y.file ? 1 : x.start - y.start));

const id = abs + "\0" + name;
if (visiting.has(id)) return fail(REASON_CROSS_FILE);
visiting.add(id);
try {
const out = new Map();
for (const m of mounts) {
if (m.prefix === null) return fail(REASON_NOT_STATIC);
const owner = modules.get(m.file);
if (m.ownerName && owner.routerUnresolved.has(m.ownerName)) return fail(REASON_NOT_STATIC);
const sameFile = m.ownerName && hasOwn(owner.routerMounts, m.ownerName);
const rooted = m.ownerName && owner.rootMounted.has(m.ownerName);
// `rooted` only says the owner router sits on an `express()` app. The
// prefix is complete only if that app is itself a root: not mounted
// in its own file and not mounted from another file.
if (sameFile && rooted) {
const app = owner.rootMounted.get(m.ownerName);
if (hasOwn(owner.routerMounts, app) || owner.routerUnresolved.has(app)) return fail(REASON_CROSS_FILE);
const appUp = chainsFor(m.file, app, visiting);
if (appUp) return fail(REASON_CROSS_FILE);
}
// A same-file mount on another Router() is not chained, so the full
// prefix is unknown. Only a mount straight on an app is complete.
if (sameFile && !rooted) return fail(REASON_CROSS_FILE);
const local = sameFile ? owner.routerMounts[m.ownerName] : "";
const base = composePrefix(local, m.prefix);
let ups = null;
if (m.ownerLinked) {
const up = chainsFor(m.file, m.ownerLinked, visiting);
if (up && up.fail) return up;
if (up) {
// Mounted in its own file and from another file: separate
// mounts of one router, so the prefixes must not be stacked.
if (sameFile) return fail(REASON_CROSS_FILE);
ups = up.chains;
}
// An exported Router() nothing reaches is not a root: its own
// prefix lives in a file we cannot see.
else if (!m.ownerIsApp && !rooted && isExported(owner, m.ownerLinked)) return fail(REASON_CROSS_FILE);
}
if (!ups) ups = [{ prefix: "", markers: [] }];
for (const u of ups) {
const prefix = composePrefix(u.prefix, base);
const markers = unionMarkers(u.markers, m.markers);
out.set(prefix + "\0" + markers.join(","), { prefix, markers });
if (out.size > MAX_CHAINS) return fail(REASON_CROSS_FILE);
}
}
const chains = [...out.values()].sort((x, y) => {
if (x.prefix !== y.prefix) return x.prefix < y.prefix ? -1 : 1;
const xm = x.markers.join(","), ym = y.markers.join(",");
return xm < ym ? -1 : xm > ym ? 1 : 0;
});
return { chains };
} finally {
visiting.delete(id);
}
};

return { chainsFor, mountTargets, tainted };
}

function isExported(mod, name) {
for (const bound of mod.exports.values()) if (bound === name) return true;
return false;
}

// True when the file exports a Router() that no resolved chain reaches.
function hasUnreachedExportedRouter(mod, abs, resolver) {
for (const name of new Set(mod.exports.values())) {
if (mod.apps && mod.apps.has(name)) continue;
if (mod.rootMounted.has(name)) continue;
if (resolver.chainsFor(abs, name) === null) return true;
}
return false;
}

function unresolvedCopy(ep, reason) {
return { ...ep, path: null, resolved: false, unresolvedReason: reason };
}

/**
* Rewrite the endpoints emitted per file with the prefixes and middleware of
* the mounts that lead to them. `pending` maps each endpoint object to
* `{abs, ownerName, linked, isRouter}`; `linked` is the Program-level router
* binding that owns the route, or null, and `isRouter` tells `Router()` from
* an `express()` app. An exported router no resolved chain reaches becomes
* unresolved; an app stays a root.
*/
export function applyCrossFileMounts(endpoints, modules, pending, fileSet) {
const resolver = createResolver(modules, fileSet);

const out = [];
for (const ep of endpoints) {
const p = pending.get(ep);
if (!p || ep.resolved === false) {
out.push(ep);
continue;
}
const res = p.linked ? resolver.chainsFor(p.abs, p.linked) : null;
if (res && res.fail) {
out.push(unresolvedCopy(ep, res.fail));
} else if (res && hasOwn(modules.get(p.abs).routerMounts, p.linked)) {
// Mounted in its own file and from another file: those are separate
// mounts of the same router, so the two prefixes must not be stacked.
out.push(unresolvedCopy(ep, REASON_CROSS_FILE));
} else if (res) {
for (const c of res.chains) {
out.push({ ...ep, path: joinPath(c.prefix, ep.path), authMarkers: unionMarkers(ep.authMarkers, c.markers) });
}
} else if (p.linked && p.isRouter && isExported(modules.get(p.abs), p.linked) &&
!modules.get(p.abs).rootMounted.has(p.linked)) {
// An exported Router() nothing in the scan reaches: its real prefix
// lives in a file we cannot see (alias, package, .ts, sub-directory).
out.push(unresolvedCopy(ep, REASON_CROSS_FILE));
} else if (resolver.tainted.has(p.abs) ||
(p.ownerName && hasOwn(modules.get(p.abs).routerMounts, p.ownerName) &&
(resolver.mountTargets.has(p.abs) || hasUnreachedExportedRouter(modules.get(p.abs), p.abs, resolver)))) {
out.push(unresolvedCopy(ep, REASON_CROSS_FILE));
} else {
out.push(ep);
}
}
return out;
}
Loading
Loading