diff --git a/CHANGELOG.md b/CHANGELOG.md index b23f1f7..4f07e06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## [Unreleased] + +### Added +- **`@kidkender/archmind-express-parser` 0.1.0 (new package): Express.js, JavaScript and TypeScript.** One graph per route: routers mounted across files (`require` / `module.exports`, ES modules, `router.route()` chains, routers mounted from arrays in a `forEach`, registrar functions handed the app); the middleware chain in Express order, classified by npm package, name and — for project middleware — body into `ir:auth_gate`, `ir:authz_check` and `ir:validation_gate` (rate limiting, optional auth and CSRF as `ir:unknown_middleware` with that role; body parsers, logging, CORS left out); the handler through controller modules, class methods and wrappers; service calls, including class controllers with constructor-injected services; transactions (Sequelize, TypeORM, Prisma, Mongoose, Knex) in the handler or one call below, with the writes inside them as `ir:txn_write`; ownership checks from `archmind.json`. +- `analysis`, the CLI and the MCP server detect an Express project (`package.json` depends on `express`, not NestJS; at the root or one directory down when the root is not another backend) after every other framework. The MCP server caches Express graphs and re-parses when a JS/TS file changes; `archmind_get_dependents` indexes Express service calls (`userService` / `userService::createUser`). +- `research/cross-framework`: Express versions of auth-only, auth-authz, auth-validation, auth-service-call and auth-transaction; Express matches NestJS and Laravel on each. +- `research/express-corpus`: the projects, commits, scripts and results the parser was measured with. + +### Changed +- `analysis`: a route counts as throttled when a node has role `rate_limiting` (Express rate limiters, Laravel `throttle:`), not only when an auth node is named so; without it every rate-limited login route reported `no_rate_limiting`. + +### Measured, with limits +- On six projects read while building it: 163 of 163 route registration sites (regex count). On six it had not seen: 101 of 101 real registrations (the regex also counted three HTTP client calls), every route that opens a transaction in a production Sequelize app (sfbrigade/bats-server), and 9 of 15 security middleware classified correctly blind, 15 of 15 after fixes made on that same set. +- Decorator-based routing (routing-controllers, tsoa) is not read: such a project yields no routes. Not extracted: tenant isolation, side effects, response shaping. Not yet through the LLM accuracy benchmark. + ## [0.9.1] - 2026-10-28 ### Added diff --git a/README.md b/README.md index ab13cd9..0fc78cb 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ArchMind -**Semantic execution graph engine for Laravel, NestJS, Spring Boot, and Go/Gin — built for AI assistants and CI.** +**Semantic execution graph engine for Laravel, NestJS, Spring Boot, Go/Gin and Express — built for AI assistants and CI.** ArchMind parses your app into a structured execution graph and gives AI assistants (Claude, Cursor, Copilot) the minimal relevant subgraph for a query — achieving comparable or better answer quality at a fraction of the tokens that naive file-dump RAG uses. @@ -29,6 +29,8 @@ The difference compounds on large codebases where a single route touches dozens **Go/Gin support is newer and not yet held to the same bar.** The numbers above are Laravel/NestJS/Spring Boot only, from hand-verified ground truth compared against real LLM calls. Go/Gin has been validated structurally — full-project parsing against 3 real Gin+GORM codebases with zero crashes and spot-checked node accuracy — but not yet run through the same hand-verified accuracy benchmark. Treat it as functional but less battle-tested until that benchmark exists. +**Express support is the newest, measured structurally only.** On six projects it had not seen it found every real route (101 of 101) and every transaction-opening route of a production app, and classified 9 of 15 security middleware correctly before fixes made on that same set (15 of 15 after) — see [`research/express-corpus`](research/express-corpus/README.md). It has not been through the LLM accuracy benchmark either. + --- ## MCP Server (Claude Code / AI assistants) @@ -226,12 +228,21 @@ DELETE /api/vaults/{id} A handler that calls one of them (directly, or one hop into a helper method on the same receiver) is treated as authorized by ownership. A handler that acts on a URL `:id` without resolving the caller is still reported — that is the case worth looking at. `ignoreFindings` drops whole finding types (e.g. `["missing_authorization"]`) for a project where the rule does not apply at all. +### Express + +- JavaScript and TypeScript; routers mounted across files through `require` / `module.exports` and ES modules, `router.route()` chains, routers mounted from arrays, registrar functions handed the app +- Middleware chain in Express order (global, path-scoped, per-router, per-route, arrays), classified by package, name and — for project middleware — body: passport / express-jwt / custom JWT checks as auth gates, role checks as authorization, celebrate / express-validator / Joi wrappers as validation, rate limiters, CSRF, optional auth; body parsers, logging, CORS and the like left out +- Handlers resolved through controller modules, class methods and wrappers (`catchAsync`); service calls, including class controllers with constructor-injected services +- Transactions (Sequelize, TypeORM, Prisma, Mongoose, Knex) in the handler or one call below, with the writes inside them +- Ownership authorization (as above) and `guards` from `archmind.json` +- Not read: decorator-based routing (routing-controllers, tsoa); tenant isolation and side effects are not extracted. Details: [`packages/express-parser`](packages/express-parser/README.md) + --- ## Requirements - Node.js ≥ 18 -- A Laravel (≥8, tested on 10/11/12), NestJS, Spring Boot (Maven or Gradle), or Go/Gin project +- A Laravel (≥8, tested on 10/11/12), NestJS, Spring Boot (Maven or Gradle), Go/Gin, or Express project ## License diff --git a/apps/cli/build.mjs b/apps/cli/build.mjs index d35cf72..b996d34 100644 --- a/apps/cli/build.mjs +++ b/apps/cli/build.mjs @@ -19,6 +19,7 @@ await build({ "@kidkender/archmind-laravel-parser", "@kidkender/archmind-nestjs-parser", "@kidkender/archmind-go-parser", + "@kidkender/archmind-express-parser", "@kidkender/archmind-llm-client", "@kidkender/archmind-orchestrator", "@kidkender/archmind-protocol", diff --git a/apps/cli/package.json b/apps/cli/package.json index 8306209..a63d061 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -19,6 +19,7 @@ "@kidkender/archmind-llm-client": "*", "@kidkender/archmind-nestjs-parser": "*", "@kidkender/archmind-go-parser": "*", + "@kidkender/archmind-express-parser": "*", "@kidkender/archmind-orchestrator": "*", "@kidkender/archmind-protocol": "*", "@kidkender/archmind-retrieval": "*", diff --git a/apps/cli/src/utils/parse-project.ts b/apps/cli/src/utils/parse-project.ts index 2392940..ec0e458 100644 --- a/apps/cli/src/utils/parse-project.ts +++ b/apps/cli/src/utils/parse-project.ts @@ -10,9 +10,10 @@ import { } from "@kidkender/archmind-laravel-parser" import { parseNestJSProject } from "@kidkender/archmind-nestjs-parser" import { parseGinProjectAt, isGinProject, findGoFiles } from "@kidkender/archmind-go-parser" +import { parseExpressProjectAt, isExpressProject, findExpressRoot, findSourceFiles } from "@kidkender/archmind-express-parser" import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" -export type Framework = "laravel" | "nestjs" | "springboot" | "go" | "unknown" +export type Framework = "laravel" | "nestjs" | "springboot" | "go" | "express" | "unknown" function tryParseSpringBoot(root: string): { graphs: IntermediateExecutionGraph[]; fileCount: number } | null { try { @@ -103,6 +104,8 @@ export function detectFramework(projectRoot: string): Framework { if (existsSync(join(projectRoot, "artisan"))) return "laravel" if (existsSync(join(projectRoot, "nest-cli.json"))) return "nestjs" if (existsSync(join(projectRoot, "pom.xml")) || existsSync(join(projectRoot, "build.gradle"))) return "springboot" + // last: express is a dependency of many Node projects, so every other signal wins + if (isExpressProject(projectRoot)) return "express" return "unknown" } @@ -126,6 +129,12 @@ export function parseProject(projectRoot: string): ParsedProject { return { graphs, routeCount: graphs.length, fileCount: findGoFiles(projectRoot).length, projectRoot, framework } } + if (framework === "express") { + const graphs = parseExpressProjectAt(projectRoot) + const appRoot = findExpressRoot(projectRoot) ?? projectRoot + return { graphs, routeCount: graphs.length, fileCount: findSourceFiles(appRoot).length, projectRoot, framework } + } + // Default: Laravel const config = loadProjectConfig(projectRoot) const { aliasMap, routeFiles, routeWrapping, routeNamespaceWrapping, routePrefixWrapping } = resolveAliasMap(projectRoot, config) diff --git a/package-lock.json b/package-lock.json index 342fe41..22e72df 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "license": "MIT", "dependencies": { "@kidkender/archmind-explainer": "*", + "@kidkender/archmind-express-parser": "*", "@kidkender/archmind-go-parser": "*", "@kidkender/archmind-laravel-parser": "*", "@kidkender/archmind-llm-client": "*", @@ -1431,6 +1432,10 @@ "resolved": "packages/explainer", "link": true }, + "node_modules/@kidkender/archmind-express-parser": { + "resolved": "packages/express-parser", + "link": true + }, "node_modules/@kidkender/archmind-go-parser": { "resolved": "packages/go-parser", "link": true @@ -6197,6 +6202,7 @@ "version": "0.2.3", "license": "MIT", "dependencies": { + "@kidkender/archmind-express-parser": "*", "@kidkender/archmind-go-parser": "*", "@kidkender/archmind-laravel-parser": "*", "@kidkender/archmind-nestjs-parser": "*", @@ -6289,6 +6295,27 @@ "node": ">=18" } }, + "packages/express-parser": { + "name": "@kidkender/archmind-express-parser", + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "@kidkender/archmind-protocol": "^0.5.1", + "ts-morph": "^23.0.0" + }, + "devDependencies": { + "@kidkender/archmind-laravel-parser": "*", + "@kidkender/archmind-nestjs-parser": "*", + "@types/jest": "^29.5.0", + "@types/node": "^20.0.0", + "jest": "^29.0.0", + "ts-jest": "^29.0.0", + "typescript": "^5.4.0" + }, + "engines": { + "node": ">=18" + } + }, "packages/go-parser": { "name": "@kidkender/archmind-go-parser", "version": "0.3.0", @@ -6441,6 +6468,7 @@ "license": "MIT", "dependencies": { "@kidkender/archmind-explainer": "*", + "@kidkender/archmind-express-parser": "*", "@kidkender/archmind-go-parser": "*", "@kidkender/archmind-laravel-parser": "*", "@kidkender/archmind-lens": "*", diff --git a/packages/analysis/build.mjs b/packages/analysis/build.mjs index 6e1b7a4..ce14fb3 100644 --- a/packages/analysis/build.mjs +++ b/packages/analysis/build.mjs @@ -17,6 +17,7 @@ await build({ "@kidkender/archmind-nestjs-parser", "@kidkender/archmind-springboot-parser", "@kidkender/archmind-go-parser", + "@kidkender/archmind-express-parser", ], minify: false, }) diff --git a/packages/analysis/package.json b/packages/analysis/package.json index 02d9e0e..76a4b25 100644 --- a/packages/analysis/package.json +++ b/packages/analysis/package.json @@ -20,6 +20,7 @@ "@kidkender/archmind-nestjs-parser": "*", "@kidkender/archmind-springboot-parser": "*", "@kidkender/archmind-go-parser": "*", + "@kidkender/archmind-express-parser": "*", "@kidkender/archmind-protocol": "*" }, "devDependencies": { diff --git a/packages/analysis/src/analyze.ts b/packages/analysis/src/analyze.ts index 724c0ea..8d0d38a 100644 --- a/packages/analysis/src/analyze.ts +++ b/packages/analysis/src/analyze.ts @@ -18,6 +18,8 @@ export async function analyzeProject(projectRoot: string): Promise const springbootParser = require("@kidkender/archmind-springboot-parser") // eslint-disable-next-line @typescript-eslint/no-require-imports const goParser = require("@kidkender/archmind-go-parser") + // eslint-disable-next-line @typescript-eslint/no-require-imports + const expressParser = require("@kidkender/archmind-express-parser") const isNestJS = existsSync(join(projectRoot, "nest-cli.json")) const isSpringBoot = !isNestJS && springbootParser.isSpringBootProject(projectRoot) @@ -25,6 +27,9 @@ export async function analyzeProject(projectRoot: string): Promise // the PHP/JS/Java branches so a Gin project never falls through to the // Laravel default below. const isGin = !isNestJS && !isSpringBoot && goParser.isGinProject(projectRoot) + // Express last before the Laravel default: a package.json depending on + // express (and not NestJS), at the root or one directory down. + const isExpress = !isNestJS && !isSpringBoot && !isGin && expressParser.isExpressProject(projectRoot) if (isNestJS) { return analyzeNestJS(projectRoot, nestjsParser, userConfig) @@ -35,6 +40,9 @@ export async function analyzeProject(projectRoot: string): Promise if (isGin) { return analyzeGin(projectRoot, goParser, userConfig) } + if (isExpress) { + return analyzeExpress(projectRoot, expressParser, userConfig) + } return analyzeLaravel(projectRoot, laravelParser, userConfig) } @@ -120,6 +128,22 @@ function analyzeGin(projectRoot: string, parser: any, userConfig?: ArchMindUserC return routes } +function analyzeExpress(projectRoot: string, parser: any, userConfig?: ArchMindUserConfig): RouteInfo[] { + const { parseExpressProjectAt } = parser + const graphs = parseExpressProjectAt(projectRoot) as any[] + const routes: RouteInfo[] = [] + + for (const graph of graphs) { + const handler = graph.nodes.find((n: any) => n.type === "ir:business_handler") + if (!handler) continue + try { + routes.push(buildRoute(graph, handler, "express", projectRoot, userConfig)) + } catch { /* skip */ } + } + + return routes +} + function inferPublicRoutes(routes: RouteInfo[]): void { const someHaveAuth = routes.some(r => r.authGates.length > 0) if (!someHaveAuth) return @@ -138,8 +162,8 @@ function buildRoute(graph: any, handler: any, framework: string, projectRoot?: s const services = graph.nodes.filter((n: any) => n.type === "ir:service_call").map((n: any) => n.symbol as string) const hasTxn = graph.nodes.some((n: any) => n.type === "ir:txn_boundary") const throttled = graph.nodes.some((n: any) => - (n.type === "ir:auth_gate" || n.type === "ir:authz_check") && - THROTTLE_RE.test(n.symbol as string) + n.role === "rate_limiting" || + ((n.type === "ir:auth_gate" || n.type === "ir:authz_check") && THROTTLE_RE.test(n.symbol as string)) ) const line = resolveHandlerLine(handler, projectRoot) diff --git a/packages/express-parser/README.md b/packages/express-parser/README.md new file mode 100644 index 0000000..6d5cd41 --- /dev/null +++ b/packages/express-parser/README.md @@ -0,0 +1,80 @@ +# @kidkender/archmind-express-parser + +**Express.js adapter for ArchMind.** Turns an Express project — JavaScript or TypeScript — into one execution graph per route: the route, its authentication, authorization and validation middleware, the services its handler calls, and the database transactions it opens. + +Uses ts-morph to read the code; nothing in the project is installed or run. + +--- + +## Install + +```bash +npm install @kidkender/archmind-express-parser +``` + +## Usage + +```ts +import { isExpressProject, parseExpressProjectAt } from "@kidkender/archmind-express-parser" + +if (isExpressProject(root)) { + const graphs = parseExpressProjectAt(root) // IntermediateExecutionGraph[], one per route + for (const g of graphs) console.log(g.entrypoint, g.nodes.map((n) => n.type)) +} +``` + +`parseExpressProjectAt` reads the project's `archmind.json` itself. `parseExpressSources(files, options)` takes already-read files (used in tests). `extractRoutes` and `classifyMiddleware` are exported for tools that want the routes and middleware before they become graphs. + +Most of ArchMind uses it through `@kidkender/archmind-analysis`, the CLI (`archmind trace`, `archmind findings`) and the MCP server. + +--- + +## Detection + +A project is Express when its `package.json` depends on `express` and not on NestJS — at the root, or in one directory below it (`server/`, `backend/`) when the root is not itself another backend (`artisan`, `composer.json`, `go.mod`, `pom.xml`, `build.gradle`, `nest-cli.json`). The CLI and MCP server check every other framework first. + +## What it extracts + +- **Routes**: `app.get/post/put/patch/delete/all/options/head`, `router.route("/x").get(...).post(...)`, path arrays; routers created with `express()`, `express.Router()`, `Router()` or `require("express").Router()`. +- **Mounts across files**: `app.use("/api", router)` with the router imported through `require` / `module.exports`, `exports.x`, ES `import` / `export default`, re-exports, or built in one expression (`export default Router().use("/api", api)`); routers mounted from an array in a `forEach` (each path stays with its own router); registrar functions handed the app (`require("./routes")(app)`); factory functions that return a router. Path constants, concatenation and template literals resolve; a path that does not is reported, not guessed. +- **Middleware chain** in Express order: `app.use` / `router.use` before the route, path-scoped `use("/admin", mw)`, parent middleware before a mount, `use(path, mw, router)`, middleware passed as arrays or constants holding one. +- **Middleware kinds**, decided in this order: + 1. `archmind.json` `guards.auth_gate` / `guards.authz_check`; + 2. `(err, req, res, next)` error handlers (left out); + 3. optional auth (`auth.optional`, `credentialsRequired: false`) — resolves a user if present, blocks nothing; + 4. the npm package behind the value: passport, express-jwt, express-oauth2-jwt-bearer, celebrate, express-validator, express-validation, express-rate-limit, csurf, helmet, cors, body parsers, ...; + 5. the name: `checkJwt`, `requireAuth`, `verifyAuthToken`, `checkRole`, `isAdmin`, `isAdminUser`, `validate*`, `*Limiter`; `auth(...)` / `authorize(...)` called with roles is both an auth gate and an authorization check; + 6. the body of project middleware: `jwt.verify` or the `authorization` header → authentication (optional when the function always ends in `next()`); a role or permission read off the user and answered with 401/403 → authorization; `csrf`; a middleware that never stops the request → infrastructure. + + Auth, authorization and validation become `ir:auth_gate`, `ir:authz_check`, `ir:validation_gate`. Rate limiting, optional auth and CSRF are `ir:unknown_middleware` with that `role` (the IR has no type for them yet). Infrastructure (body parsing, logging, CORS, static files, sessions) is left out of the graph. +- **Handler**: written inline, a function or controller method from another module, a class static or instance method (`ctrl.list.bind(ctrl)`), looked through wrappers (`catchAsync(fn)`, `asyncHandler(...)`). +- **Service calls**: calls from the handler into project functions in service-like files (service, repository, provider, model, ...) or reached through a module or instance (`userService.createUser` → `userService::createUser`), including `this.users.findAll()` in class controllers whose services come in through the constructor. Utility modules, helpers in the handler's own file and `req` / `res` / `next` calls are not service calls. +- **Transactions**, in the handler or one call below it: `$transaction`, `withTransaction`, `startTransaction`, and `x.transaction(...)` when `x` is a database handle (`sequelize`, `dataSource`, `prisma`, `knex`, `getManager()`, ...) or comes from an ORM package. Writes inside it become `ir:txn_write` (`Order::save`): TypeORM `manager.save(Order, ...)`, Sequelize / Mongoose `Order.create(...)`, Prisma `tx.order.create(...)` and the array form, and for an unmanaged transaction the calls that pass it (`{ transaction: t }`, `{ session }`). +- **Ownership**: a call to one of `archmind.json` `authorization.ownershipSources`, in the handler or one call below → `ir:authz_check` `ownership:`. + +Nodes carry the `file` and `line` where the parser found them, relative to the project root. + +## Configuration + +`archmind.json` at the project root: + +```json +{ + "guards": { "auth_gate": ["gatekeeper"], "authz_check": ["requireTeamMember"] }, + "authorization": { "ownershipSources": ["currentUser"] }, + "ignoreFindings": [] +} +``` + +## Measured + +On six projects read while building it: 163 of 163 route registration sites. On six projects it had not seen: 101 of 101 real registrations, every transaction-opening route of a production Sequelize app, and 15 of 15 security middleware classified after fixes made on that set (9 of 15 blind). Details, commits and method: [`research/express-corpus`](../../research/express-corpus/README.md). + +## Limits + +- **Decorator-based routing** (routing-controllers, tsoa, inversify-express-utils) is not read: such a project yields no routes. +- Paths computed at runtime (from a `Map`, a config file, a loop over values that are not array literals) are reported as unresolved. +- Registration order across files is approximate: a route registered by a function in another file than the app is ordered after every middleware of the app's file, so middleware registered after that call is over-applied to it. +- Middleware classification is heuristic. A middleware with an uninformative name and a body that reads no token and no role is `ir:unknown_middleware`; name it in `archmind.json` `guards`. +- One call below the handler is followed for transactions and ownership; a graph shows the route's first transaction. +- Not extracted: tenant isolation, side effects (events, queues, mail), response shaping. diff --git a/packages/express-parser/jest.config.js b/packages/express-parser/jest.config.js new file mode 100644 index 0000000..29918b5 --- /dev/null +++ b/packages/express-parser/jest.config.js @@ -0,0 +1,16 @@ +/** @type {import('jest').Config} */ +export default { + preset: "ts-jest/presets/default-esm", + testEnvironment: "node", + extensionsToTreatAsEsm: [".ts"], + testPathIgnorePatterns: ["/node_modules/", "/dist/", "/fixtures/"], + moduleNameMapper: { + "^(\\.{1,2}/.*)\\.js$": "$1", + }, + transform: { + "^.+\\.tsx?$": ["ts-jest", { + useESM: true, + diagnostics: { ignoreCodes: [151002, 1343] }, + }], + }, +} diff --git a/packages/express-parser/package.json b/packages/express-parser/package.json new file mode 100644 index 0000000..9a53c03 --- /dev/null +++ b/packages/express-parser/package.json @@ -0,0 +1,51 @@ +{ + "name": "@kidkender/archmind-express-parser", + "version": "0.1.0", + "description": "Static analysis parser for Express.js projects (JavaScript and TypeScript) — extracts routes, middleware chains and auth patterns into ArchMind IR graphs.", + "type": "module", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "files": [ + "dist", + "!dist/__tests__", + "!dist/__tests__/**" + ], + "keywords": [ + "archmind", + "express", + "nodejs", + "parser", + "static-analysis" + ], + "license": "MIT", + "homepage": "https://github.com/Architecture-Mind/ArchMind#readme", + "repository": { + "type": "git", + "url": "https://github.com/Architecture-Mind/ArchMind", + "directory": "packages/express-parser" + }, + "engines": { + "node": ">=18" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "build": "tsc", + "dev": "tsc --watch", + "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" + }, + "dependencies": { + "@kidkender/archmind-protocol": "^0.5.1", + "ts-morph": "^23.0.0" + }, + "devDependencies": { + "@kidkender/archmind-laravel-parser": "*", + "@kidkender/archmind-nestjs-parser": "*", + "@types/jest": "^29.5.0", + "@types/node": "^20.0.0", + "jest": "^29.0.0", + "ts-jest": "^29.0.0", + "typescript": "^5.4.0" + } +} diff --git a/packages/express-parser/src/__tests__/cross-framework.test.ts b/packages/express-parser/src/__tests__/cross-framework.test.ts new file mode 100644 index 0000000..bd12346 --- /dev/null +++ b/packages/express-parser/src/__tests__/cross-framework.test.ts @@ -0,0 +1,91 @@ +/** + * Cross-framework equivalence: the same security pattern written in Laravel, + * NestJS and Express produces the same set of semantic IR node types. + * Fixtures live in research/cross-framework/{pattern}/{laravel,nestjs,express}/. + * + * Not covered for Express (outside the parser's scope): auth-side-effects + * (events, queues), auth-api-resource (response shaping), cron-transaction. + */ +import { describe, test, expect } from "@jest/globals" +import { join, dirname } from "path" +import { fileURLToPath } from "url" +import { parseRouteFile, augmentGraph, inferProjectConfig, resolveAliasMap } from "@kidkender/archmind-laravel-parser" +import { parseNestJSProject } from "@kidkender/archmind-nestjs-parser" +import { validateGraph } from "@kidkender/archmind-protocol" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" +import { parseExpressProjectAt } from "../adapter.js" + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const FIXTURES = join(__dirname, "../../../../research/cross-framework") + +/** Node types that carry the security / data semantics compared across frameworks. */ +const SEMANTIC_TYPES = new Set([ + "ir:auth_gate", "ir:authz_check", "ir:validation_gate", "ir:business_handler", + "ir:service_call", "ir:txn_boundary", "ir:txn_write", +]) + +function semanticTypes(graphs: IntermediateExecutionGraph[], only: ReadonlySet = SEMANTIC_TYPES): string[] { + expect(graphs).toHaveLength(1) + return [...new Set(graphs[0].nodes.map((n) => n.type).filter((t) => only.has(t)))].sort() +} + +/** + * The types a pattern is about: the security layers always (a missing or extra + * one must show), plus the pattern's own concern. Incidental calls outside it — + * the Laravel auth-authz fixture also updates the model, which Laravel reports + * as a service call — are not part of the comparison. + */ +function comparedTypes(expected: string[]): Set { + return new Set(["ir:auth_gate", "ir:authz_check", "ir:validation_gate", "ir:business_handler", ...expected]) +} + +function laravel(pattern: string): IntermediateExecutionGraph[] { + const root = join(FIXTURES, pattern, "laravel") + const config = inferProjectConfig(root) + const aliasMap = resolveAliasMap(root, config) as unknown as Record + return parseRouteFile(join(root, "routes/api.php"), { aliasMap }).map((g) => augmentGraph(g, { projectRoot: root, config })) +} + +const nestjs = (pattern: string) => parseNestJSProject(join(FIXTURES, pattern, "nestjs")) +const express = (pattern: string) => parseExpressProjectAt(join(FIXTURES, pattern, "express")) + +const PATTERNS: { pattern: string; expected: string[] }[] = [ + { pattern: "auth-only", expected: ["ir:auth_gate", "ir:business_handler"] }, + { pattern: "auth-authz", expected: ["ir:auth_gate", "ir:authz_check", "ir:business_handler"] }, + { pattern: "auth-validation", expected: ["ir:auth_gate", "ir:business_handler", "ir:validation_gate"] }, + { pattern: "auth-service-call", expected: ["ir:auth_gate", "ir:business_handler", "ir:service_call"] }, + { pattern: "auth-transaction", expected: ["ir:auth_gate", "ir:business_handler", "ir:txn_boundary", "ir:txn_write"] }, +] + +describe.each(PATTERNS)("cross-framework: $pattern", ({ pattern, expected }) => { + test("Express emits the expected semantic node types", () => { + expect(semanticTypes(express(pattern))).toEqual(expected) + }) + + test("Express matches NestJS", () => { + const only = comparedTypes(expected) + expect(semanticTypes(express(pattern), only)).toEqual(semanticTypes(nestjs(pattern), only)) + }) + + test("Express matches Laravel", () => { + const only = comparedTypes(expected) + expect(semanticTypes(express(pattern), only)).toEqual(semanticTypes(laravel(pattern), only)) + }) + + test("Express graphs use only IR node types and edge relations", () => { + for (const g of express(pattern)) { + const unknown = validateGraph(g).violations.filter( + (v) => v.kind === "unknown_node_type" || v.kind === "unknown_edge_relation", + ) + expect(unknown).toEqual([]) + } + }) +}) + +test("transaction writes name their entities, as NestJS does", () => { + const [g] = express("auth-transaction") + const writes = g.nodes.filter((n) => n.type === "ir:txn_write").map((n) => n.symbol) + expect(writes).toEqual(["Order::save", "Payment::save"]) + const [ng] = nestjs("auth-transaction") + expect(ng.nodes.filter((n) => n.type === "ir:txn_write").map((n) => n.symbol).sort()).toEqual(writes) +}) diff --git a/packages/express-parser/src/__tests__/handler.test.ts b/packages/express-parser/src/__tests__/handler.test.ts new file mode 100644 index 0000000..5702083 --- /dev/null +++ b/packages/express-parser/src/__tests__/handler.test.ts @@ -0,0 +1,224 @@ +import { describe, test, expect } from "@jest/globals" +import { IR_NODE_TYPES, IR_EDGE_RELATIONS } from "@kidkender/archmind-protocol" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" +import { parseExpressSources, type ParseExpressOptions } from "../adapter.js" + +function graphs(files: Record, opts: ParseExpressOptions = {}): IntermediateExecutionGraph[] { + return parseExpressSources(Object.entries(files).map(([path, content]) => ({ path, content })), opts) +} + +function graph(gs: IntermediateExecutionGraph[], entry: string): IntermediateExecutionGraph { + const g = gs.find((x) => x.entrypoint === entry) + if (!g) throw new Error(`no graph ${entry}; have ${gs.map((x) => x.entrypoint).join(", ")}`) + return g +} + +const symbolsOf = (g: IntermediateExecutionGraph, type: string) => g.nodes.filter((n) => n.type === type).map((n) => n.symbol) + +describe("analyzeHandler — service calls", () => { + const files = { + "src/routes/user.route.js": ` + const express = require('express') + const userController = require('../controllers/user.controller') + const router = express.Router() + router.post('/users', userController.createUser) + module.exports = router + `, + "src/app.js": ` + const app = require('express')() + app.use(require('./routes/user.route')) + `, + "src/controllers/user.controller.js": ` + const userService = require('../services/user.service') + const pick = require('../utils/pick') + const format = (u) => u + const createUser = async (req, res) => { + const filter = pick(req.body, ['name']) + const user = await userService.createUser(filter) + res.status(201).send(format(user)) + } + module.exports = { createUser } + `, + "src/services/user.service.js": ` + const createUser = async (body) => body + module.exports = { createUser } + `, + "src/utils/pick.js": ` + module.exports = (o, keys) => o + `, + } + + test("calls into a service module become ir:service_call nodes; utilities, local helpers and req/res do not", () => { + const g = graph(graphs(files), "POST /users") + expect(g.nodes.filter((n) => n.type === IR_NODE_TYPES.SERVICE_CALL)).toEqual([ + expect.objectContaining({ symbol: "userService::createUser", file: "src/services/user.service.js", line: 2 }), + ]) + expect(g.edges).toContainEqual(expect.objectContaining({ from: "handler", relation: IR_EDGE_RELATIONS.CALLS })) + }) + + test("a class controller reaches its service through a constructor parameter property", () => { + const g = graph(graphs({ + "src/app.ts": ` + import express from 'express' + import { UserController } from './user.controller' + import { UserService } from './user.service' + const ctrl = new UserController(new UserService()) + const app = express() + app.get('/users', ctrl.list.bind(ctrl)) + `, + "src/user.controller.ts": ` + import { UserService } from './user.service' + export class UserController { + constructor(private readonly users: UserService) {} + async list(req, res) { + res.json(await this.users.findAll()) + } + } + `, + "src/user.service.ts": ` + export class UserService { + async findAll() { return [] } + } + `, + }), "GET /users") + expect(g.nodes.find((n) => n.id === "handler")).toMatchObject({ symbol: "ctrl.list", file: "src/user.controller.ts", line: 5 }) + expect(symbolsOf(g, IR_NODE_TYPES.SERVICE_CALL)).toEqual(["users::findAll"]) + }) +}) + +describe("analyzeHandler — transactions", () => { + test("ORM transactions in the handler or one call below it; a domain method named transaction is not one", () => { + const gs = graphs({ + "app.js": ` + const express = require('express') + const { sequelize } = require('./db') + const orderService = require('./order.service') + const app = express() + app.post('/orders', async (req, res) => { + await sequelize.transaction(async (t) => { await Order.create(req.body, { transaction: t }) }) + res.send() + }) + app.post('/payments', async (req, res) => { await orderService.pay(req.body); res.send() }) + app.post('/wallet', async (req, res) => { wallet.transaction(5); res.send() }) + app.post('/mongo', async (req, res) => { const s = await mongoose.startSession(); await s.withTransaction(async () => {}); res.send() }) + `, + "order.service.js": ` + const prisma = require('./prisma') + exports.pay = async (body) => prisma.$transaction([prisma.payment.create({ data: body })]) + `, + }) + expect(graph(gs, "POST /orders").nodes.find((n) => n.id === "txn")).toMatchObject({ + type: IR_NODE_TYPES.TXN_BOUNDARY, symbol: "sequelize.transaction", file: "app.js", line: 7, + }) + expect(graph(gs, "POST /payments").nodes.find((n) => n.id === "txn")).toMatchObject({ + symbol: "prisma.$transaction", file: "order.service.js", line: 3, + }) + expect(graph(gs, "POST /mongo").nodes.find((n) => n.id === "txn")?.symbol).toBe("s.withTransaction") + expect(graph(gs, "POST /wallet").nodes.some((n) => n.id === "txn")).toBe(false) + }) + + test("writes inside a transaction: callback, Prisma array, unmanaged transaction passed as an option", () => { + const gs = graphs({ + "app.js": ` + const app = require('express')() + app.post('/a', async (req, res) => { + await sequelize.transaction(async (t) => { + await Order.create(req.body, { transaction: t }) + await prisma.audit.create({ data: {} }) + }) + }) + app.post('/b', async (req, res) => { + await prisma.$transaction([prisma.order.create({ data: req.body }), prisma.payment.update({ where: {}, data: {} })]) + }) + app.post('/c', async (req, res) => { + const t = await sequelize.transaction() + await Order.update(req.body, { where: {}, transaction: t }) + await Log.create({ msg: 'not in the transaction' }) + await t.commit() + }) + `, + }) + const writes = (key: string) => graph(gs, key).nodes.filter((n) => n.type === IR_NODE_TYPES.TXN_WRITE).map((n) => n.symbol) + expect(writes("POST /a")).toEqual(["Order::create", "Audit::create"]) + expect(writes("POST /b")).toEqual(["Order::create", "Payment::update"]) + expect(writes("POST /c")).toEqual(["Order::update"]) + expect(graph(gs, "POST /a").edges).toContainEqual(expect.objectContaining({ from: "txn", to: "txn_write_0", relation: IR_EDGE_RELATIONS.WRAPS })) + }) + + test("a transaction in a helper of the route file is found one call below the handler", () => { + const [g] = graphs({ + "routes.js": ` + const router = require('express').Router() + async function resetCounts(userId) { + return models.sequelize.transaction(async (transaction) => { + await models.Count.update({ n: 0 }, { where: {}, transaction }) + }) + } + router.post('/close', async (req, res) => { await resetCounts(req.user.id); res.end() }) + module.exports = router + `, + }) + expect(g.nodes.find((n) => n.id === "txn")).toMatchObject({ symbol: "models.sequelize.transaction", line: 4 }) + expect(g.nodes.filter((n) => n.type === IR_NODE_TYPES.SERVICE_CALL)).toEqual([]) // a local helper is not a service + }) + + test("a transaction on a handle from an ORM package counts whatever it is named", () => { + const g = graph(graphs({ + "app.ts": ` + import express from 'express' + import { DataSource } from 'typeorm' + const store = new DataSource({ type: 'postgres' }) + const app = express() + app.post('/x', async (req, res) => { await getManager().transaction(async (m) => {}); res.send() }) + app.post('/y', async (req, res) => { await orm.transaction(async (m) => {}); res.send() }) + `, + }), "POST /x") + expect(g.nodes.find((n) => n.id === "txn")?.symbol).toBe("getManager().transaction") + }) +}) + +describe("analyzeHandler — ownership", () => { + test("a configured ownership source called by the handler or its service is an ir:authz_check", () => { + const files = { + "app.js": ` + const express = require('express') + const svc = require('./note.service') + const app = express() + app.delete('/notes/:id', requireAuth, async (req, res) => { + const me = await currentUser(req) + await svc.remove(me, req.params.id) + res.send() + }) + app.put('/notes/:id', requireAuth, async (req, res) => { await svc.update(req); res.send() }) + app.get('/notes/:id', requireAuth, async (req, res) => { res.send() }) + `, + "note.service.js": ` + exports.remove = async (me, id) => {} + exports.update = async (req) => { const me = await currentUser(req) } + `, + } + const gs = graphs(files, { ownershipSources: ["currentUser"] }) + + const del = graph(gs, "DELETE /notes/:id") + expect(del.nodes.find((n) => n.id === "ownership")).toMatchObject({ + type: IR_NODE_TYPES.AUTHZ_CHECK, symbol: "ownership:currentUser", file: "app.js", line: 6, + }) + expect(graph(gs, "PUT /notes/:id").nodes.find((n) => n.id === "ownership")?.file).toBe("note.service.js") + expect(graph(gs, "GET /notes/:id").nodes.some((n) => n.id === "ownership")).toBe(false) + expect(graphs(files).every((g) => !g.nodes.some((n) => n.id === "ownership"))).toBe(true) + }) + + test("ownership and the transaction follow the handler in the precedes chain", () => { + const [g] = graphs({ + "app.js": ` + const app = require('express')() + app.post('/x', requireAuth, async (req, res) => { + const me = currentUser(req) + await db.transaction(async () => {}) + }) + `, + }, { ownershipSources: ["currentUser"] }) + const chain = g.edges.filter((e) => e.relation === IR_EDGE_RELATIONS.PRECEDES).map((e) => `${e.from}->${e.to}`) + expect(chain).toEqual(["mw_0->handler", "handler->ownership", "ownership->txn"]) + }) +}) diff --git a/packages/express-parser/src/__tests__/middleware.test.ts b/packages/express-parser/src/__tests__/middleware.test.ts new file mode 100644 index 0000000..04503d3 --- /dev/null +++ b/packages/express-parser/src/__tests__/middleware.test.ts @@ -0,0 +1,247 @@ +import { describe, test, expect } from "@jest/globals" +import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" +import { createExpressProject } from "../project.js" +import { extractRoutes, type ExpressRoute } from "../routes.js" +import { classifyMiddleware, type ClassifyOptions } from "../middleware.js" +import { parseExpressSources } from "../adapter.js" + +function routesOf(files: Record): ExpressRoute[] { + return extractRoutes(createExpressProject(Object.entries(files).map(([path, content]) => ({ path, content })))).routes +} + +/** "name=kind+kind" for each middleware of the single route in `app.js`. */ +function kindsOf(files: Record, opts: ClassifyOptions = {}): string[] { + const [route] = routesOf(files) + return route.middleware.map((m) => `${m.name}=${classifyMiddleware(m, opts).kinds.join("+")}`) +} + +describe("classifyMiddleware — packages", () => { + test("auth, rate limit, validation, CSRF and infrastructure packages", () => { + expect(kindsOf({ + "app.js": ` + const express = require('express') + const passport = require('passport') + const helmet = require('helmet') + const cors = require('cors') + const rateLimit = require('express-rate-limit') + const { celebrate, Joi } = require('celebrate') + const csrf = require('csurf') + const { expressjwt } = require('express-jwt') + const app = express() + const limiter = rateLimit({ windowMs: 60000 }) + app.use(helmet()) + app.use(cors()) + app.use(express.json()) + app.use(passport.initialize()) + app.post('/x', + limiter, + passport.authenticate('jwt', { session: false }), + expressjwt({ secret: 's', algorithms: ['HS256'] }), + celebrate({ body: Joi.object() }), + csrf(), + (req, res) => {}) + `, + })).toEqual([ + "helmet=infrastructure", "cors=infrastructure", "json=infrastructure", "initialize=infrastructure", + "limiter=rate_limit", "authenticate=auth_gate", "expressjwt=auth_gate", "celebrate=validation_gate", "csrf=csrf", + ]) + }) + + test("express-validator chains are validation", () => { + expect(kindsOf({ + "app.ts": ` + import express from 'express' + import { body, param } from 'express-validator' + const app = express() + app.put('/users/:id', param('id').isInt(), body('email').isEmail().normalizeEmail(), (req, res) => {}) + `, + })).toEqual(["param=validation_gate", "body=validation_gate"]) + }) +}) + +describe("classifyMiddleware — names", () => { + test("auth and authorization names; an auth factory with roles is both", () => { + expect(kindsOf({ + "app.js": ` + const app = require('express')() + app.delete('/users/:id', checkJwt, checkRole(['ADMIN']), isAdmin, auth('manageUsers'), authorize(), requireAuth, (req, res) => {}) + `, + })).toEqual([ + "checkJwt=auth_gate", "checkRole=authz_check", "isAdmin=authz_check", + "auth=auth_gate+authz_check", "authorize=auth_gate", "requireAuth=auth_gate", + ]) + }) + + test("validation and rate-limit names", () => { + expect(kindsOf({ + "app.js": ` + const app = require('express')() + app.post('/login', loginLimiter, validate(schema), validateBody(schema), (req, res) => {}) + `, + })).toEqual(["loginLimiter=rate_limit", "validate=validation_gate", "validateBody=validation_gate"]) + }) + + test("auth.required is an auth gate; auth.optional and credentialsRequired: false block nothing", () => { + expect(kindsOf({ + "app.ts": ` + import express from 'express' + import { expressjwt as jwt } from 'express-jwt' + const auth = { + required: jwt({ secret: 's', algorithms: ['HS256'] }), + optional: jwt({ secret: 's', credentialsRequired: false, algorithms: ['HS256'] }), + } + const app = express() + app.get('/feed', auth.required, auth.optional, jwt({ secret: 's', credentialsRequired: false }), (req, res) => {}) + `, + })).toEqual(["required=auth_gate", "optional=optional_auth", "jwt=optional_auth"]) + }) +}) + +describe("classifyMiddleware — bodies of project middleware", () => { + test("jwt.verify is authentication; a role check that denies is authorization; an ORM scope() is neither", () => { + expect(kindsOf({ + "app.js": ` + const app = require('express')() + const jwt = require('jsonwebtoken') + const apiMiddleware = async (req, res, next) => { + const token = req.headers['x-token'] + if (!token) return res.status(401).send() + req.user = jwt.verify(token, process.env.SECRET) + const user = await User.scope('withSecretColumns').findOne({ where: { id: req.user.id } }) + return next() + } + const adminMiddleware = (req, res, next) => { + if (req.user && req.user.isAdmin) return next() + return res.status(403).send('Forbidden') + } + const tracker = (req, res, next) => { + if (!user) return res.status(500).send() + next() + } + app.get('/admin', apiMiddleware, adminMiddleware, tracker, (req, res) => {}) + `, + })).toEqual(["apiMiddleware=auth_gate", "adminMiddleware=authz_check", "tracker=unknown"]) + }) + + test("middleware that never stops a request is infrastructure; one that mentions csrf is csrf", () => { + expect(kindsOf({ + "app.js": ` + const app = require('express')() + const lusca = require('lusca') + app.use((req, res, next) => { res.locals.user = req.user; next() }) + app.use((req, res, next) => { if (req.path === '/upload') next(); else lusca.csrf()(req, res, next) }) + app.get('/', (req, res) => {}) + `, + })).toEqual(["=infrastructure", "=csrf"]) + }) + + test("role flags on the user (isSuperUser, isAdminUser) answered with 403 are authorization; role names with a User suffix too", () => { + expect(kindsOf({ + "app.js": ` + const app = require('express')() + function isAdminUser(req, res, next) { if (req.user.isAdminUser) return next(); res.status(403).end() } + async function isPartnerUser(req, res, next) { + if (!req.user.isSuperUser && (await req.user.getOrganization()).type !== 'PARTNER') return res.status(403).end() + next() + } + app.get('/x', isAdminUser, isPartnerUser, (req, res) => {}) + `, + })).toEqual(["isAdminUser=authz_check", "isPartnerUser=authz_check"]) + }) + + test("a token read that always ends in next() is optional auth; one that stops the request is a gate", () => { + expect(kindsOf({ + "app.js": ` + const app = require('express')() + async function attachUser(req, res, next) { + const { authorization } = req.headers + if (authorization?.startsWith('Bearer ')) req.user = await findUser(authorization.slice(7)) + next() + } + async function bearerOnly(req, res, next) { + const { authorization } = req.headers + if (!authorization?.startsWith('Bearer ')) return res.status(401).end() + req.user = await findUser(authorization.slice(7)) + return next() + } + app.get('/x', attachUser, bearerOnly, (req, res) => {}) + `, + })).toEqual(["attachUser=optional_auth", "bearerOnly=auth_gate"]) + }) + + test("compound token names; expressValidator() installs, body() validates; more infrastructure packages", () => { + expect(kindsOf({ + "app.ts": ` + import express from 'express' + import expressValidator from 'express-validator' + import { body } from 'express-validator' + import expressLayouts from 'express-ejs-layouts' + import nocache from 'nocache' + import { verifyAuthToken } from './auth' + const app = express() + app.use(expressValidator()) + app.use(expressLayouts) + app.use(nocache()) + app.post('/x', verifyAuthToken, body('email').isEmail(), (req, res) => {}) + `, + })).toEqual([ + "expressValidator=infrastructure", "expressLayouts=infrastructure", "nocache=infrastructure", + "verifyAuthToken=auth_gate", "body=validation_gate", + ]) + }) + + test("(err, req, res, next) is an error handler", () => { + expect(kindsOf({ + "app.js": ` + const app = require('express')() + function onError(err, req, res, next) { res.status(500).send() } + app.use(onError) + app.get('/', (req, res) => {}) + `, + })).toEqual(["onError=error_handler"]) + }) +}) + +describe("classifyMiddleware — archmind.json guards", () => { + test("configured names win over every heuristic", () => { + expect(kindsOf({ + "app.js": ` + const app = require('express')() + app.get('/x', gatekeeper, validate(schema), passportConfig.isAuthorized, (req, res) => {}) + `, + }, { authGates: ["gatekeeper"], authzChecks: ["validate", "passportConfig.isAuthorized"] })).toEqual([ + "gatekeeper=auth_gate", "validate=authz_check", "isAuthorized=authz_check", + ]) + }) +}) + +describe("parseExpressSources — classified graphs", () => { + test("infrastructure is left out; controls become their IR nodes in order", () => { + const [g] = parseExpressSources([{ + path: "app.js", + content: ` + const express = require('express') + const app = express() + app.use(express.json()) + app.post('/orders', limiter, auth('createOrder'), validate(schema), (req, res) => {}) + `, + }]) + expect(g.nodes.map((n) => [n.type, n.role])).toEqual([ + [IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, "rate_limiting"], + [IR_NODE_TYPES.AUTH_GATE, "authentication"], + [IR_NODE_TYPES.AUTHZ_CHECK, "authorization"], + [IR_NODE_TYPES.VALIDATION_GATE, "validation"], + [IR_NODE_TYPES.BUSINESS_HANDLER, "handler"], + ]) + expect(g.nodes[2]).toMatchObject({ symbol: "auth('createOrder')", args: ["'createOrder'"] }) + expect(g.edges).toHaveLength(4) + }) + + test("guards from options reach the classifier", () => { + const [g] = parseExpressSources( + [{ path: "app.js", content: `const app = require('express')(); app.get('/x', gatekeeper, (req, res) => {})` }], + { authGates: ["gatekeeper"] }, + ) + expect(g.nodes[0].type).toBe(IR_NODE_TYPES.AUTH_GATE) + }) +}) diff --git a/packages/express-parser/src/__tests__/routes.test.ts b/packages/express-parser/src/__tests__/routes.test.ts new file mode 100644 index 0000000..ec9c436 --- /dev/null +++ b/packages/express-parser/src/__tests__/routes.test.ts @@ -0,0 +1,379 @@ +import { describe, test, expect } from "@jest/globals" +import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" +import { createExpressProject } from "../project.js" +import { extractRoutes, joinPath, type ExpressRoute } from "../routes.js" +import { parseExpressSources } from "../adapter.js" +import type { SourceFile } from "../scanner.js" + +function routesOf(files: Record): ExpressRoute[] { + const sources: SourceFile[] = Object.entries(files).map(([path, content]) => ({ path, content })) + return extractRoutes(createExpressProject(sources)).routes +} + +function keys(routes: ExpressRoute[]): string[] { + return routes.map((r) => `${r.method} ${r.path}`).sort() +} + +function route(routes: ExpressRoute[], key: string): ExpressRoute { + const r = routes.find((x) => `${x.method} ${x.path}` === key) + if (!r) throw new Error(`no route ${key}; have ${keys(routes).join(", ")}`) + return r +} + +const names = (r: ExpressRoute) => r.middleware.map((m) => m.name) + +describe("extractRoutes — registration", () => { + test("routes registered on the app in one file", () => { + const routes = routesOf({ + "app.js": ` + const express = require('express') + const app = express() + app.get('/health', (req, res) => res.send('ok')) + app.post('/items', createItem) + app.delete(\`/items/:id\`, removeItem) + function createItem(req, res) {} + function removeItem(req, res) {} + `, + }) + expect(keys(routes)).toEqual(["DELETE /items/:id", "GET /health", "POST /items"]) + expect(route(routes, "POST /items").handler).toMatchObject({ symbol: "createItem", file: "app.js", line: 7 }) + expect(route(routes, "GET /health").handler.symbol).toBe("") + }) + + test("a router in another CommonJS file, mounted with a prefix", () => { + const routes = routesOf({ + "src/app.js": ` + const express = require('express') + const users = require('./routes/users') + const app = express() + app.use('/api/users', users) + `, + "src/routes/users.js": ` + const router = require('express').Router() + router.get('/', list) + router.get('/:id', show) + function list() {} + function show() {} + module.exports = router + `, + }) + expect(keys(routes)).toEqual(["GET /api/users", "GET /api/users/:id"]) + }) + + test("ES modules: named Router import, chained use, a default export built in one expression", () => { + const routes = routesOf({ + "src/main.ts": ` + import express from 'express' + import routes from './routes' + const app = express() + app.use(routes) + `, + "src/routes/index.ts": ` + import { Router } from 'express' + import tags from './tags' + import articles from './articles' + const api = Router().use(tags).use(articles) + export default Router().use('/api', api) + `, + "src/routes/tags.ts": ` + import { Router } from 'express' + const router = Router() + router.get('/tags', async (req, res) => {}) + export default router + `, + "src/routes/articles.ts": ` + import { Router } from 'express' + export const router = Router() + router.post('/articles', async (req, res) => {}) + export default router + `, + }) + expect(keys(routes)).toEqual(["GET /api/tags", "POST /api/articles"]) + }) + + test("router.route() chains register one route per verb", () => { + const routes = routesOf({ + "app.js": ` + const express = require('express') + const router = express.Router() + router + .route('/:userId') + .get(ctrl.get) + .patch(ctrl.update) + .delete(ctrl.remove) + const ctrl = { get() {}, update() {}, remove() {} } + const app = express() + app.use('/users', router) + `, + }) + expect(keys(routes)).toEqual(["DELETE /users/:userId", "GET /users/:userId", "PATCH /users/:userId"]) + }) + + test("routers mounted from an array in a forEach keep each path with its own router", () => { + const routes = routesOf({ + "routes/index.js": ` + const express = require('express') + const authRoute = require('./auth') + const userRoute = require('./user') + const router = express.Router() + const defaultRoutes = [ + { path: '/auth', route: authRoute }, + { path: '/users', route: userRoute }, + ] + defaultRoutes.forEach((route) => { + router.use(route.path, route.route) + }) + module.exports = router + `, + "routes/auth.js": ` + const router = require('express').Router() + router.post('/login', (req, res) => {}) + module.exports = router + `, + "routes/user.js": ` + const router = require('express').Router() + router.get('/', (req, res) => {}) + module.exports = router + `, + }) + expect(keys(routes)).toEqual(["GET /users", "POST /auth/login"]) + }) + + test("a registrar function handed the app registers on it", () => { + const routes = routesOf({ + "server.js": ` + const express = require('express') + const app = express() + require('./routes')(app) + `, + "routes.js": ` + module.exports = function (app) { + app.get('/a', (req, res) => {}) + app.post('/b', (req, res) => {}) + } + `, + }) + expect(keys(routes)).toEqual(["GET /a", "POST /b"]) + }) + + test("calls that are not on a router are ignored, and so is app.get(setting)", () => { + const routes = routesOf({ + "app.js": ` + const express = require('express') + const axios = require('axios') + const app = express() + const cache = new Map() + cache.get('/x', 1) + axios.get('/remote', { timeout: 1 }) + const env = app.get('env') + app.get('/real', (req, res) => {}) + `, + }) + expect(keys(routes)).toEqual(["GET /real"]) + }) + + test("a path that cannot be resolved to a string is reported, not guessed", () => { + const { routes, unresolvedPaths } = extractRoutes(createExpressProject([{ + path: "app.js", + content: ` + const app = require('express')() + for (const url of getUrls()) app.get(url, (req, res) => {}) + `, + }])) + expect(routes).toEqual([]) + expect(unresolvedPaths).toEqual([{ file: "app.js", line: 3, text: "url" }]) + }) + + test("path constants and concatenation resolve", () => { + const routes = routesOf({ + "app.js": ` + const express = require('express') + const API = '/api' + const VERSION = 'v2' + const app = express() + app.get(API + '/' + VERSION + '/ping', (req, res) => {}) + app.get(\`\${API}/status\`, (req, res) => {}) + `, + }) + expect(keys(routes)).toEqual(["GET /api/status", "GET /api/v2/ping"]) + }) +}) + +describe("extractRoutes — middleware chain", () => { + test("app.use middleware applies to routes registered after it, in order", () => { + const routes = routesOf({ + "app.js": ` + const express = require('express') + const app = express() + app.get('/before', (req, res) => {}) + app.use(helmet()) + app.use(express.json()) + app.get('/after', (req, res) => {}) + app.use(lateMiddleware) + `, + }) + expect(names(route(routes, "GET /before"))).toEqual([]) + expect(names(route(routes, "GET /after"))).toEqual(["helmet", "json"]) + }) + + test("path-scoped middleware runs only under its path; route-level middleware follows it", () => { + const routes = routesOf({ + "app.js": ` + const express = require('express') + const app = express() + app.use('/admin', requireAdmin) + app.get('/admin/stats', audit, (req, res) => {}) + app.get('/administrators', (req, res) => {}) + app.get('/public', (req, res) => {}) + `, + }) + expect(names(route(routes, "GET /admin/stats"))).toEqual(["requireAdmin", "audit"]) + expect(names(route(routes, "GET /administrators"))).toEqual([]) + expect(names(route(routes, "GET /public"))).toEqual([]) + }) + + test("middleware passed in an array, or in a constant holding one, is spread out", () => { + const routes = routesOf({ + "user.ts": ` + import { Router } from 'express' + import { checkJwt } from './checkJwt' + import { checkRole } from './checkRole' + const adminOnly = [checkJwt, checkRole(['ADMIN'])] + const router = Router() + router.get('/', [checkJwt, checkRole(['ADMIN'])], list) + router.delete('/:id', adminOnly, remove) + export default router + `, + }) + for (const key of ["GET /", "DELETE /:id"]) { + const r = route(routes, key) + expect(names(r)).toEqual(["checkJwt", "checkRole"]) + expect(r.middleware[1].args).toEqual(["['ADMIN']"]) + } + }) + + test("middleware on a parent applies to a mounted router; use(path, mw, router) applies mw to it", () => { + const routes = routesOf({ + "app.js": ` + const express = require('express') + const api = require('./api') + const app = express() + app.use(cors()) + app.use('/api', authenticate, api) + `, + "api.js": ` + const router = require('express').Router() + router.use(rateLimit) + router.get('/me', (req, res) => {}) + module.exports = router + `, + }) + expect(names(route(routes, "GET /api/me"))).toEqual(["cors", "authenticate", "rateLimit"]) + }) +}) + +describe("extractRoutes — handlers", () => { + test("controller methods from a CommonJS module, an exports object, and a class", () => { + const routes = routesOf({ + "routes.js": ` + const express = require('express') + const userController = require('./user.controller') + const { list } = require('./list.controller') + const UserController = require('./UserController') + const router = express.Router() + router.post('/users', userController.create) + router.get('/users', list) + router.get('/users/:id', UserController.getOne) + module.exports = router + `, + "user.controller.js": ` + exports.create = async (req, res) => {} + `, + "list.controller.js": ` + const list = (req, res) => {} + module.exports = { list } + `, + "UserController.js": ` + class UserController { + static getOne = async (req, res) => {} + } + module.exports = UserController + `, + }) + expect(route(routes, "POST /users").handler).toMatchObject({ symbol: "userController.create", file: "user.controller.js", line: 2 }) + expect(route(routes, "GET /users").handler).toMatchObject({ symbol: "list", file: "list.controller.js", line: 2 }) + expect(route(routes, "GET /users/:id").handler).toMatchObject({ symbol: "UserController.getOne", file: "UserController.js", line: 3 }) + }) + + test("a wrapper (catchAsync) and .bind are looked through to the handler", () => { + const routes = routesOf({ + "routes.js": ` + const express = require('express') + const catchAsync = (fn) => (req, res, next) => fn(req, res, next).catch(next) + const ctrl = require('./ctrl') + const router = express.Router() + router.get('/a', ctrl.a) + router.get('/b', catchAsync(ctrl.b)) + router.get('/c', ctrl.c.bind(ctrl)) + router.get('/d', catchAsync(async (req, res) => {})) + module.exports = router + `, + "ctrl.js": ` + const catchAsync = require('./catchAsync') + const a = catchAsync(async (req, res) => {}) + const b = async (req, res) => {} + function c(req, res) {} + module.exports = { a, b, c } + `, + "catchAsync.js": ` + module.exports = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next) + `, + }) + expect(route(routes, "GET /a").handler).toMatchObject({ symbol: "ctrl.a", file: "ctrl.js", line: 3 }) + expect(route(routes, "GET /b").handler).toMatchObject({ symbol: "ctrl.b", file: "ctrl.js", line: 4 }) + expect(route(routes, "GET /c").handler).toMatchObject({ symbol: "ctrl.c", file: "ctrl.js", line: 5 }) + expect(route(routes, "GET /d").handler).toMatchObject({ symbol: "", file: "routes.js", line: 9 }) + }) + + test("a call that wraps no project function keeps its own text", () => { + const routes = routesOf({ + "docs.js": ` + const express = require('express') + const swaggerUi = require('swagger-ui-express') + const router = express.Router() + router.get('/', swaggerUi.setup(specs)) + module.exports = router + `, + }) + expect(route(routes, "GET /").handler.symbol).toBe("swaggerUi.setup(specs)") + }) +}) + +describe("parseExpressSources — graphs", () => { + test("one graph per route: middleware then handler, linked by precedes", () => { + const [g] = parseExpressSources([{ + path: "app.js", + content: ` + const app = require('express')() + app.post('/orders', authenticate, validate(schema), (req, res) => {}) + `, + }]) + expect(g.entrypoint).toBe("POST /orders") + expect(g.framework).toBe("express") + expect(g.nodes.map((n) => n.type)).toEqual([ + IR_NODE_TYPES.AUTH_GATE, IR_NODE_TYPES.VALIDATION_GATE, IR_NODE_TYPES.BUSINESS_HANDLER, + ]) + expect(g.nodes[1]).toMatchObject({ symbol: "validate(schema)", args: ["schema"], file: "app.js", line: 3 }) + expect(g.edges.map((e) => `${e.from}->${e.to}`)).toEqual(["mw_0->mw_1", "mw_1->handler"]) + }) +}) + +describe("joinPath", () => { + test("joins prefixes without doubled or trailing slashes", () => { + expect(joinPath("", "/")).toBe("/") + expect(joinPath("/api", "/")).toBe("/api") + expect(joinPath("/api/", "/users/")).toBe("/api/users") + expect(joinPath("", "users")).toBe("/users") + expect(joinPath("/v1", "*")).toBe("/v1/*") + }) +}) diff --git a/packages/express-parser/src/__tests__/skeleton.test.ts b/packages/express-parser/src/__tests__/skeleton.test.ts new file mode 100644 index 0000000..4242b06 --- /dev/null +++ b/packages/express-parser/src/__tests__/skeleton.test.ts @@ -0,0 +1,121 @@ +import { describe, test, expect, beforeEach, afterEach } from "@jest/globals" +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "fs" +import { tmpdir } from "os" +import { join } from "path" +import { isExpressProject, findExpressRoot } from "../detect.js" +import { findSourceFiles, readSourceFiles } from "../scanner.js" +import { createExpressProject, relativePath } from "../project.js" +import { parseExpressProjectAt } from "../adapter.js" + +let dir: string + +function write(rel: string, content: string): void { + const abs = join(dir, rel) + mkdirSync(join(abs, ".."), { recursive: true }) + writeFileSync(abs, content) +} + +function packageJson(rel: string, deps: Record, devDeps: Record = {}): void { + write(rel, JSON.stringify({ name: "app", dependencies: deps, devDependencies: devDeps })) +} + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "archmind-express-")) +}) + +afterEach(() => { + rmSync(dir, { recursive: true, force: true }) +}) + +describe("isExpressProject / findExpressRoot", () => { + test("a package.json depending on express is an Express project", () => { + packageJson("package.json", { express: "^4.19.0" }) + expect(isExpressProject(dir)).toBe(true) + expect(findExpressRoot(dir)).toBe(dir) + }) + + test("a NestJS project is not, even though it depends on express", () => { + packageJson("package.json", { express: "^4.19.0", "@nestjs/core": "^10.0.0" }) + expect(isExpressProject(dir)).toBe(false) + }) + + test("an Express app one directory down (server/) is found", () => { + packageJson("package.json", { react: "^18.0.0" }) + packageJson("server/package.json", { express: "^4.19.0" }) + expect(findExpressRoot(dir)).toBe(join(dir, "server")) + }) + + test("no package.json, a malformed one, or no express dependency is not Express", () => { + expect(isExpressProject(dir)).toBe(false) + write("package.json", "{ not json") + expect(isExpressProject(dir)).toBe(false) + packageJson("package.json", { koa: "^2.0.0" }) + expect(isExpressProject(dir)).toBe(false) + }) + + test("a Laravel (or Go, Java) root with a Node server in a subdirectory is not Express", () => { + write("artisan", "") + packageJson("package.json", { vite: "^5.0.0" }) + packageJson("server/package.json", { express: "^4.19.0" }) + expect(isExpressProject(dir)).toBe(false) + }) + + test("node_modules is never taken for the app", () => { + packageJson("package.json", { react: "^18.0.0" }) + packageJson("node_modules/package.json", { express: "^4.19.0" }) + expect(isExpressProject(dir)).toBe(false) + }) +}) + +describe("findSourceFiles / readSourceFiles", () => { + test("lists JS and TS server files, skipping tests, declarations, build output and front-end folders", () => { + write("src/app.js", "") + write("src/routes/user.route.ts", "") + write("src/routes/user.route.test.ts", "") + write("src/types.d.ts", "") + write("src/server.mjs", "") + write("dist/app.js", "") + write("node_modules/express/index.js", "") + write("public/bundle.min.js", "") + write("tests/app.test.js", "") + write("README.md", "") + + expect(findSourceFiles(dir)).toEqual(["src/app.js", "src/routes/user.route.ts", "src/server.mjs"]) + }) + + test("reads contents with project-relative paths", () => { + write("src/app.js", "const express = require('express')") + expect(readSourceFiles(dir)).toEqual([{ path: "src/app.js", content: "const express = require('express')" }]) + }) +}) + +describe("createExpressProject", () => { + test("loads JavaScript and TypeScript files under their project-relative paths", () => { + const { files } = createExpressProject([ + { path: "src/app.js", content: "const express = require('express'); const app = express();" }, + { path: "src/routes.ts", content: "import { Router } from 'express'; export const r: Router = Router();" }, + ]) + expect([...files.keys()]).toEqual(["src/app.js", "src/routes.ts"]) + const app = files.get("src/app.js")! + expect(relativePath(app)).toBe("src/app.js") + expect(app.getVariableDeclaration("app")).toBeDefined() + expect(files.get("src/routes.ts")!.getVariableDeclaration("r")).toBeDefined() + }) +}) + +describe("parseExpressProjectAt", () => { + test("an app one directory down reports node files relative to the project root", () => { + packageJson("package.json", { react: "^18.0.0" }) + packageJson("server/package.json", { express: "^4.19.0" }) + write("server/src/app.js", "const app = require('express')(); app.get('/x', function show(req, res) {})") + const [g] = parseExpressProjectAt(dir) + expect(g.entrypoint).toBe("GET /x") + expect(g.nodes.find((n) => n.id === "handler")?.file).toBe("server/src/app.js") + }) + + test("returns no graphs for a project that is not Express", () => { + packageJson("package.json", { koa: "^2.0.0" }) + write("src/app.js", "") + expect(parseExpressProjectAt(dir)).toEqual([]) + }) +}) diff --git a/packages/express-parser/src/adapter.ts b/packages/express-parser/src/adapter.ts new file mode 100644 index 0000000..097a840 --- /dev/null +++ b/packages/express-parser/src/adapter.ts @@ -0,0 +1,63 @@ +import { relative } from "path" +import { loadUserConfig } from "@kidkender/archmind-protocol" +import type { IntermediateExecutionGraph, SemanticAdapter } from "@kidkender/archmind-protocol" +import { findExpressRoot } from "./detect.js" +import { readSourceFiles, type SourceFile } from "./scanner.js" +import { createExpressProject } from "./project.js" +import { extractRoutes } from "./routes.js" +import { Evaluator } from "./evaluator.js" +import { analyzeHandler } from "./handler.js" +import { routeToGraph } from "./graph.js" + +export interface ParseExpressOptions { + /** Middleware / function names classified as ir:auth_gate (archmind.json `guards.auth_gate`). */ + authGates?: string[] + /** Middleware / function names classified as ir:authz_check (archmind.json `guards.authz_check`). */ + authzChecks?: string[] + /** Functions that resolve the caller's own record (archmind.json `authorization.ownershipSources`). */ + ownershipSources?: string[] +} + +/** + * Parses already-read Express sources into one IntermediateExecutionGraph per + * route. Takes the file list directly so tests can use synthetic fixtures; + * parseExpressProjectAt reads a project from disk. + */ +export function parseExpressSources(sources: SourceFile[], opts: ParseExpressOptions = {}): IntermediateExecutionGraph[] { + if (sources.length === 0) return [] + const ep = createExpressProject(sources) + const ev = new Evaluator(ep) + const { routes } = extractRoutes(ep, ev) + const classify = { authGates: opts.authGates, authzChecks: opts.authzChecks } + return routes.map((r) => routeToGraph(r, classify, analyzeHandler(r, ev, { ownershipSources: opts.ownershipSources }))) +} + +/** + * Discovers and parses an Express project on disk (the root itself, or the one + * directory below it that holds the Express app). Reads archmind.json from the + * project root; anything passed in `opts` takes precedence. + */ +export function parseExpressProjectAt(root: string, opts: ParseExpressOptions = {}): IntermediateExecutionGraph[] { + const appRoot = findExpressRoot(root) + if (!appRoot) return [] + const userConfig = loadUserConfig(root) + const graphs = parseExpressSources(readSourceFiles(appRoot), { + authGates: userConfig?.guards?.auth_gate, + authzChecks: userConfig?.guards?.authz_check, + ownershipSources: userConfig?.authorization?.ownershipSources, + ...opts, + }) + // node files are relative to the app; report them relative to the project root + const prefix = relative(root, appRoot).replace(/\\/g, "/") + if (!prefix) return graphs + for (const g of graphs) { + for (const n of g.nodes) if (n.file) n.file = `${prefix}/${n.file}` + } + return graphs +} + +export class ExpressAdapter implements SemanticAdapter { + parseProject(root: string): IntermediateExecutionGraph[] { + return parseExpressProjectAt(root) + } +} diff --git a/packages/express-parser/src/detect.ts b/packages/express-parser/src/detect.ts new file mode 100644 index 0000000..7592aa2 --- /dev/null +++ b/packages/express-parser/src/detect.ts @@ -0,0 +1,71 @@ +import { existsSync, readFileSync, readdirSync, statSync } from "fs" +import { join } from "path" + +/** Directories that never hold the Express app's own package.json. */ +const SKIP_DIRS = new Set(["node_modules", "dist", "build", "coverage", "vendor", "public", "docs"]) + +/** Files at a root that make it another kind of backend. */ +const OTHER_BACKEND_MARKERS = ["artisan", "composer.json", "go.mod", "pom.xml", "build.gradle", "build.gradle.kts", "nest-cli.json"] + +/** Packages whose presence means the project is not plain Express (it has its own parser). */ +const OTHER_FRAMEWORKS = ["@nestjs/core", "@nestjs/common"] + +interface PackageJson { + dependencies?: Record + devDependencies?: Record +} + +function readPackageJson(dir: string): PackageJson | null { + const path = join(dir, "package.json") + if (!existsSync(path)) return null + try { + return JSON.parse(readFileSync(path, "utf-8")) as PackageJson + } catch { + return null + } +} + +function usesExpress(pkg: PackageJson | null): boolean { + if (!pkg) return false + const deps = { ...pkg.devDependencies, ...pkg.dependencies } + return "express" in deps && !OTHER_FRAMEWORKS.some((name) => name in deps) +} + +/** + * The directory holding the Express app: `root` itself when its package.json + * depends on `express` (and not on NestJS), otherwise a direct subdirectory + * that does (`server/`, `backend/`, `api/` in a repo that also holds a + * front-end). Null when neither does. + */ +export function findExpressRoot(root: string): string | null { + const own = readPackageJson(root) + if (usesExpress(own)) return root + // A NestJS app depends on express too; never look below a project that is NestJS. + if (own && OTHER_FRAMEWORKS.some((name) => name in { ...own.devDependencies, ...own.dependencies })) return null + // A root that is another backend (a Laravel app with a small Node socket + // server in server/, a Go or Java service) is that backend, not Express. + if (OTHER_BACKEND_MARKERS.some((marker) => existsSync(join(root, marker)))) return null + + let entries: string[] + try { + entries = readdirSync(root) + } catch { + return null + } + for (const entry of entries.sort()) { + if (SKIP_DIRS.has(entry) || entry.startsWith(".")) continue + const dir = join(root, entry) + try { + if (!statSync(dir).isDirectory()) continue + } catch { + continue + } + if (usesExpress(readPackageJson(dir))) return dir + } + return null +} + +/** True when `root`, or one directory below it, is an Express app. */ +export function isExpressProject(root: string): boolean { + return findExpressRoot(root) !== null +} diff --git a/packages/express-parser/src/evaluator.ts b/packages/express-parser/src/evaluator.ts new file mode 100644 index 0000000..9e43942 --- /dev/null +++ b/packages/express-parser/src/evaluator.ts @@ -0,0 +1,607 @@ +import { Node, SyntaxKind, type SourceFile, type ParameterDeclaration, type CallExpression } from "ts-morph" +import { lookupName, type Binding } from "./scope.js" +import { relativePath, type ExpressProject } from "./project.js" + +/** + * What an expression can evaluate to, as far as routing is concerned. Evaluation + * is demand-driven and returns every value an expression may have (a parameter + * bound at several call sites, both arms of a conditional). + */ +export type Value = + /** An Express app (`express()`) or router (`express.Router()`); `id` is its creation site. */ + | { kind: "router"; id: string; isApp: boolean; file: string; line: number } + /** `router.route("/x")` and the verbs chained on it. */ + | { kind: "routeChain"; router: Extract; paths: string[] } + | { kind: "function"; node: Node; name: string | null } + | { kind: "class"; node: Node } + | { kind: "instance"; classNode: Node } + /** A project file used as a value: a namespace import, or require() of a file without module.exports. */ + | { kind: "module"; file: SourceFile } + /** An npm package or a member of one: "express", "express.Router", "passport.authenticate". */ + | { kind: "external"; name: string } + /** + * The result of calling a package member other than express itself: + * `helmet()` → "helmet", `rateLimit({...})` → "express-rate-limit", + * `body("email").isEmail()` → "express-validator.body" (methods called on + * the result keep its name). + */ + | { kind: "externalCall"; name: string } + | { kind: "object"; node: Node } + | { kind: "array"; node: Node } + | { kind: "string"; value: string } + +export type RouterValue = Extract + +/** Parameter → values, for evaluating inside a loop callback element by element. */ +export type Env = ReadonlyMap +const EMPTY_ENV: Env = new Map() + +const MAX_VALUES = 64 +const MODULE_EXTENSIONS = ["", ".ts", ".js", ".mts", ".cts", ".mjs", ".cjs", "/index.ts", "/index.js", "/index.mjs", "/index.cjs"] + +export class Evaluator { + private readonly memo = new Map() + private readonly inProgress = new Set() + private callSites: Map | null = null + + constructor(private readonly ep: ExpressProject) {} + + // ------------------------------------------------------------------------- + // Expressions + // ------------------------------------------------------------------------- + + evaluate(node: Node | undefined, env: Env = EMPTY_ENV): Value[] { + if (!node) return [] + const cacheable = env.size === 0 + if (cacheable) { + const cached = this.memo.get(node) + if (cached) return cached + } + if (this.inProgress.has(node)) return [] + this.inProgress.add(node) + let result: Value[] + try { + result = dedupe(this.evaluateUncached(node, env)).slice(0, MAX_VALUES) + } finally { + this.inProgress.delete(node) + } + if (cacheable) this.memo.set(node, result) + return result + } + + private evaluateUncached(node: Node, env: Env): Value[] { + if (Node.isParenthesizedExpression(node) || Node.isAsExpression(node) || Node.isNonNullExpression(node) || + Node.isTypeAssertion(node) || Node.isSatisfiesExpression(node) || Node.isAwaitExpression(node)) { + return this.evaluate(node.getExpression(), env) + } + if (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) { + return [{ kind: "string", value: node.getLiteralValue() }] + } + if (Node.isTemplateExpression(node)) return this.evaluateTemplate(node, env) + if (Node.isBinaryExpression(node)) { + const op = node.getOperatorToken().getKind() + if (op === SyntaxKind.PlusToken) return concat(this.evaluate(node.getLeft(), env), this.evaluate(node.getRight(), env)) + if (op === SyntaxKind.BarBarToken || op === SyntaxKind.QuestionQuestionToken) { + return [...this.evaluate(node.getLeft(), env), ...this.evaluate(node.getRight(), env)] + } + return [] + } + if (Node.isConditionalExpression(node)) { + return [...this.evaluate(node.getWhenTrue(), env), ...this.evaluate(node.getWhenFalse(), env)] + } + if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) { + return [{ kind: "function", node, name: functionName(node) }] + } + if (Node.isFunctionDeclaration(node)) return [{ kind: "function", node, name: node.getName() ?? null }] + if (Node.isClassDeclaration(node) || Node.isClassExpression(node)) return [{ kind: "class", node }] + if (Node.isObjectLiteralExpression(node)) return [{ kind: "object", node }] + if (Node.isArrayLiteralExpression(node)) return [{ kind: "array", node }] + if (Node.isIdentifier(node)) return this.evaluateIdentifier(node, env) + if (node.getKind() === SyntaxKind.ThisKeyword) { + // `this` inside a class method: an instance of that class (static methods: the class) + const cls = node.getFirstAncestor((a) => Node.isClassDeclaration(a) || Node.isClassExpression(a)) + if (!cls) return [] + const method = node.getFirstAncestor((a) => Node.isMethodDeclaration(a) || Node.isPropertyDeclaration(a)) + const isStatic = !!method && (Node.isMethodDeclaration(method) || Node.isPropertyDeclaration(method)) && method.isStatic() + return [isStatic ? { kind: "class", node: cls } : { kind: "instance", classNode: cls }] + } + if (Node.isPropertyAccessExpression(node)) { + return this.member(this.evaluate(node.getExpression(), env), node.getName(), env) + } + if (Node.isElementAccessExpression(node)) { + const keys = this.evaluate(node.getArgumentExpression(), env).filter(isString) + const objects = this.evaluate(node.getExpression(), env) + return keys.flatMap((k) => this.member(objects, k.value, env)) + } + if (Node.isCallExpression(node)) return this.evaluateCall(node, env) + if (Node.isNewExpression(node)) { + return this.evaluate(node.getExpression(), env).flatMap((v): Value[] => { + if (v.kind === "class") return [{ kind: "instance", classNode: v.node }] + if (v.kind === "external" && (v.name === "express.Router" || v.name === "express")) { + return [this.newRouter(node, v.name === "express")] + } + return [] + }) + } + return [] + } + + private evaluateTemplate(node: Node, env: Env): Value[] { + if (!Node.isTemplateExpression(node)) return [] + let acc: Value[] = [{ kind: "string", value: node.getHead().getLiteralText() }] + for (const span of node.getTemplateSpans()) { + acc = concat(acc, this.evaluate(span.getExpression(), env)) + acc = concat(acc, [{ kind: "string", value: span.getLiteral().getLiteralText() }]) + } + return acc + } + + private evaluateIdentifier(node: Node, env: Env): Value[] { + const name = node.getText() + const binding = lookupName(node, name) + return binding ? this.evaluateBinding(binding, env) : [] + } + + evaluateBinding(binding: Binding, env: Env = EMPTY_ENV): Value[] { + switch (binding.kind) { + case "var": + return this.select(this.evaluate(binding.init, env), binding.path, env) + case "param": { + const bound = env.get(binding.param) ?? this.parameterValues(binding.param) + return this.select(bound, binding.path, env) + } + case "function": + return [{ kind: "function", node: binding.node, name: Node.isFunctionDeclaration(binding.node) ? binding.node.getName() ?? null : null }] + case "class": + return [{ kind: "class", node: binding.node }] + case "import": + return this.importValue(binding.file, binding.specifier, binding.imported) + } + } + + /** Follows a destructuring path (`const { a: { b } } = x`) into values. */ + private select(values: Value[], path: string[], env: Env): Value[] { + let current = values + for (const key of path) current = this.member(current, key, env) + return current + } + + /** `obj.key` for every value obj may have. */ + member(objects: Value[], key: string, env: Env = EMPTY_ENV): Value[] { + return objects.flatMap((obj): Value[] => { + switch (obj.kind) { + case "module": + return this.exportValue(obj.file, key) + case "external": + return [{ kind: "external", name: `${obj.name}.${key}` }] + case "externalCall": + return [obj] + case "object": + return this.objectProperty(obj.node, key, env) + case "array": { + if (!Node.isArrayLiteralExpression(obj.node)) return [] + const index = Number(key) + return Number.isInteger(index) ? this.evaluate(obj.node.getElements()[index], env) : [] + } + case "class": + return this.classMember(obj.node, key, true) + case "instance": + return this.classMember(obj.classNode, key, false) + default: + return [] + } + }) + } + + private objectProperty(node: Node, key: string, env: Env): Value[] { + if (!Node.isObjectLiteralExpression(node)) return [] + const out: Value[] = [] + for (const prop of node.getProperties()) { + if (Node.isPropertyAssignment(prop) && propName(prop.getNameNode()) === key) { + out.push(...this.evaluate(prop.getInitializer(), env)) + } else if (Node.isShorthandPropertyAssignment(prop) && prop.getName() === key) { + out.push(...this.evaluate(prop.getNameNode(), env)) + } else if (Node.isMethodDeclaration(prop) && prop.getName() === key) { + out.push({ kind: "function", node: prop, name: key }) + } else if (Node.isSpreadAssignment(prop)) { + out.push(...this.member(this.evaluate(prop.getExpression(), env), key, env)) + } + } + return out + } + + private classMember(classNode: Node, key: string, isStatic: boolean): Value[] { + if (!Node.isClassDeclaration(classNode) && !Node.isClassExpression(classNode)) return [] + for (const member of classNode.getMembers()) { + if (!Node.isMethodDeclaration(member) && !Node.isPropertyDeclaration(member)) continue + if (member.getName() !== key || member.isStatic() !== isStatic) continue + if (Node.isMethodDeclaration(member)) return [{ kind: "function", node: member, name: key }] + const init = member.getInitializer() + if (init) return this.evaluate(init) + const typed = this.instanceOfType(member.getTypeNode()) + if (typed.length > 0) return typed + } + if (isStatic) { + const base = this.baseClass(classNode) + return base ? this.classMember(base, key, true) : [] + } + // constructor parameter properties (`constructor(private users: UserService)`) + // and `this.users = new UserService()` / `this.users = users` in the constructor + for (const ctor of classNode.getConstructors()) { + for (const param of ctor.getParameters()) { + if (param.getName() === key && param.getScope() !== undefined) return this.instanceOfType(param.getTypeNode()) + if (param.getName() === key && param.isReadonly()) return this.instanceOfType(param.getTypeNode()) + } + for (const assign of ctor.getDescendantsOfKind(SyntaxKind.BinaryExpression)) { + const left = assign.getLeft() + if (assign.getOperatorToken().getKind() !== SyntaxKind.EqualsToken) continue + if (Node.isPropertyAccessExpression(left) && left.getExpression().getKind() === SyntaxKind.ThisKeyword && left.getName() === key) { + const right = this.evaluate(assign.getRight()) + if (right.length > 0) return right + const param = Node.isIdentifier(assign.getRight()) + ? ctor.getParameters().find((p) => p.getName() === assign.getRight().getText()) + : undefined + if (param) return this.instanceOfType(param.getTypeNode()) + } + } + } + const base = this.baseClass(classNode) + return base ? this.classMember(base, key, false) : [] + } + + /** An instance of the class a type annotation names (`users: UserService`), when it resolves to a project class. */ + private instanceOfType(typeNode: Node | undefined): Value[] { + if (!typeNode || !Node.isTypeReference(typeNode)) return [] + const name = typeNode.getTypeName() + if (!Node.isIdentifier(name)) return [] + return this.evaluate(name).flatMap((v): Value[] => v.kind === "class" ? [{ kind: "instance", classNode: v.node }] : []) + } + + private baseClass(classNode: Node): Node | null { + if (!Node.isClassDeclaration(classNode) && !Node.isClassExpression(classNode)) return null + const ext = classNode.getExtends() + if (!ext) return null + const base = this.evaluate(ext.getExpression()).find((v) => v.kind === "class") + return base && base.kind === "class" ? base.node : null + } + + // ------------------------------------------------------------------------- + // Calls + // ------------------------------------------------------------------------- + + private evaluateCall(node: CallExpression, env: Env): Value[] { + const callee = node.getExpression() + + // require("m") / require("m").x is handled through the property access above + if (Node.isIdentifier(callee) && callee.getText() === "require" && !lookupName(callee, "require")) { + const arg = node.getArguments()[0] + if (arg && (Node.isStringLiteral(arg) || Node.isNoSubstitutionTemplateLiteral(arg))) { + return this.requireValue(node.getSourceFile(), arg.getLiteralValue()) + } + return [] + } + + if (Node.isPropertyAccessExpression(callee)) { + const method = callee.getName() + const receivers = this.evaluate(callee.getExpression(), env) + const out: Value[] = [] + for (const r of receivers) { + if (r.kind === "router") { + if (method === "route") { + const paths = this.evaluate(node.getArguments()[0], env).filter(isString).map((s) => s.value) + out.push({ kind: "routeChain", router: r, paths }) + } else if (CHAINING_METHODS.has(method)) { + out.push(r) // app.use(...) / router.get(...) return the app / router + } + } else if (r.kind === "routeChain" && VERBS.has(method)) { + out.push(r) + } else if (r.kind === "externalCall") { + out.push(r) // body("email").isEmail().withMessage(...) + } else if (method === "bind" && r.kind === "function") { + out.push(r) // handler.bind(ctrl) + } + } + if (out.length > 0) return out + } + + return this.evaluate(callee, env).flatMap((fn): Value[] => { + if (fn.kind === "external") { + if (fn.name === "express") return [this.newRouter(node, true)] + if (fn.name === "express.Router" || fn.name === "express.default.Router") return [this.newRouter(node, false)] + return [{ kind: "externalCall", name: fn.name }] + } + if (fn.kind === "externalCall") return [fn] + if (fn.kind === "function") { + const returned = this.returnValues(fn.node) + // A wrapper — a function returning a closure of its own, called with a + // function (`catchAsync(async (req, res) => ...)`, `asyncHandler(ctrl.list)`) + // — stands for the function it wraps: that is the code that handles the request. + const returnsClosure = returned.some((v) => v.kind === "function" && isInside(v.node, fn.node)) + if (returnsClosure) { + const wrapped = node.getArguments().flatMap((a) => this.evaluate(a, env)).filter((v) => v.kind === "function") + if (wrapped.length > 0) return wrapped + } + return returned + } + return [] + }) + } + + private newRouter(node: Node, isApp: boolean): RouterValue { + const file = relativePath(node.getSourceFile()) + return { kind: "router", id: `${file}:${node.getStart()}`, isApp, file, line: node.getStartLineNumber() } + } + + /** What a function returns, for factory functions (`function createRouter() { const r = Router(); ...; return r }`). */ + private returnValues(fn: Node): Value[] { + if (Node.isArrowFunction(fn)) { + const body = fn.getBody() + if (!Node.isBlock(body)) return this.evaluate(body) + } + const out: Value[] = [] + for (const ret of fn.getDescendantsOfKind(SyntaxKind.ReturnStatement)) { + if (enclosingFunction(ret) !== fn) continue + out.push(...this.evaluate(ret.getExpression())) + } + return out + } + + // ------------------------------------------------------------------------- + // Parameters + // ------------------------------------------------------------------------- + + /** + * Values a parameter is bound to: the matching argument at every call site of + * its function (a registrar `function routes(app) {...}` called as + * `routes(app)`), or the elements of the array when the function is a + * `forEach` / `map` callback. + */ + parameterValues(param: ParameterDeclaration): Value[] { + const fn = param.getParent() as unknown as Node & { getParameters(): ParameterDeclaration[] } + const index = fn.getParameters().indexOf(param) + const out: Value[] = [] + + const parent = fn.getParent() + if (parent && Node.isCallExpression(parent) && parent.getArguments().includes(fn as Node)) { + const callee = parent.getExpression() + if (Node.isPropertyAccessExpression(callee) && ITERATORS.has(callee.getName()) && index === 0) { + for (const arr of this.evaluate(callee.getExpression())) { + if (arr.kind === "array" && Node.isArrayLiteralExpression(arr.node)) { + for (const el of arr.node.getElements()) out.push(...this.evaluate(el)) + } + } + return out + } + } + + for (const call of this.callSitesOf(fn)) { + const arg = call.getArguments()[index] + if (arg) out.push(...this.evaluate(arg)) + } + return out + } + + /** Every call in the project whose callee evaluates to `fn`. Built once, on first need. */ + private callSitesOf(fn: Node): CallExpression[] { + if (!this.callSites) { + this.callSites = new Map() + for (const file of this.ep.files.values()) { + for (const call of file.getDescendantsOfKind(SyntaxKind.CallExpression)) { + const callee = call.getExpression() + // only plain calls `f(x)` / `m.f(x)` / `require("./r")(x)` — not router methods, and not + // callees rooted in a parameter (`res.json`), whose values depend on this very index + if (Node.isPropertyAccessExpression(callee) && (VERBS.has(callee.getName()) || CHAINING_METHODS.has(callee.getName()))) continue + if (rootIsParameter(callee)) continue + for (const v of this.evaluate(callee)) { + if (v.kind !== "function") continue + const list = this.callSites.get(v.node) ?? [] + list.push(call) + this.callSites.set(v.node, list) + } + } + } + } + return this.callSites.get(fn) ?? [] + } + + // ------------------------------------------------------------------------- + // Modules + // ------------------------------------------------------------------------- + + /** The project file a relative specifier points to, or null for a package / unknown file. */ + resolveModule(from: SourceFile, specifier: string): SourceFile | null { + if (!specifier.startsWith(".")) return null + const base = relativePath(from).split("/").slice(0, -1) + for (const part of specifier.split("/")) { + if (part === "." || part === "") continue + if (part === "..") base.pop() + else base.push(part) + } + const target = base.join("/") + const stripped = target.replace(/\.(js|mjs|cjs)$/, "") // TS sources imported as "./x.js" + for (const candidate of [target, stripped]) { + for (const ext of MODULE_EXTENSIONS) { + const file = this.ep.files.get(candidate + ext) + if (file) return file + } + } + return null + } + + /** `require("m")`: module.exports when the file assigns it, else the module's named exports. */ + requireValue(from: SourceFile, specifier: string): Value[] { + const file = this.resolveModule(from, specifier) + if (!file) return specifier.startsWith(".") ? [] : [{ kind: "external", name: specifier }] + const cjs = this.moduleExportsAssignment(file) + if (cjs) return this.evaluate(cjs) + return [{ kind: "module", file }] + } + + private importValue(from: SourceFile, specifier: string, imported: string): Value[] { + const file = this.resolveModule(from, specifier) + if (!file) { + if (specifier.startsWith(".")) return [] + if (imported === "default" || imported === "*" || imported === "=") return [{ kind: "external", name: specifier }] + return [{ kind: "external", name: `${specifier}.${imported}` }] + } + if (imported === "*") return [{ kind: "module", file }] + if (imported === "=") return this.requireValue(from, specifier) + return this.exportValue(file, imported) + } + + /** A named export ("default" for the default export) of a project file, ES or CommonJS. */ + exportValue(file: SourceFile, name: string): Value[] { + const out: Value[] = [] + const cjs = this.moduleExportsAssignment(file) + for (const stmt of file.getStatements()) { + if (name === "default" && Node.isExportAssignment(stmt)) out.push(...this.evaluate(stmt.getExpression())) + if (Node.isFunctionDeclaration(stmt) || Node.isClassDeclaration(stmt)) { + const exported = stmt.isExported() && (name === "default" ? stmt.isDefaultExport() : stmt.getName() === name && !stmt.isDefaultExport()) + if (exported) out.push(...this.evaluate(stmt)) + } + if (Node.isVariableStatement(stmt) && stmt.isExported() && name !== "default") { + for (const decl of stmt.getDeclarations()) { + if (decl.getName() === name) out.push(...this.evaluate(decl.getInitializer())) + } + } + if (Node.isExportDeclaration(stmt)) { + const target = stmt.getModuleSpecifierValue() + for (const spec of stmt.getNamedExports()) { + const exportedAs = spec.getAliasNode()?.getText() ?? spec.getName() + if (exportedAs !== name) continue + if (target) { + const resolved = this.resolveModule(file, target) + if (resolved) out.push(...this.exportValue(resolved, spec.getName())) + } else { + const binding = lookupName(stmt, spec.getName()) + if (binding) out.push(...this.evaluateBinding(binding)) + } + } + if (target && stmt.isNamespaceExport() && name !== "default") { + const resolved = this.resolveModule(file, target) + if (resolved) out.push(...this.exportValue(resolved, name)) + } + } + // exports.name = x / module.exports.name = x + if (Node.isExpressionStatement(stmt)) { + const expr = stmt.getExpression() + if (Node.isBinaryExpression(expr) && expr.getOperatorToken().getKind() === SyntaxKind.EqualsToken) { + const left = expr.getLeft() + if (Node.isPropertyAccessExpression(left) && left.getName() === name && isExportsObject(left.getExpression())) { + out.push(...this.evaluate(expr.getRight())) + } + } + } + } + if (cjs) { + if (name === "default") out.push(...this.evaluate(cjs)) + else out.push(...this.member(this.evaluate(cjs), name)) + } + return out + } + + /** The right side of `module.exports = x` in a file, if any. */ + private moduleExportsAssignment(file: SourceFile): Node | null { + for (const stmt of file.getStatements()) { + if (!Node.isExpressionStatement(stmt)) continue + const expr = stmt.getExpression() + if (!Node.isBinaryExpression(expr) || expr.getOperatorToken().getKind() !== SyntaxKind.EqualsToken) continue + if (expr.getLeft().getText().replace(/\s/g, "") === "module.exports") return expr.getRight() + } + return null + } +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +export const VERBS = new Set(["get", "post", "put", "patch", "delete", "all", "options", "head"]) +/** Router methods that return the router itself, so calls can be chained. */ +const CHAINING_METHODS = new Set([...VERBS, "use", "param", "set", "enable", "disable", "engine"]) +const ITERATORS = new Set(["forEach", "map", "flatMap"]) + +export function isString(v: Value): v is Extract { + return v.kind === "string" +} + +function isExportsObject(node: Node): boolean { + const text = node.getText().replace(/\s/g, "") + return text === "exports" || text === "module.exports" +} + +function concat(left: Value[], right: Value[]): Value[] { + const out: Value[] = [] + for (const l of left) { + if (l.kind !== "string") continue + for (const r of right) { + if (r.kind === "string") out.push({ kind: "string", value: l.value + r.value }) + } + } + return out.slice(0, MAX_VALUES) +} + +function propName(node: Node): string | null { + if (Node.isIdentifier(node) || Node.isPrivateIdentifier(node)) return node.getText() + if (Node.isStringLiteral(node) || Node.isNumericLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) return node.getLiteralText() + return null +} + +function functionName(node: Node): string | null { + const parent = node.getParent() + if (parent && Node.isVariableDeclaration(parent)) return parent.getName() + if (parent && Node.isPropertyAssignment(parent)) return propName(parent.getNameNode()) + return null +} + +function isInside(node: Node, container: Node): boolean { + return node.getSourceFile() === container.getSourceFile() && + node.getStart() >= container.getStart() && node.getEnd() <= container.getEnd() && node !== container +} + +export function isFunctionNode(n: Node): boolean { + return Node.isFunctionLikeDeclaration(n) || Node.isArrowFunction(n) || Node.isFunctionExpression(n) +} + +export function enclosingFunction(node: Node): Node | undefined { + for (let p = node.getParent(); p; p = p.getParent()) { + if (isFunctionNode(p)) return p + } + return undefined +} + +/** True when an expression's leftmost identifier is a function parameter (`res.json`, `req.body.x`). */ +function rootIsParameter(node: Node): boolean { + let base: Node = node + while (Node.isPropertyAccessExpression(base) || Node.isElementAccessExpression(base) || Node.isCallExpression(base)) { + base = base.getExpression() + } + if (!Node.isIdentifier(base)) return false + return lookupName(base, base.getText())?.kind === "param" +} + +function valueKey(v: Value): string { + switch (v.kind) { + case "router": return `r:${v.id}` + case "routeChain": return `c:${v.router.id}:${v.paths.join("|")}` + case "function": return `f:${v.node.getSourceFile().getFilePath()}:${v.node.getStart()}` + case "class": return `k:${v.node.getSourceFile().getFilePath()}:${v.node.getStart()}` + case "instance": return `i:${v.classNode.getSourceFile().getFilePath()}:${v.classNode.getStart()}` + case "module": return `m:${v.file.getFilePath()}` + case "external": return `e:${v.name}` + case "externalCall": return `x:${v.name}` + case "object": return `o:${v.node.getSourceFile().getFilePath()}:${v.node.getStart()}` + case "array": return `a:${v.node.getSourceFile().getFilePath()}:${v.node.getStart()}` + case "string": return `s:${v.value}` + } +} + +function dedupe(values: Value[]): Value[] { + const seen = new Set() + return values.filter((v) => { + const k = valueKey(v) + if (seen.has(k)) return false + seen.add(k) + return true + }) +} diff --git a/packages/express-parser/src/graph.ts b/packages/express-parser/src/graph.ts new file mode 100644 index 0000000..d6d4d83 --- /dev/null +++ b/packages/express-parser/src/graph.ts @@ -0,0 +1,98 @@ +import { IR_NODE_TYPES, IR_EDGE_RELATIONS, IR_VERSION } from "@kidkender/archmind-protocol" +import type { IntermediateExecutionGraph, ExecutionNode, ExecutionEdge } from "@kidkender/archmind-protocol" +import type { ExpressRoute } from "./routes.js" +import { classifyMiddleware, type ClassifyOptions, type MiddlewareKind } from "./middleware.js" +import type { HandlerFacts } from "./handler.js" + +const ADAPTER_VERSION = "0.1.0" + +const NODE_FOR_KIND: Partial> = { + auth_gate: { type: IR_NODE_TYPES.AUTH_GATE, role: "authentication" }, + authz_check: { type: IR_NODE_TYPES.AUTHZ_CHECK, role: "authorization" }, + validation_gate: { type: IR_NODE_TYPES.VALIDATION_GATE, role: "validation" }, + // no IR node type for these: kept visible as unknown middleware with their role + rate_limit: { type: IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, role: "rate_limiting" }, + optional_auth: { type: IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, role: "optional_authentication" }, + csrf: { type: IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, role: "csrf" }, + unknown: { type: IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, role: "middleware" }, + // infrastructure and error handlers get no node +} + +/** + * One graph per route: its middleware in execution order, then the handler, + * linked by `precedes`. Middleware is classified (classifyMiddleware); + * infrastructure such as body parsers, logging and CORS is left out. + */ +export function routeToGraph(route: ExpressRoute, opts: ClassifyOptions = {}, facts?: HandlerFacts): IntermediateExecutionGraph { + const nodes: ExecutionNode[] = [] + for (const mw of route.middleware) { + const kinds = classifyMiddleware(mw, opts).kinds + // `auth("manageUsers")` is one check in two parts: the roles belong to the + // authorization node only, or the permission reads as checked twice + const split = kinds.includes("auth_gate") && kinds.includes("authz_check") + for (const kind of kinds) { + const spec = NODE_FOR_KIND[kind] + if (!spec) continue + const withArgs = mw.args.length > 0 && !(split && kind === "auth_gate") + nodes.push({ + id: `mw_${nodes.length}`, + type: spec.type, + symbol: shorten(mw.text), + file: mw.file, + line: mw.line, + ...(withArgs ? { args: mw.args } : {}), + role: spec.role, + }) + } + } + nodes.push({ + id: "handler", + type: IR_NODE_TYPES.BUSINESS_HANDLER, + symbol: route.handler.symbol, + file: route.handler.file, + line: route.handler.line, + role: "handler", + }) + + // Ownership and the transaction happen inside the handler (or a service it + // calls), so like the Go adapter they follow the handler in the chain. + if (facts?.ownership) { + nodes.push({ id: "ownership", type: IR_NODE_TYPES.AUTHZ_CHECK, ...facts.ownership, role: "authorization" }) + } + const txn = facts?.transactions[0] + if (txn) nodes.push({ id: "txn", type: IR_NODE_TYPES.TXN_BOUNDARY, symbol: txn.symbol, file: txn.file, line: txn.line, role: "transaction" }) + + const edges: ExecutionEdge[] = [] + for (let i = 0; i < nodes.length - 1; i++) { + edges.push({ from: nodes[i].id, to: nodes[i + 1].id, relation: IR_EDGE_RELATIONS.PRECEDES, traceability: "static" }) + } + + // Writes inside the transaction hang off it, as Laravel's and NestJS's do. + for (const [i, w] of (txn?.writes ?? []).entries()) { + nodes.push({ id: `txn_write_${i}`, type: IR_NODE_TYPES.TXN_WRITE, symbol: w.symbol, file: w.file, line: w.line, role: "persistence", mutates: true }) + edges.push({ from: "txn", to: `txn_write_${i}`, relation: IR_EDGE_RELATIONS.WRAPS, traceability: "static" }) + } + + // Services the handler calls hang off it, outside the chain. + for (const [i, svc] of (facts?.services ?? []).entries()) { + nodes.push({ id: `svc_${i}`, type: IR_NODE_TYPES.SERVICE_CALL, ...svc, role: "service" }) + edges.push({ from: "handler", to: `svc_${i}`, relation: IR_EDGE_RELATIONS.CALLS, traceability: "static" }) + } + + return { + entrypoint: `${route.method} ${route.path}`, + method: route.method, + path: route.path, + nodes, + edges, + annotations: [], + framework: "express", + ir_ver: IR_VERSION, + adapter_ver: ADAPTER_VERSION, + } +} + +/** Inline middleware can be long: keep the first line, at most 100 characters. */ +function shorten(text: string): string { + return text.length > 100 ? `${text.slice(0, 97)}...` : text +} diff --git a/packages/express-parser/src/handler.ts b/packages/express-parser/src/handler.ts new file mode 100644 index 0000000..af9da8b --- /dev/null +++ b/packages/express-parser/src/handler.ts @@ -0,0 +1,264 @@ +import { Node, SyntaxKind, type CallExpression } from "ts-morph" +import { Evaluator, isFunctionNode, type Value } from "./evaluator.js" +import { relativePath } from "./project.js" +import type { ExpressRoute } from "./routes.js" + +export interface CodeRef { + symbol: string + file: string + line: number +} + +/** A write to the database made inside a transaction, `Entity::operation`. */ +export interface TxnWrite extends CodeRef { + entity: string + operation: string +} + +export interface TransactionRef extends CodeRef { + writes: TxnWrite[] +} + +export interface HandlerFacts { + /** Project functions the handler calls (services, repositories, helpers in other modules). */ + services: CodeRef[] + /** Transaction boundaries in the handler, or in a service it calls (one hop). */ + transactions: TransactionRef[] + /** The first call to a configured ownership source (archmind.json authorization.ownershipSources). */ + ownership: CodeRef | null +} + +export interface HandlerOptions { + ownershipSources?: string[] +} + +/** Service calls kept per route, so a long handler cannot flood the graph. */ +const MAX_SERVICES = 15 + +/** Methods that open a transaction whatever they are called on. */ +const TXN_METHODS = new Set(["$transaction", "withTransaction", "startTransaction"]) +/** `x.transaction(...)` counts when x is a database handle by name ... */ +const DB_RECEIVER = /^(sequelize|db|database|prisma|datasource|appdatasource|connection|conn|manager|entitymanager|em|knex|orm|trx|pool|client|mongoose|session|queryrunner|getmanager\(\)|getconnection\(\))$/i +/** ... or comes from an ORM package. */ +const ORM_PACKAGES = ["sequelize", "typeorm", "knex", "mongoose", "@prisma/client", "objection", "@mikro-orm/core", "drizzle-orm"] + +export function analyzeHandler(route: ExpressRoute, ev: Evaluator, opts: HandlerOptions = {}): HandlerFacts { + const facts: HandlerFacts = { services: [], transactions: [], ownership: null } + const handler = route.handler.node + if (!handler || !isFunctionNode(handler)) return facts + + const owners = new Set(opts.ownershipSources ?? []) + const params = new Set(parameterNames(handler)) + // every project function the handler calls; only service-like ones become nodes, + // but transactions and ownership are looked for in all of them (a helper in the + // route file that wraps its writes in a transaction counts) + const calledFns: Node[] = [] + const seenFns = new Set() + + for (const call of callsIn(handler)) { + const callee = call.getExpression() + if (rootName(callee) && params.has(rootName(callee)!)) continue // req.*, res.*, next() + + if (!facts.ownership && owners.has(lastName(callee))) facts.ownership = ref(`ownership:${lastName(callee)}`, call) + const txn = transactionCall(call, ev) + if (txn) facts.transactions.push(txn) + + for (const fn of projectFunctions(ev.evaluate(callee))) { + if (fn === handler || isWithin(fn, handler) || seenFns.has(fn)) continue + seenFns.add(fn) + calledFns.push(fn) + if (isServiceTarget(callee, fn, handler) && facts.services.length < MAX_SERVICES) { + facts.services.push({ symbol: serviceSymbol(callee), file: relativePath(fn.getSourceFile()), line: fn.getStartLineNumber() }) + } + } + } + + // one hop: transactions and ownership inside the functions the handler calls + for (const fn of calledFns) { + for (const call of callsIn(fn)) { + const txn = transactionCall(call, ev) + if (txn) facts.transactions.push(txn) + const callee = call.getExpression() + if (!facts.ownership && owners.has(lastName(callee))) facts.ownership = ref(`ownership:${lastName(callee)}`, call) + } + } + return facts +} + +/** Calls in a function's body, including in callbacks written inside it. */ +function callsIn(fn: Node): CallExpression[] { + return fn.getDescendantsOfKind(SyntaxKind.CallExpression) +} + +function transactionCall(call: CallExpression, ev: Evaluator): TransactionRef | null { + const callee = call.getExpression() + if (!Node.isPropertyAccessExpression(callee)) return null + const method = callee.getName() + let isTxn = TXN_METHODS.has(method) + if (!isTxn && method === "transaction") { + const receiver = callee.getExpression() + const tail = receiver.getText().replace(/\s/g, "").split(".").pop() ?? "" + isTxn = DB_RECEIVER.test(tail) || ev.evaluate(receiver).some((v) => + (v.kind === "external" || v.kind === "externalCall") && + ORM_PACKAGES.some((pkg) => v.name === pkg || v.name.startsWith(`${pkg}.`))) + } + if (!isTxn) return null + return { ...ref(calleeSymbol(callee), call), writes: transactionWrites(call) } +} + +// --------------------------------------------------------------------------- +// Writes inside a transaction +// --------------------------------------------------------------------------- + +const WRITE_METHODS = new Set([ + "save", "insert", "update", "delete", "remove", "upsert", "softDelete", "recover", + "create", "createMany", "bulkCreate", "destroy", "updateMany", "deleteMany", "insertMany", + "updateOne", "deleteOne", "findOneAndUpdate", "findByIdAndUpdate", "findOneAndDelete", "increment", "decrement", +]) +/** An options argument that ties a write to an unmanaged transaction or a Mongo session. */ +const TXN_OPTION = /\btransaction\s*[:,}]|\{\s*session\b|\bsession\s*:/ + +/** + * Writes made inside the transaction: in its callback (`dataSource.transaction( + * async (manager) => manager.save(Order, dto))`, `prisma.$transaction(async (tx) + * => tx.order.create(...))`), in its array form (`prisma.$transaction([ + * prisma.order.create(...)])`), or — for an unmanaged transaction + * (`const t = await sequelize.transaction()`) — calls in the same function that + * pass it (`Order.create(data, { transaction: t })`). + */ +function transactionWrites(txnCall: CallExpression): TxnWrite[] { + const scopes: Node[] = [] + for (const arg of txnCall.getArguments()) { + if (isFunctionNode(arg) || Node.isArrayLiteralExpression(arg)) scopes.push(arg) + } + const out: TxnWrite[] = [] + const seen = new Set() + const visit = (call: CallExpression, requireOption: boolean) => { + if (seen.has(call)) return + const w = writeOf(call) + if (!w) return + if (requireOption && !call.getArguments().some((a) => TXN_OPTION.test(a.getText()))) return + seen.add(call) + out.push(w) + } + for (const scope of scopes) { + if (Node.isCallExpression(scope)) visit(scope, false) + for (const call of scope.getDescendantsOfKind(SyntaxKind.CallExpression)) visit(call, false) + } + if (scopes.length === 0) { + const fn = txnCall.getFirstAncestor((a) => isFunctionNode(a)) + for (const call of fn?.getDescendantsOfKind(SyntaxKind.CallExpression) ?? []) visit(call, true) + } + return out +} + +/** `manager.save(Order, dto)` → Order::save; `Order.create(...)` → Order::create; `tx.order.create(...)` → Order::create. */ +function writeOf(call: CallExpression): TxnWrite | null { + const callee = call.getExpression() + if (!Node.isPropertyAccessExpression(callee)) return null + const operation = callee.getName() + if (!WRITE_METHODS.has(operation)) return null + const receiver = callee.getExpression() + const entity = entityFromArgument(call.getArguments()[0]) ?? entityFromReceiver(receiver) + if (!entity) return null + return { entity, operation, symbol: `${entity}::${operation}`, file: relativePath(call.getSourceFile()), line: call.getStartLineNumber() } +} + +/** TypeORM's EntityManager takes the entity first: `save(Order, dto)`, `save(new Order(...))`. */ +function entityFromArgument(arg: Node | undefined): string | null { + if (!arg) return null + if (Node.isIdentifier(arg) && /^[A-Z]/.test(arg.getText())) return arg.getText() + if (Node.isNewExpression(arg)) { + const name = arg.getExpression().getText() + return /^[A-Z]/.test(name) ? name : null + } + return null +} + +function entityFromReceiver(receiver: Node): string | null { + // Order.create(...) / Order.update(...) + if (Node.isIdentifier(receiver)) { + const name = receiver.getText() + if (/^[A-Z]/.test(name)) return name + // order.save(...) on an instance: the variable names the entity + return /^(res|req|next|manager|tx|trx|em|session|t|db|prisma)$/.test(name) ? null : capitalize(name) + } + // tx.order.create(...) / prisma.order.create(...) + if (Node.isPropertyAccessExpression(receiver)) { + const name = receiver.getName() + if (/^(res|req|body|query|params)$/.test(name)) return null + return capitalize(name) + } + // manager.getRepository(Order).save(...) + if (Node.isCallExpression(receiver)) return entityFromArgument(receiver.getArguments()[0]) + return null +} + +function capitalize(s: string): string { + return s.charAt(0).toUpperCase() + s.slice(1) +} + +/** Where services live: a file or folder named for the layer. */ +const SERVICE_PATH = /(service|repositor|repo\b|dao|store|provider|manager|usecase|use-case|model|entit|domain|gateway|client)/i +/** Where helpers live: response formatters, pickers, id generators. */ +const UTILITY_PATH = /(^|\/)(utils?|helpers?|lib\/utils|common\/utils|shared\/utils)(\/|\.|$)/i + +/** + * Whether a called project function counts as a service call: it lives in a + * service-like file, or is a method reached through a module, object or + * instance (`userService.create`, `emailProvider.send`) — but not a utility + * module, and not a helper in the handler's own file. + */ +function isServiceTarget(callee: Node, fn: Node, handler: Node): boolean { + const path = relativePath(fn.getSourceFile()) + if (UTILITY_PATH.test(path)) return false + if (SERVICE_PATH.test(path)) return true + if (fn.getSourceFile() === handler.getSourceFile()) return false + return Node.isPropertyAccessExpression(callee) +} + +/** Functions defined in the project (not packages) among a callee's values. */ +function projectFunctions(values: Value[]): Node[] { + return values.flatMap((v) => (v.kind === "function" ? [v.node] : [])) +} + +function ref(symbol: string, node: Node): CodeRef { + return { symbol, file: relativePath(node.getSourceFile()), line: node.getStartLineNumber() } +} + +function calleeSymbol(callee: Node): string { + return callee.getText().replace(/\s+/g, "").replace(/^this\./, "") +} + +/** + * `userService.createUser` → "userService::createUser", the Owner::method form + * the other adapters use, so dependents can be looked up by owner name. + */ +function serviceSymbol(callee: Node): string { + const text = calleeSymbol(callee) + const dot = text.lastIndexOf(".") + return dot > 0 && Node.isPropertyAccessExpression(callee) ? `${text.slice(0, dot)}::${text.slice(dot + 1)}` : text +} + +function lastName(callee: Node): string { + if (Node.isPropertyAccessExpression(callee)) return callee.getName() + return callee.getText() +} + +function rootName(callee: Node): string | null { + let base: Node = callee + while (Node.isPropertyAccessExpression(base) || Node.isElementAccessExpression(base) || Node.isCallExpression(base)) { + base = base.getExpression() + } + return Node.isIdentifier(base) ? base.getText() : null +} + +function parameterNames(fn: Node): string[] { + const params = (fn as unknown as { getParameters?: () => { getName(): string }[] }).getParameters?.() ?? [] + return params.map((p) => p.getName()) +} + +function isWithin(node: Node, container: Node): boolean { + return node.getSourceFile() === container.getSourceFile() && + node.getStart() >= container.getStart() && node.getEnd() <= container.getEnd() +} diff --git a/packages/express-parser/src/index.ts b/packages/express-parser/src/index.ts new file mode 100644 index 0000000..b18f0c5 --- /dev/null +++ b/packages/express-parser/src/index.ts @@ -0,0 +1,6 @@ +export { parseExpressSources, parseExpressProjectAt, ExpressAdapter, type ParseExpressOptions } from "./adapter.js" +export { isExpressProject, findExpressRoot } from "./detect.js" +export { findSourceFiles, readSourceFiles, type SourceFile } from "./scanner.js" +export { extractRoutes, type ExpressRoute, type ChainEntry, type HandlerRef, type ExtractResult } from "./routes.js" +export { createExpressProject } from "./project.js" +export { classifyMiddleware, type Classification, type MiddlewareKind, type ClassifyOptions } from "./middleware.js" diff --git a/packages/express-parser/src/middleware.ts b/packages/express-parser/src/middleware.ts new file mode 100644 index 0000000..5c53157 --- /dev/null +++ b/packages/express-parser/src/middleware.ts @@ -0,0 +1,272 @@ +import { Node } from "ts-morph" +import type { ChainEntry } from "./routes.js" +import type { Value } from "./evaluator.js" + +/** + * What a middleware does, as far as the IR is concerned. + * - auth_gate / authz_check / validation_gate: a security control, with the + * matching IR node (an auth factory called with roles or permissions — + * `auth("manageUsers")`, `authorize(ADMIN)` — is both an auth gate and an + * authorization check). + * - rate_limit / optional_auth / csrf: a control the IR has no node type for; + * emitted as ir:unknown_middleware with that role. + * - unknown: not recognised; ir:unknown_middleware, an honest "don't know". + * - infrastructure / error_handler: body parsing, logging, CORS, static files, + * `(err, req, res, next)` handlers — left out of the graph. + */ +export type MiddlewareKind = + | "auth_gate" | "authz_check" | "validation_gate" + | "rate_limit" | "optional_auth" | "csrf" | "unknown" + | "infrastructure" | "error_handler" + +export interface Classification { + kinds: MiddlewareKind[] + /** How it was decided, for diagnostics: "config", "package:express-jwt", "name", "body". */ + source: string +} + +export interface ClassifyOptions { + authGates?: string[] + authzChecks?: string[] +} + +// --------------------------------------------------------------------------- +// Packages (matched on the npm name behind a value, the most precise signal) +// --------------------------------------------------------------------------- + +const PACKAGE_KINDS: [string, MiddlewareKind][] = [ + // authentication + ["passport.authenticate", "auth_gate"], + ["passport.authorize", "auth_gate"], + ["express-jwt", "auth_gate"], + ["express-oauth2-jwt-bearer", "auth_gate"], + ["express-openid-connect.requiresAuth", "auth_gate"], + ["express-basic-auth", "auth_gate"], + ["@clerk/express.requireAuth", "auth_gate"], + ["keycloak-connect", "auth_gate"], + // authorization + ["express-jwt-authz", "authz_check"], + ["express-jwt-permissions", "authz_check"], + // validation + ["celebrate", "validation_gate"], + ["express-validator", "validation_gate"], + ["express-validation", "validation_gate"], + ["express-joi-validation", "validation_gate"], + ["express-openapi-validator", "validation_gate"], + ["zod-express-middleware", "validation_gate"], + ["express-zod-safe", "validation_gate"], + // rate limiting / CSRF + ["express-rate-limit", "rate_limit"], + ["express-slow-down", "rate_limit"], + ["rate-limiter-flexible", "rate_limit"], + ["express-brute", "rate_limit"], + ["csurf", "csrf"], + ["lusca.csrf", "csrf"], + // infrastructure + ["express.json", "infrastructure"], ["express.urlencoded", "infrastructure"], ["express.raw", "infrastructure"], + ["express.text", "infrastructure"], ["express.static", "infrastructure"], + ["passport.initialize", "infrastructure"], ["passport.session", "infrastructure"], + ["body-parser", "infrastructure"], ["cookie-parser", "infrastructure"], ["express-session", "infrastructure"], + ["helmet", "infrastructure"], ["cors", "infrastructure"], ["compression", "infrastructure"], + ["morgan", "infrastructure"], ["pino-http", "infrastructure"], ["express-winston", "infrastructure"], + ["method-override", "infrastructure"], ["express-mongo-sanitize", "infrastructure"], ["xss-clean", "infrastructure"], + ["hpp", "infrastructure"], ["lusca", "infrastructure"], ["connect-flash", "infrastructure"], + ["serve-favicon", "infrastructure"], ["response-time", "infrastructure"], ["connect-timeout", "infrastructure"], + ["swagger-ui-express", "infrastructure"], ["multer", "infrastructure"], + ["express-ejs-layouts", "infrastructure"], ["express-status-monitor", "infrastructure"], ["nocache", "infrastructure"], + ["cookie-session", "infrastructure"], +] + +/** + * `expressValidator()` — the default export of express-validator before v6 — + * only installs `req.checkBody()` and friends on every request; the validation + * itself happens in the handler. Its members (`body()`, `check()`, ...) are the + * per-route validation. + */ +const INSTALLERS = new Set(["express-validator"]) + +function packageKind(values: Value[]): { kind: MiddlewareKind; pkg: string } | null { + for (const v of values) { + if (v.kind !== "external" && v.kind !== "externalCall") continue + if (v.kind === "externalCall" && INSTALLERS.has(v.name)) return { kind: "infrastructure", pkg: v.name } + // longest matching prefix: "lusca.csrf" before "lusca", "passport.authenticate" before nothing + let best: [string, MiddlewareKind] | null = null + for (const entry of PACKAGE_KINDS) { + const [pkg] = entry + if ((v.name === pkg || v.name.startsWith(`${pkg}.`)) && (!best || pkg.length > best[0].length)) best = entry + } + if (best) return { kind: best[1], pkg: best[0] } + } + return null +} + +// --------------------------------------------------------------------------- +// Names (the last identifier of the reference or callee) +// --------------------------------------------------------------------------- + +/** Auth factories: called with roles or permissions they are also an authorization check. */ +const AUTH_FACTORY = /^(auth|authenticate|authorize|authorise|protect|requireAuth)$/i + +const AUTHZ_NAME = new RegExp( + "^(" + [ + "authori[sz]e", "isAuthorized", "permit", "can", "guard", + "(check|require|has|ensure|verify|restrict|allow|only|is)?(Any)?(Roles?|Permissions?|Admin|Scopes?|Owner|Ownership|Privileges?|Rights?|Access)(Middleware|Guard|Auth|Only|Check|Required)?", + "(admin|role|roles|owner|permission)(Middleware|Guard|Auth|Only|Check)", + // isAdminUser, isSuperUser, requireStaff, onlyModerator, isOwnerOrAdmin + "(is|has|require|ensure|check|only)(Admin|Super|SuperUser|SuperAdmin|Staff|Moderator|Manager|Owner|Root)\\w*", + "restrictTo", "grantAccess", + ].join("|") + ")$", + "i", +) + +const AUTH_NAME = new RegExp( + "^(" + [ + "auth", "authenticate[d]?", "protect(ed)?", "withAuth", "loggedIn", + "(require|requires|ensure|verify|check|validate|is|has)?(Auth|Authentication|Authenticated|Jwt|Token|Login|LoggedIn|SignedIn|Signin|Session|User|ApiKey)(Middleware|Guard|Handler)?", + "(auth|jwt|token|apiKey|bearer)(Middleware|Guard|Handler|Check|Required)", + "authenticate(Token|Jwt|User|Request)", + // verifyAuthToken, checkAccessToken, validateJwtToken, requireApiKey + "(verify|check|validate|require|ensure|authenticate)(Auth|Access|Bearer|Id|Api|Jwt|User)?(Token|Jwt|JWT|Key|ApiKey|Session)", + ].join("|") + ")$", + "i", +) + +const VALIDATION_NAME = /^(validate\w*|validator|validation|\w*Validat(e|or|ion)|schemaValidator|celebrate|checkSchema|zodValidate)$/i +const RATE_LIMIT_NAME = /(limit(er)?|throttle|slowDown|brute(force)?)$/i + +const INFRASTRUCTURE_NAMES = new Set([ + "json", "urlencoded", "raw", "text", "static", "helmet", "cors", "compression", "compress", + "morgan", "logger", "morganLogger", "requestLogger", "httpLogger", "pinoHttp", "successHandler", "errorHandler", + "cookieParser", "session", "methodOverride", "xss", "xssClean", "mongoSanitize", "hpp", "initialize", "flash", + "serve", "favicon", "responseTime", "timeout", "xframe", "xssProtection", "nosniff", "hsts", +]) + +// --------------------------------------------------------------------------- +// Bodies (project-defined middleware the name does not give away) +// --------------------------------------------------------------------------- + +const BODY_AUTH = new RegExp([ + "\\b(jwt|jsonwebtoken)\\.verify\\s*\\(", + "\\bverify(Token|Jwt|JWT|IdToken|AccessToken)\\s*\\(", + "passport\\.authenticate\\s*\\(", + "\\.isAuthenticated\\s*\\(\\s*\\)", + "headers\\.authorization", + "headers\\[\\s*['\"`](authorization|x-token|x-access-token|x-api-key|x-auth-token)['\"`]\\s*\\]", + "\\.get\\(\\s*['\"`](authorization|x-api-key)['\"`]\\s*\\)", + // const { authorization } = req.headers + "\\{[^}]*\\bauthorization\\b[^}]*\\}\\s*=\\s*\\w+\\.headers", + "['\"`]Bearer\\s", +].join("|"), "i") + +// a role / permission read off the user or token, not any word like "scope" (`User.scope("withSecrets")` is an ORM call) +const BODY_ROLE = /\.(role|roles|isAdmin|admin|permissions?|rights|scopes|privileges?)\b|\b(roles|isAdmin|hasRole|hasAnyRole|hasPermission|permissions|requiredRights)\b|\.(is|has)(Super|Admin|Staff|Owner|Moderator|Manager|Root)\w*/ +const BODY_DENY = /\b40[13]\b|forbidden|unauthori[sz]ed/i + +const BODY_CSRF = /csrf/i +/** Ways a middleware ends the request instead of passing it on. */ +const BODY_STOPS = /\bres\.(status|sendStatus|send|json|end|redirect|render|sendFile)\s*\(|\bthrow\b|\bnext\s*\(\s*[^)\s]/ + +/** + * A middleware whose last top-level statement is a plain `next()` lets the + * request through whatever happened above it: reading a token there makes it + * optional authentication, not a gate (calling it a gate would hide routes that + * are really open). + */ +function endsWithUnconditionalNext(fn: Node): boolean { + const body = (fn as unknown as { getBody?: () => Node | undefined }).getBody?.() + if (!body || !Node.isBlock(body)) return false + const statements = body.getStatements() + const last = statements.at(-1) + if (!last || !/^(return\s+)?(await\s+)?next\s*\(\s*\)\s*;?$/.test(last.getText().trim())) return false + // `if (!token) return res.status(401).end()` at the top level still blocks a request without a token + return !statements.some(isTopLevelExit) +} + +/** A top-level statement that ends the request: an unconditional stop, or an `if` whose branch stops directly. */ +function isTopLevelExit(stmt: Node): boolean { + if (Node.isThrowStatement(stmt)) return true + if (Node.isExpressionStatement(stmt) || Node.isReturnStatement(stmt)) return BODY_STOPS_CALL.test(stmt.getText()) + if (Node.isIfStatement(stmt)) { + for (const branch of [stmt.getThenStatement(), stmt.getElseStatement()]) { + if (!branch) continue + const direct = Node.isBlock(branch) ? branch.getStatements() : [branch] + if (direct.some((s) => Node.isThrowStatement(s) || ((Node.isReturnStatement(s) || Node.isExpressionStatement(s)) && BODY_STOPS_CALL.test(s.getText())))) { + return true + } + } + } + return false +} + +const BODY_STOPS_CALL = /\bres\.(status|sendStatus|send|json|end|redirect|render)\s*\(|\bnext\s*\(\s*[^)\s]/ + +function bodyKinds(fn: Node): MiddlewareKind[] { + const text = fn.getText() + const kinds: MiddlewareKind[] = [] + if (BODY_AUTH.test(text)) { + if (endsWithUnconditionalNext(fn)) return ["optional_auth"] + kinds.push("auth_gate") + } + if (BODY_ROLE.test(text) && BODY_DENY.test(text)) kinds.push("authz_check") + if (kinds.length > 0) return kinds + if (BODY_CSRF.test(text)) return ["csrf"] + // never stops a request (sets res.locals, remembers a URL, then next()): not a control + if (!BODY_STOPS.test(text)) return ["infrastructure"] + return [] +} + +// --------------------------------------------------------------------------- + +export function classifyMiddleware(entry: ChainEntry, opts: ClassifyOptions = {}): Classification { + const callee = calleeText(entry.node) + + // archmind.json guards: the project knows best + const configured = (list?: string[]) => !!list && (list.includes(entry.name) || list.includes(callee)) + if (configured(opts.authzChecks)) return { kinds: ["authz_check"], source: "config" } + if (configured(opts.authGates)) return { kinds: ["auth_gate"], source: "config" } + + const fn = functionOf(entry.values) + if (fn && isErrorHandler(fn)) return { kinds: ["error_handler"], source: "signature" } + + // `auth.optional` / jwt({ credentialsRequired: false }): resolves the user if present, blocks nothing + if (/\boptional$/i.test(callee) || /credentialsRequired\s*:\s*false/.test(entry.node.getText())) { + return { kinds: ["optional_auth"], source: "name" } + } + + const pkg = packageKind(entry.values) + if (pkg) return { kinds: [pkg.kind], source: `package:${pkg.pkg}` } + + const name = entry.name + const hasArgs = entry.args.length > 0 + if (/\bauth\w*\.required$/i.test(callee)) return { kinds: ["auth_gate"], source: "name" } + if (AUTH_FACTORY.test(name)) { + return { kinds: hasArgs ? ["auth_gate", "authz_check"] : ["auth_gate"], source: "name" } + } + if (AUTHZ_NAME.test(name)) return { kinds: ["authz_check"], source: "name" } + if (AUTH_NAME.test(name)) return { kinds: ["auth_gate"], source: "name" } + if (VALIDATION_NAME.test(name)) return { kinds: ["validation_gate"], source: "name" } + if (RATE_LIMIT_NAME.test(name)) return { kinds: ["rate_limit"], source: "name" } + if (INFRASTRUCTURE_NAMES.has(name)) return { kinds: ["infrastructure"], source: "name" } + + if (fn) { + const kinds = bodyKinds(fn) + if (kinds.length > 0) return { kinds, source: "body" } + } + return { kinds: ["unknown"], source: "none" } +} + +function calleeText(node: Node): string { + const target = Node.isCallExpression(node) ? node.getExpression() : node + return target.getText().replace(/\s+/g, "") +} + +function functionOf(values: Value[]): Node | null { + const fn = values.find((v) => v.kind === "function") + return fn && fn.kind === "function" ? fn.node : null +} + +/** Express runs a 4-parameter function only for errors: `(err, req, res, next)`. */ +function isErrorHandler(fn: Node): boolean { + const params = (fn as unknown as { getParameters?: () => unknown[] }).getParameters?.() + return !!params && params.length === 4 +} diff --git a/packages/express-parser/src/project.ts b/packages/express-parser/src/project.ts new file mode 100644 index 0000000..042ddb2 --- /dev/null +++ b/packages/express-parser/src/project.ts @@ -0,0 +1,35 @@ +import { Project, ScriptKind, type SourceFile as TsSourceFile } from "ts-morph" +import type { SourceFile } from "./scanner.js" + +/** + * An in-memory ts-morph project over the given files. Paths stay relative to the + * project root (mounted at "/"), so node file/line come out project-relative. + * Module resolution between files is done by the extractors themselves, not + * by the TypeScript checker: JavaScript `require()` and + * re-exports need the same handling as ES imports, and no tsconfig is read. + */ +export interface ExpressProject { + project: Project + /** Project-relative path ("src/app.js") → source file. */ + files: Map +} + +export function createExpressProject(sources: SourceFile[]): ExpressProject { + const project = new Project({ + useInMemoryFileSystem: true, + skipAddingFilesFromTsConfig: true, + skipFileDependencyResolution: true, + compilerOptions: { allowJs: true, checkJs: false, noEmit: true, skipLibCheck: true, strict: false }, + }) + const files = new Map() + for (const source of sources) { + const scriptKind = /\.[cm]?ts$/.test(source.path) ? ScriptKind.TS : ScriptKind.JS + files.set(source.path, project.createSourceFile(`/${source.path}`, source.content, { scriptKind, overwrite: true })) + } + return { project, files } +} + +/** The project-relative path of a source file created by createExpressProject. */ +export function relativePath(file: TsSourceFile): string { + return file.getFilePath().replace(/^\//, "") +} diff --git a/packages/express-parser/src/routes.ts b/packages/express-parser/src/routes.ts new file mode 100644 index 0000000..0178962 --- /dev/null +++ b/packages/express-parser/src/routes.ts @@ -0,0 +1,377 @@ +import { Node, SyntaxKind, type CallExpression, type ParameterDeclaration } from "ts-morph" +import { Evaluator, VERBS, isString, isFunctionNode, enclosingFunction, type Value, type RouterValue, type Env } from "./evaluator.js" +import { relativePath, type ExpressProject } from "./project.js" + +/** A middleware or handler argument as written at a registration site. */ +export interface ChainEntry { + /** Source text, e.g. "auth('manageUsers')", "checkJwt", "userController.createUser". */ + text: string + /** Last identifier of the callee or reference, e.g. "auth", "checkJwt", "createUser". */ + name: string + /** Call arguments as written, e.g. ["'manageUsers'"]. */ + args: string[] + /** What the argument evaluates to (functions, externals, ...). */ + values: Value[] + /** + * For a call that stands for a function it wraps (`catchAsync(ctrl.list)`, + * `ctrl.list.bind(ctrl)`): the wrapped argument's text, "" for a + * function written in place. Undefined otherwise. + */ + wrapped?: string + node: Node + file: string + line: number +} + +export interface HandlerRef { + /** "userController.createUser", or "" for a function written at the route. */ + symbol: string + /** Where the handler function is defined, when it was resolved; else the route registration. */ + file: string + line: number + /** The handler function, when resolved. */ + node: Node | null +} + +export interface ExpressRoute { + method: string + path: string + /** Where the route is registered. */ + file: string + line: number + /** Middleware in execution order: app/router `use` first, then the route's own. */ + middleware: ChainEntry[] + handler: HandlerRef +} + +export interface ExtractResult { + routes: ExpressRoute[] + /** Registration sites on a known router whose path could not be resolved to a string. */ + unresolvedPaths: { file: string; line: number; text: string }[] +} + +interface RouteRegistration { + kind: "route" + router: RouterValue + method: string + paths: string[] + entries: ChainEntry[] + site: Node +} + +interface UseRegistration { + kind: "use" + router: RouterValue + prefixes: string[] + /** In argument order: middleware entries and mounted routers. */ + items: ({ kind: "middleware"; entry: ChainEntry } | { kind: "mount"; child: RouterValue })[] + site: Node +} + +type Registration = RouteRegistration | UseRegistration + +const MAX_MOUNT_DEPTH = 12 + +export function extractRoutes(ep: ExpressProject, ev: Evaluator = new Evaluator(ep)): ExtractResult { + const registrations: Registration[] = [] + const unresolvedPaths: ExtractResult["unresolvedPaths"] = [] + + for (const file of ep.files.values()) { + for (const call of file.getDescendantsOfKind(SyntaxKind.CallExpression)) { + const callee = call.getExpression() + if (!Node.isPropertyAccessExpression(callee)) continue + const method = callee.getName() + if (!VERBS.has(method) && method !== "use") continue + for (const env of loopEnvs(call, ev)) { + collect(call, method, callee.getExpression(), env, ev, registrations, unresolvedPaths) + } + } + } + + return { routes: expand(registrations), unresolvedPaths } +} + +/** + * Environments to evaluate a registration under. A registration inside a + * `forEach` / `map` callback over an array literal (`defaultRoutes.forEach(r => + * router.use(r.path, r.route))`) is evaluated once per element, so each path + * stays paired with its own router. + */ +function loopEnvs(call: CallExpression, ev: Evaluator): Env[] { + const fn = enclosingFunction(call) + const parent = fn?.getParent() + if (!fn || !parent || !Node.isCallExpression(parent) || !parent.getArguments().includes(fn)) return [new Map()] + const callee = parent.getExpression() + if (!Node.isPropertyAccessExpression(callee) || !["forEach", "map", "flatMap"].includes(callee.getName())) return [new Map()] + const param = (fn as unknown as { getParameters(): ParameterDeclaration[] }).getParameters()[0] + if (!param) return [new Map()] + const envs: Env[] = [] + for (const arr of ev.evaluate(callee.getExpression())) { + if (arr.kind !== "array" || !Node.isArrayLiteralExpression(arr.node)) continue + for (const el of arr.node.getElements()) envs.push(new Map([[param, ev.evaluate(el)]])) + } + return envs.length > 0 ? envs : [new Map()] +} + +function collect( + call: CallExpression, + method: string, + receiver: Node, + env: Env, + ev: Evaluator, + out: Registration[], + unresolved: ExtractResult["unresolvedPaths"], +): void { + const args = call.getArguments() + for (const target of ev.evaluate(receiver, env)) { + if (method === "use" && target.kind === "router") { + const first = args[0] + const firstStrings = first ? ev.evaluate(first, env).filter(isString).map((s) => s.value) : [] + const hasPrefix = firstStrings.length > 0 + const rest = hasPrefix ? args.slice(1) : args + const items: UseRegistration["items"] = [] + for (const arg of flattenArgs(rest, ev, env)) { + const values = ev.evaluate(arg, env) + const routers = values.filter((v): v is RouterValue => v.kind === "router") + if (routers.length > 0) { + for (const child of routers) items.push({ kind: "mount", child }) + } else { + items.push({ kind: "middleware", entry: chainEntry(arg, values, ev, env) }) + } + } + out.push({ kind: "use", router: target, prefixes: hasPrefix ? firstStrings : [""], items, site: call }) + } else if (VERBS.has(method) && target.kind === "router") { + // app.get("env") reads a setting; a route needs a path and at least one handler + if (args.length < 2) continue + const paths = pathStrings(args[0], ev, env) + if (paths.length === 0) { + unresolved.push({ file: relativePath(call.getSourceFile()), line: call.getStartLineNumber(), text: args[0].getText() }) + continue + } + const entries = flattenArgs(args.slice(1), ev, env).map((a) => chainEntry(a, ev.evaluate(a, env), ev, env)) + out.push({ kind: "route", router: target, method: httpMethod(method), paths, entries, site: call }) + } else if (VERBS.has(method) && target.kind === "routeChain") { + if (args.length < 1) continue + const entries = flattenArgs(args, ev, env).map((a) => chainEntry(a, ev.evaluate(a, env), ev, env)) + out.push({ kind: "route", router: target.router, method: httpMethod(method), paths: target.paths, entries, site: call }) + } + } +} + +/** A route path argument: a string, or an array of strings (`router.get(["/a", "/b"], h)`). */ +function pathStrings(arg: Node, ev: Evaluator, env: Env): string[] { + const out: string[] = [] + for (const v of ev.evaluate(arg, env)) { + if (v.kind === "string") out.push(v.value) + else if (v.kind === "array" && Node.isArrayLiteralExpression(v.node)) { + for (const el of v.node.getElements()) out.push(...ev.evaluate(el, env).filter(isString).map((s) => s.value)) + } + } + return out +} + +/** Arguments with array literals (and constants holding one) spread out: `[checkJwt, checkRole(["ADMIN"])]`. */ +function flattenArgs(args: Node[], ev: Evaluator, env: Env): Node[] { + const out: Node[] = [] + for (const arg of args) { + if (Node.isArrayLiteralExpression(arg)) { + out.push(...flattenArgs(arg.getElements(), ev, env)) + continue + } + if (Node.isIdentifier(arg)) { + const arrays = ev.evaluate(arg, env).filter((v) => v.kind === "array") + const first = arrays[0] + if (arrays.length === 1 && first.kind === "array" && Node.isArrayLiteralExpression(first.node)) { + out.push(...flattenArgs(first.node.getElements(), ev, env)) + continue + } + } + if (Node.isSpreadElement(arg)) { + out.push(...flattenArgs([arg.getExpression()], ev, env)) + continue + } + out.push(arg) + } + return out +} + +function chainEntry(node: Node, values: Value[], ev: Evaluator, env: Env): ChainEntry { + let callee: Node = node + let args: string[] = [] + if (Node.isCallExpression(node)) { + callee = node.getExpression() + args = node.getArguments().map((a) => a.getText()) + // a method chain is named after the call it starts from: body("email").isEmail() → "body" + while (Node.isPropertyAccessExpression(callee) && Node.isCallExpression(callee.getExpression())) { + const inner = callee.getExpression() as CallExpression + callee = inner.getExpression() + args = inner.getArguments().map((a) => a.getText()) + } + } + const name = Node.isPropertyAccessExpression(callee) ? callee.getName() + : Node.isIdentifier(callee) ? callee.getText() + : isFunctionNode(node) ? "" + : callee.getText() + return { + text: node.getText().replace(/\s+/g, " "), + name, + wrapped: wrappedText(node, values, ev, env), + args, + values, + node, + file: relativePath(node.getSourceFile()), + line: node.getStartLineNumber(), + } +} + +function httpMethod(verb: string): string { + return verb === "all" ? "ALL" : verb.toUpperCase() +} + +// --------------------------------------------------------------------------- +// Expansion: routers → full routes +// --------------------------------------------------------------------------- + +interface ScopedMiddleware { + entry: ChainEntry + /** Full path prefix the middleware is mounted at ("" for all paths). */ + scope: string +} + +function expand(registrations: Registration[]): ExpressRoute[] { + const byRouter = new Map() + const mounted = new Set() + const routers = new Map() + for (const r of registrations) { + routers.set(r.router.id, r.router) + const list = byRouter.get(r.router.id) ?? [] + list.push(r) + byRouter.set(r.router.id, list) + if (r.kind === "use") { + for (const item of r.items) { + if (item.kind === "mount") { + mounted.add(item.child.id) + routers.set(item.child.id, item.child) + } + } + } + } + for (const list of byRouter.values()) list.sort((a, b) => compareSites(a, b)) + + const out: ExpressRoute[] = [] + const seen = new Set() + const visit = (router: RouterValue, prefix: string, inherited: ScopedMiddleware[], stack: Set): void => { + if (stack.has(router.id) || stack.size >= MAX_MOUNT_DEPTH) return + const nextStack = new Set(stack).add(router.id) + const local: ScopedMiddleware[] = [] + for (const reg of byRouter.get(router.id) ?? []) { + if (reg.kind === "use") { + for (const p of reg.prefixes) { + const scope = joinPath(prefix, p) + const pending: ScopedMiddleware[] = [] + for (const item of reg.items) { + if (item.kind === "middleware") { + pending.push({ entry: item.entry, scope: p === "" ? prefix : scope }) + } else { + visit(item.child, scope, [...inherited, ...local, ...pending], nextStack) + } + } + local.push(...pending) + } + } else { + for (const p of reg.paths) { + const full = joinPath(prefix, p) + const key = `${reg.method} ${full} ${reg.site.getSourceFile().getFilePath()}:${reg.site.getStart()}` + if (seen.has(key)) continue + seen.add(key) + const chain = [...inherited, ...local].filter((m) => inScope(m.scope, full)).map((m) => m.entry) + const own = reg.entries.slice(0, -1) + const last = reg.entries[reg.entries.length - 1] + out.push({ + method: reg.method, + path: full, + file: relativePath(reg.site.getSourceFile()), + line: reg.site.getStartLineNumber(), + middleware: [...chain, ...own], + handler: handlerRef(last, reg.site), + }) + } + } + } + } + + // Apps first, then routers nothing mounts (mounted somewhere this parser cannot see) + const roots = [...routers.values()].filter((r) => !mounted.has(r.id)) + roots.sort((a, b) => Number(b.isApp) - Number(a.isApp) || a.id.localeCompare(b.id)) + for (const root of roots) visit(root, "", [], new Set()) + return out +} + +/** + * Registration order on one router. Within a file, source order. A registration + * in another file than the router was created in (a registrar function handed + * the router) is ordered after the router's own file — the call site that hands + * it over is not tracked, so middleware registered after that call is + * over-applied to it. + */ +function compareSites(a: Registration, b: Registration): number { + const home = a.router.file + const fa = relativePath(a.site.getSourceFile()) + const fb = relativePath(b.site.getSourceFile()) + if (fa === fb) return a.site.getStart() - b.site.getStart() + if (fa === home) return -1 + if (fb === home) return 1 + return fa.localeCompare(fb) +} + +/** Express path-scoped middleware: `app.use("/api", mw)` runs for "/api" and "/api/...". */ +function inScope(scope: string, path: string): boolean { + if (scope === "" || scope === "/") return true + return path === scope || path.startsWith(scope.endsWith("/") ? scope : `${scope}/`) +} + +export function joinPath(prefix: string, path: string): string { + if (!path || path === "/") return prefix || "/" + const joined = `${prefix}/${path}`.replace(/\/{2,}/g, "/") + const withSlash = joined.startsWith("/") ? joined : `/${joined}` + return withSlash.length > 1 ? withSlash.replace(/\/$/, "") : withSlash +} + +/** + * The route handler: the last argument at the registration. A wrapper call + * (`catchAsync(async (req, res) => ...)`, `asyncHandler(controller.list)`) is + * looked through to the function it wraps. + */ +function handlerRef(entry: ChainEntry | undefined, site: Node): HandlerRef { + const fallback = { file: relativePath(site.getSourceFile()), line: site.getStartLineNumber() } + if (!entry) return { symbol: "", node: null, ...fallback } + const symbol = isFunctionNode(entry.node) ? "" : entry.wrapped ?? entry.text + const fn = resolvedFunction(entry) + if (!fn) return { symbol, node: null, ...fallback } + return { symbol, node: fn, file: relativePath(fn.getSourceFile()), line: fn.getStartLineNumber() } +} + +/** The handler function: written inline, or what the argument evaluates to (wrappers are looked through by the evaluator). */ +function resolvedFunction(entry: ChainEntry): Node | null { + if (isFunctionNode(entry.node)) return entry.node + const fn = entry.values.find((v) => v.kind === "function") + return fn && fn.kind === "function" ? fn.node : null +} + +/** + * When a call evaluated to a function that one of its arguments (or, for + * `.bind`, its receiver) evaluates to, that argument's text: the call is a + * wrapper and the argument is the real handler. + */ +function wrappedText(node: Node, values: Value[], ev: Evaluator, env: Env): string | undefined { + if (!Node.isCallExpression(node)) return undefined + const fns = new Set(values.filter((v) => v.kind === "function").map((v) => (v as { node: Node }).node)) + if (fns.size === 0) return undefined + const callee = node.getExpression() + if (Node.isPropertyAccessExpression(callee) && callee.getName() === "bind") return callee.getExpression().getText() + for (const arg of node.getArguments()) { + if (isFunctionNode(arg) && fns.has(arg)) return "" + if (ev.evaluate(arg, env).some((v) => v.kind === "function" && fns.has(v.node))) return arg.getText().replace(/\s+/g, " ") + } + return undefined +} diff --git a/packages/express-parser/src/scanner.ts b/packages/express-parser/src/scanner.ts new file mode 100644 index 0000000..97d426d --- /dev/null +++ b/packages/express-parser/src/scanner.ts @@ -0,0 +1,62 @@ +import { readdirSync, readFileSync, statSync } from "fs" +import { join, relative } from "path" + +/** Directories that hold no server code (or only tests, build output, front-end assets). */ +const SKIP_DIRS = new Set([ + "node_modules", "dist", "build", "out", "coverage", ".git", + "public", "static", "client", "frontend", "views", + "test", "tests", "__tests__", "__mocks__", "e2e", "docs", +]) + +const SOURCE_FILE = /\.(js|cjs|mjs|ts|cts|mts)$/ +const EXCLUDED_FILE = /(\.d\.ts|\.(test|spec)\.[cm]?[jt]s|\.min\.js)$/ + +export interface SourceFile { + /** Path relative to the project root, with `/` separators. */ + path: string + content: string +} + +/** JavaScript and TypeScript server files under `root`, relative to it, `/`-separated, sorted. */ +export function findSourceFiles(root: string): string[] { + const out: string[] = [] + walk(root, root, out, 0) + return out.sort() +} + +function walk(root: string, dir: string, out: string[], depth: number): void { + if (depth > 12) return + let entries: string[] + try { + entries = readdirSync(dir) + } catch { + return + } + for (const entry of entries) { + if (entry.startsWith(".") || SKIP_DIRS.has(entry)) continue + const abs = join(dir, entry) + let isDir: boolean + try { + isDir = statSync(abs).isDirectory() + } catch { + continue + } + if (isDir) walk(root, abs, out, depth + 1) + else if (SOURCE_FILE.test(entry) && !EXCLUDED_FILE.test(entry)) { + out.push(relative(root, abs).replace(/\\/g, "/")) + } + } +} + +/** Reads every server file under `root`. Unreadable files are skipped. */ +export function readSourceFiles(root: string): SourceFile[] { + const out: SourceFile[] = [] + for (const path of findSourceFiles(root)) { + try { + out.push({ path, content: readFileSync(join(root, path), "utf-8") }) + } catch { + // unreadable — skip + } + } + return out +} diff --git a/packages/express-parser/src/scope.ts b/packages/express-parser/src/scope.ts new file mode 100644 index 0000000..3e09f15 --- /dev/null +++ b/packages/express-parser/src/scope.ts @@ -0,0 +1,131 @@ +import { Node, SyntaxKind, type BindingElement, type ParameterDeclaration, type SourceFile } from "ts-morph" + +/** + * Where a name is declared, found by walking lexical scopes outward from a use + * site. Done by hand rather than through the TypeScript checker so JavaScript + * (require, module.exports) and TypeScript resolve the same way and no type + * checking runs. + */ +export type Binding = + /** `const x = init`, or `const { a: x } = init` with path ["a"]. */ + | { kind: "var"; init: Node | undefined; path: string[]; node: Node } + /** A function parameter; `path` selects into a destructured parameter. */ + | { kind: "param"; param: ParameterDeclaration; path: string[] } + | { kind: "function"; node: Node } + | { kind: "class"; node: Node } + /** `import x from "m"` (imported "default"), `import * as x` ("*"), `import { a as x }` ("a"). */ + | { kind: "import"; specifier: string; imported: string; file: SourceFile } + +const SCOPE_KINDS = new Set([ + SyntaxKind.SourceFile, SyntaxKind.Block, SyntaxKind.ModuleBlock, SyntaxKind.CaseClause, SyntaxKind.DefaultClause, + SyntaxKind.FunctionDeclaration, SyntaxKind.FunctionExpression, SyntaxKind.ArrowFunction, SyntaxKind.MethodDeclaration, + SyntaxKind.Constructor, SyntaxKind.GetAccessor, SyntaxKind.SetAccessor, + SyntaxKind.ForStatement, SyntaxKind.ForOfStatement, SyntaxKind.ForInStatement, SyntaxKind.CatchClause, +]) + +export function lookupName(from: Node, name: string): Binding | null { + for (let scope: Node | undefined = from; scope; scope = scope.getParent()) { + if (!SCOPE_KINDS.has(scope.getKind())) continue + const found = declaredIn(scope, name) + if (found) return found + } + return null +} + +function declaredIn(scope: Node, name: string): Binding | null { + // parameters of a function-like scope + if (Node.isFunctionLikeDeclaration(scope) || Node.isArrowFunction(scope) || Node.isFunctionExpression(scope)) { + for (const param of scope.getParameters()) { + const path = bindingPath(param.getNameNode(), name) + if (path) return { kind: "param", param, path } + } + // the body is a Block, visited as its own scope on the way out + return null + } + // `for (const x of xs)` / `for (const x in o)` / `for (let i = ...)` + if (Node.isForOfStatement(scope) || Node.isForInStatement(scope) || Node.isForStatement(scope)) { + const init = scope.getInitializer() + if (init && Node.isVariableDeclarationList(init)) { + for (const decl of init.getDeclarations()) { + const path = bindingPath(decl.getNameNode(), name) + if (path) return { kind: "var", init: undefined, path, node: decl } + } + } + return null + } + if (Node.isCatchClause(scope)) return null + + if (!(Node.isSourceFile(scope) || Node.isBlock(scope) || Node.isModuleBlock(scope) || + Node.isCaseClause(scope) || Node.isDefaultClause(scope))) return null + + for (const stmt of scope.getStatements()) { + if (Node.isVariableStatement(stmt)) { + for (const decl of stmt.getDeclarations()) { + const path = bindingPath(decl.getNameNode(), name) + if (path) return { kind: "var", init: decl.getInitializer(), path, node: decl } + } + } else if (Node.isFunctionDeclaration(stmt) && stmt.getName() === name) { + return { kind: "function", node: stmt } + } else if (Node.isClassDeclaration(stmt) && stmt.getName() === name) { + return { kind: "class", node: stmt } + } else if (Node.isImportDeclaration(stmt)) { + const specifier = stmt.getModuleSpecifierValue() + const file = stmt.getSourceFile() + if (stmt.getDefaultImport()?.getText() === name) return { kind: "import", specifier, imported: "default", file } + if (stmt.getNamespaceImport()?.getText() === name) return { kind: "import", specifier, imported: "*", file } + for (const named of stmt.getNamedImports()) { + const local = named.getAliasNode()?.getText() ?? named.getName() + if (local === name) return { kind: "import", specifier, imported: named.getName(), file } + } + } else if (Node.isImportEqualsDeclaration(stmt) && stmt.getName() === name) { + // `import x = require("m")` + const ref = stmt.getModuleReference() + if (Node.isExternalModuleReference(ref)) { + const expr = ref.getExpression() + if (expr && Node.isStringLiteral(expr)) { + return { kind: "import", specifier: expr.getLiteralValue(), imported: "=", file: stmt.getSourceFile() } + } + } + } + } + return null +} + +/** + * The property path from a binding pattern to `name`: [] for a plain + * identifier, ["a"] for `{ a }` / `{ a: name }`, ["a", "b"] for `{ a: { b } }`, + * array elements as their index. Null when `name` is not bound by it. + */ +function bindingPath(nameNode: Node, name: string): string[] | null { + if (Node.isIdentifier(nameNode)) return nameNode.getText() === name ? [] : null + if (Node.isObjectBindingPattern(nameNode)) { + for (const el of nameNode.getElements()) { + const key = propertyKey(el) + const inner = bindingPath(el.getNameNode(), name) + if (inner && key !== null) return [key, ...inner] + } + return null + } + if (Node.isArrayBindingPattern(nameNode)) { + const elements = nameNode.getElements() + for (let i = 0; i < elements.length; i++) { + const el = elements[i] + if (!Node.isBindingElement(el)) continue + const inner = bindingPath(el.getNameNode(), name) + if (inner) return [String(i), ...inner] + } + } + return null +} + +function propertyKey(el: BindingElement): string | null { + const prop = el.getPropertyNameNode() + if (!prop) { + const n = el.getNameNode() + return Node.isIdentifier(n) ? n.getText() : null + } + if (Node.isIdentifier(prop) || Node.isStringLiteral(prop)) { + return Node.isStringLiteral(prop) ? prop.getLiteralValue() : prop.getText() + } + return null +} diff --git a/packages/express-parser/tsconfig.json b/packages/express-parser/tsconfig.json new file mode 100644 index 0000000..b85441a --- /dev/null +++ b/packages/express-parser/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist" + }, + "include": ["src"], + "exclude": ["dist", "node_modules", "src/__tests__/fixtures"] +} diff --git a/packages/mcp-server/build.mjs b/packages/mcp-server/build.mjs index 04ea50c..c5342ef 100644 --- a/packages/mcp-server/build.mjs +++ b/packages/mcp-server/build.mjs @@ -22,6 +22,7 @@ await build({ "@kidkender/archmind-laravel-parser", "@kidkender/archmind-nestjs-parser", "@kidkender/archmind-go-parser", + "@kidkender/archmind-express-parser", "@kidkender/archmind-lens", "@kidkender/archmind-retrieval", "@kidkender/archmind-runtime-ingest", diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index 769ac35..8182132 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -18,6 +18,7 @@ "@kidkender/archmind-laravel-parser": "*", "@kidkender/archmind-nestjs-parser": "*", "@kidkender/archmind-go-parser": "*", + "@kidkender/archmind-express-parser": "*", "@kidkender/archmind-lens": "*", "@kidkender/archmind-retrieval": "*", "@kidkender/archmind-explainer": "*", diff --git a/packages/mcp-server/src/cache.ts b/packages/mcp-server/src/cache.ts index 6ead2a8..31c7190 100644 --- a/packages/mcp-server/src/cache.ts +++ b/packages/mcp-server/src/cache.ts @@ -1,6 +1,7 @@ import { parseRouteFile, augmentGraph, loadProjectConfig, resolveAliasMap, ParseCache } from "@kidkender/archmind-laravel-parser" import { parseNestJSProjectIncremental, createNestProject } from "@kidkender/archmind-nestjs-parser" import { parseGinProjectAt, isGinProject, findGoFiles } from "@kidkender/archmind-go-parser" +import { parseExpressProjectAt, isExpressProject, findExpressRoot, findSourceFiles } from "@kidkender/archmind-express-parser" import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" import { join, relative } from "path" import { existsSync, statSync, readdirSync } from "fs" @@ -18,17 +19,21 @@ const nestProjects = new Map() const nestTrackedFiles = new Map>() // Go: relPath → last-seen mtimeMs for every *.go file discovered by the last parse. const goTrackedFiles = new Map>() +// Express: app-relative path → last-seen mtimeMs for every JS/TS server file of the last parse. +const expressTrackedFiles = new Map>() -export type Framework = "laravel" | "nestjs" | "go" +export type Framework = "laravel" | "nestjs" | "go" | "express" // Auto-detect framework from project root. // nest-cli.json → NestJS // go.mod (importing gin) → Go/Gin +// package.json → express → Express (not NestJS; root or one directory down) // artisan → Laravel // default → Laravel export function detectFramework(projectRoot: string): Framework { if (existsSync(join(projectRoot, "nest-cli.json"))) return "nestjs" if (isGinProject(projectRoot)) return "go" + if (!existsSync(join(projectRoot, "artisan")) && isExpressProject(projectRoot)) return "express" return "laravel" } @@ -84,6 +89,29 @@ export function hasAnyTrackedFileChanged(projectRoot: string): boolean { // correctness over parse speed for v1). Detects both edits to tracked // files and newly added/removed .go files. ────────────────────────── +// ── Express: same whole-project mtime check as Go, over the app's JS/TS files ── + +function expressFileIndex(projectRoot: string): Map { + const appRoot = findExpressRoot(projectRoot) ?? projectRoot + const index = new Map() + for (const rel of findSourceFiles(appRoot)) { + const mtime = statMtime(join(appRoot, rel)) + if (mtime !== null) index.set(rel, mtime) + } + return index +} + +function hasAnyExpressFileChanged(projectRoot: string): boolean { + const index = expressTrackedFiles.get(projectRoot) + if (!index) return true + const current = expressFileIndex(projectRoot) + if (current.size !== index.size) return true + for (const [rel, mtime] of current) { + if (index.get(rel) !== mtime) return true + } + return false +} + function hasAnyGoFileChanged(projectRoot: string): boolean { const index = goTrackedFiles.get(projectRoot) if (!index) return true @@ -200,6 +228,18 @@ export function getGraphs(projectRoot: string): IntermediateExecutionGraph[] { return graphs } + if (framework === "express") { + if (cache.has(projectRoot) && hasAnyExpressFileChanged(projectRoot)) { + cache.delete(projectRoot) + } + if (cache.has(projectRoot)) return cache.get(projectRoot)! + + const graphs = parseExpressProjectAt(projectRoot) + expressTrackedFiles.set(projectRoot, expressFileIndex(projectRoot)) + cache.set(projectRoot, graphs) + return graphs + } + if (framework === "nestjs") { // Auto-invalidate if tracked controller/config files changed. // Keep nestProjects alive — the cached Project will be refreshed below. @@ -277,6 +317,7 @@ export function invalidate(projectRoot: string): void { nestProjects.delete(projectRoot) nestTrackedFiles.delete(projectRoot) goTrackedFiles.delete(projectRoot) + expressTrackedFiles.delete(projectRoot) // Don't clear parseCaches — content-hash keying means a changed file produces // a new hash (miss) while unchanged files stay warm. Clearing would only slow // the next full re-parse without gaining correctness. diff --git a/packages/mcp-server/src/server.ts b/packages/mcp-server/src/server.ts index eb7291f..2baefff 100644 --- a/packages/mcp-server/src/server.ts +++ b/packages/mcp-server/src/server.ts @@ -33,7 +33,7 @@ export function createServer(): McpServer { server.registerTool( "archmind_detect_framework", { - description: "Detect whether a project is Laravel, NestJS, or Go/Gin. Call this first if you are unsure which framework the project uses.", + description: "Detect whether a project is Laravel, NestJS, Go/Gin, or Express. Call this first if you are unsure which framework the project uses.", inputSchema: { project_root: z.string().describe("Absolute path to the project root"), }, @@ -53,12 +53,12 @@ export function createServer(): McpServer { "archmind_list_entrypoints", { description: - "List HTTP routes (Laravel, NestJS, Go/Gin) with the handler's file and line. " + + "List HTTP routes (Laravel, NestJS, Go/Gin, Express) with the handler's file and line. " + "Use it to find which route and handler file serve an endpoint, then Read that file. " + "Pass `filter` (e.g. 'inventory', 'character.go') to narrow the list; an unfiltered call on a large API returns every route. " + "Routes only: it does not locate services, helpers, DTOs, tests or non-HTTP code (websocket, game loops, background workers) - use grep for those.", inputSchema: { - project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, or Go/Gin)"), + project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, Go/Gin, or Express)"), filter: z .string() .optional() @@ -83,9 +83,9 @@ export function createServer(): McpServer { "archmind_get_execution_graph", { description: - "Return the semantic execution graph for a specific entrypoint in a Laravel, NestJS, or Go/Gin project. Use `focus` to narrow to a concern: auth, validation, runtime, transaction, isolation, side_effects (queue jobs / mail / notifications / API resources only), all. Framework is auto-detected.", + "Return the semantic execution graph for a specific entrypoint in a Laravel, NestJS, Go/Gin, or Express project. Use `focus` to narrow to a concern: auth, validation, runtime, transaction, isolation, side_effects (queue jobs / mail / notifications / API resources only), all. Framework is auto-detected.", inputSchema: { - project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, or Go/Gin)"), + project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, Go/Gin, or Express)"), entrypoint: z.string().describe('Entrypoint in "METHOD /path" format, e.g. "PUT /tasks/{task}"'), focus: z .enum(FOCUS_VALUES) @@ -152,7 +152,7 @@ export function createServer(): McpServer { description: "Run static and optional runtime pattern detectors on the execution graph and return semantic findings (no LLM call). Findings include security issues, authorization gaps, transaction anomalies, isolation violations, and — when a trace session is provided — runtime findings like N+1 queries and slow queries.", inputSchema: { - project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, or Go/Gin)"), + project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, Go/Gin, or Express)"), entrypoint: z.string().describe('Entrypoint in "METHOD /path" format, e.g. "PUT /tasks/{task}" or "GET /users/:id"'), query: z .string() @@ -253,7 +253,7 @@ export function createServer(): McpServer { "formatted for direct LLM consumption. Prefer this over archmind_get_findings when you need " + "to reason about a specific question rather than enumerate all findings.", inputSchema: { - project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, or Go/Gin)"), + project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, Go/Gin, or Express)"), entrypoint: z.string().describe('Entrypoint in "METHOD /path" format, e.g. "PUT /products/{product}"'), question: z.string().describe('Natural language question, e.g. "Why is authorization duplicated?" or "Can a guest update this resource?"'), }, @@ -293,7 +293,7 @@ export function createServer(): McpServer { " side_effects — routes that dispatch queue jobs, send mail/notifications, or return API resources; flags synchronous mail\n" + " request — full execution path for a single route (requires entrypoint)", inputSchema: { - project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, or Go/Gin)"), + project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, Go/Gin, or Express)"), pattern: z .enum(["auth", "event", "transaction", "isolation", "side_effects", "request"]) .describe("Trace pattern to run"), @@ -320,10 +320,10 @@ export function createServer(): McpServer { "Answers 'which routes break if I change X?', not 'which files reference X'. " + "Pass a class name (e.g. 'OrderService', 'GenerateInvoicePdfJob') for all usages, or a full symbol " + "(e.g. 'OrderService::create') for a specific method. " + - "Currently indexes Laravel and NestJS service calls only: on Go/Gin projects it returns no results, which means " + + "Indexes Laravel, NestJS and Express service calls (Express: 'userService' or 'userService::createUser'); on Go/Gin projects it returns no results, which means " + "'not indexed', not 'no dependents' - use grep there.", inputSchema: { - project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, or Go/Gin)"), + project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, Go/Gin, or Express)"), symbol: z .string() .describe( @@ -367,7 +367,7 @@ export function createServer(): McpServer { "validation, services, async side-effects, and a risk level. " + "Use this instead of archmind_get_execution_graph when you want to reason about a route without navigating raw nodes.", inputSchema: { - project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, or Go/Gin)"), + project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, Go/Gin, or Express)"), entrypoint: z .string() .optional() @@ -494,7 +494,7 @@ export function createServer(): McpServer { description: "Invalidate the cached parse result for a project root, forcing a fresh parse on the next call. Use when the project's source files have changed.", inputSchema: { - project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, or Go/Gin)"), + project_root: z.string().describe("Absolute path to the project root (Laravel, NestJS, Go/Gin, or Express)"), }, }, async ({ project_root }) => { diff --git a/research/cross-framework/auth-authz/express/app.js b/research/cross-framework/auth-authz/express/app.js new file mode 100644 index 0000000..168e54f --- /dev/null +++ b/research/cross-framework/auth-authz/express/app.js @@ -0,0 +1,12 @@ +// Auth + authorization: authenticated, then a role check for "editor". +const express = require('express') +const { requireAuth, requireRole } = require('./auth') + +const app = express() +app.use(express.json()) + +app.put('/tasks/:id', requireAuth, requireRole('editor'), (req, res) => { + res.json({ id: req.params.id }) +}) + +module.exports = app diff --git a/research/cross-framework/auth-authz/express/auth.js b/research/cross-framework/auth-authz/express/auth.js new file mode 100644 index 0000000..c584c52 --- /dev/null +++ b/research/cross-framework/auth-authz/express/auth.js @@ -0,0 +1,15 @@ +const jwt = require('jsonwebtoken') + +exports.requireAuth = (req, res, next) => { + try { + req.user = jwt.verify(req.headers.authorization, process.env.JWT_SECRET) + next() + } catch { + res.status(401).end() + } +} + +exports.requireRole = (role) => (req, res, next) => { + if (req.user.roles.includes(role)) return next() + res.status(403).end() +} diff --git a/research/cross-framework/auth-authz/express/package.json b/research/cross-framework/auth-authz/express/package.json new file mode 100644 index 0000000..ce5c4de --- /dev/null +++ b/research/cross-framework/auth-authz/express/package.json @@ -0,0 +1,5 @@ +{ + "name": "auth-authz-express", + "private": true, + "dependencies": { "express": "^4.19.0" } +} diff --git a/research/cross-framework/auth-only/express/app.js b/research/cross-framework/auth-only/express/app.js new file mode 100644 index 0000000..738aa1a --- /dev/null +++ b/research/cross-framework/auth-only/express/app.js @@ -0,0 +1,16 @@ +// Auth only: a JWT-authenticated read, no authorization, no validation. +const express = require('express') +const { requireAuth } = require('./auth') + +const app = express() +app.use(express.json()) + +const tasks = express.Router() +tasks.use(requireAuth) +tasks.get('/:id', (req, res) => { + res.json({ id: req.params.id }) +}) + +app.use('/tasks', tasks) + +module.exports = app diff --git a/research/cross-framework/auth-only/express/auth.js b/research/cross-framework/auth-only/express/auth.js new file mode 100644 index 0000000..b46b6c2 --- /dev/null +++ b/research/cross-framework/auth-only/express/auth.js @@ -0,0 +1,11 @@ +const jwt = require('jsonwebtoken') + +exports.requireAuth = (req, res, next) => { + const token = (req.headers.authorization || '').replace('Bearer ', '') + try { + req.user = jwt.verify(token, process.env.JWT_SECRET) + next() + } catch { + res.status(401).end() + } +} diff --git a/research/cross-framework/auth-only/express/package.json b/research/cross-framework/auth-only/express/package.json new file mode 100644 index 0000000..703e423 --- /dev/null +++ b/research/cross-framework/auth-only/express/package.json @@ -0,0 +1,5 @@ +{ + "name": "auth-only-express", + "private": true, + "dependencies": { "express": "^4.19.0" } +} diff --git a/research/cross-framework/auth-service-call/express/app.js b/research/cross-framework/auth-service-call/express/app.js new file mode 100644 index 0000000..a9d5f55 --- /dev/null +++ b/research/cross-framework/auth-service-call/express/app.js @@ -0,0 +1,12 @@ +// Auth + service call: the handler delegates to a service. +const express = require('express') +const { requireAuth } = require('./auth') +const taskService = require('./task.service') + +const app = express() + +app.get('/tasks/:id', requireAuth, async (req, res) => { + res.json(await taskService.findById(req.params.id)) +}) + +module.exports = app diff --git a/research/cross-framework/auth-service-call/express/auth.js b/research/cross-framework/auth-service-call/express/auth.js new file mode 100644 index 0000000..b46b6c2 --- /dev/null +++ b/research/cross-framework/auth-service-call/express/auth.js @@ -0,0 +1,11 @@ +const jwt = require('jsonwebtoken') + +exports.requireAuth = (req, res, next) => { + const token = (req.headers.authorization || '').replace('Bearer ', '') + try { + req.user = jwt.verify(token, process.env.JWT_SECRET) + next() + } catch { + res.status(401).end() + } +} diff --git a/research/cross-framework/auth-service-call/express/package.json b/research/cross-framework/auth-service-call/express/package.json new file mode 100644 index 0000000..81e0e87 --- /dev/null +++ b/research/cross-framework/auth-service-call/express/package.json @@ -0,0 +1,5 @@ +{ + "name": "auth-service-call-express", + "private": true, + "dependencies": { "express": "^4.19.0" } +} diff --git a/research/cross-framework/auth-service-call/express/task.service.js b/research/cross-framework/auth-service-call/express/task.service.js new file mode 100644 index 0000000..7b4a92a --- /dev/null +++ b/research/cross-framework/auth-service-call/express/task.service.js @@ -0,0 +1 @@ +exports.findById = async (id) => ({ id }) diff --git a/research/cross-framework/auth-transaction/express/app.ts b/research/cross-framework/auth-transaction/express/app.ts new file mode 100644 index 0000000..6516246 --- /dev/null +++ b/research/cross-framework/auth-transaction/express/app.ts @@ -0,0 +1,19 @@ +// Auth + transaction: two writes inside one TypeORM transaction. +import express from 'express' +import { requireAuth } from './auth' +import { dataSource } from './data-source' +import { Order } from './order.entity' +import { Payment } from './payment.entity' + +const app = express() +app.use(express.json()) + +app.post('/orders', requireAuth, async (req, res) => { + await dataSource.transaction(async (manager) => { + const order = await manager.save(Order, req.body) + await manager.save(Payment, { orderId: order.id, amount: req.body.total }) + }) + res.status(201).json({ created: true }) +}) + +export default app diff --git a/research/cross-framework/auth-transaction/express/auth.ts b/research/cross-framework/auth-transaction/express/auth.ts new file mode 100644 index 0000000..81b3958 --- /dev/null +++ b/research/cross-framework/auth-transaction/express/auth.ts @@ -0,0 +1,11 @@ +import jwt from 'jsonwebtoken' +import type { Request, Response, NextFunction } from 'express' + +export function requireAuth(req: Request, res: Response, next: NextFunction) { + try { + (req as any).user = jwt.verify(req.headers.authorization ?? '', process.env.JWT_SECRET!) + next() + } catch { + res.status(401).end() + } +} diff --git a/research/cross-framework/auth-transaction/express/data-source.ts b/research/cross-framework/auth-transaction/express/data-source.ts new file mode 100644 index 0000000..9ff0874 --- /dev/null +++ b/research/cross-framework/auth-transaction/express/data-source.ts @@ -0,0 +1,3 @@ +import { DataSource } from 'typeorm' + +export const dataSource = new DataSource({ type: 'postgres' }) diff --git a/research/cross-framework/auth-transaction/express/order.entity.ts b/research/cross-framework/auth-transaction/express/order.entity.ts new file mode 100644 index 0000000..39360bb --- /dev/null +++ b/research/cross-framework/auth-transaction/express/order.entity.ts @@ -0,0 +1 @@ +export class Order { id!: number } diff --git a/research/cross-framework/auth-transaction/express/package.json b/research/cross-framework/auth-transaction/express/package.json new file mode 100644 index 0000000..71c91f3 --- /dev/null +++ b/research/cross-framework/auth-transaction/express/package.json @@ -0,0 +1,5 @@ +{ + "name": "auth-transaction-express", + "private": true, + "dependencies": { "express": "^4.19.0" } +} diff --git a/research/cross-framework/auth-transaction/express/payment.entity.ts b/research/cross-framework/auth-transaction/express/payment.entity.ts new file mode 100644 index 0000000..474c22f --- /dev/null +++ b/research/cross-framework/auth-transaction/express/payment.entity.ts @@ -0,0 +1 @@ +export class Payment { orderId!: number; amount!: number } diff --git a/research/cross-framework/auth-validation/express/app.js b/research/cross-framework/auth-validation/express/app.js new file mode 100644 index 0000000..03e71f1 --- /dev/null +++ b/research/cross-framework/auth-validation/express/app.js @@ -0,0 +1,13 @@ +// Auth + validation: authenticated, then the request body is validated. +const express = require('express') +const { body } = require('express-validator') +const { requireAuth } = require('./auth') + +const app = express() +app.use(express.json()) + +app.post('/tasks', requireAuth, body('title').isString().notEmpty(), (req, res) => { + res.status(201).json({ created: true }) +}) + +module.exports = app diff --git a/research/cross-framework/auth-validation/express/auth.js b/research/cross-framework/auth-validation/express/auth.js new file mode 100644 index 0000000..b46b6c2 --- /dev/null +++ b/research/cross-framework/auth-validation/express/auth.js @@ -0,0 +1,11 @@ +const jwt = require('jsonwebtoken') + +exports.requireAuth = (req, res, next) => { + const token = (req.headers.authorization || '').replace('Bearer ', '') + try { + req.user = jwt.verify(token, process.env.JWT_SECRET) + next() + } catch { + res.status(401).end() + } +} diff --git a/research/cross-framework/auth-validation/express/package.json b/research/cross-framework/auth-validation/express/package.json new file mode 100644 index 0000000..1f58dab --- /dev/null +++ b/research/cross-framework/auth-validation/express/package.json @@ -0,0 +1,5 @@ +{ + "name": "auth-validation-express", + "private": true, + "dependencies": { "express": "^4.19.0" } +} diff --git a/research/express-corpus/README.md b/research/express-corpus/README.md new file mode 100644 index 0000000..40f3a75 --- /dev/null +++ b/research/express-corpus/README.md @@ -0,0 +1,60 @@ +# Express parser — measurement corpus + +How `@kidkender/archmind-express-parser` was measured, on which projects, and what it found. Measured 2026-11-11 on parser 0.1.0. + +## Method + +1. Shallow-clone each project at the commit below. Nothing in them is installed or run. +2. Denominator: `node count-routes.mjs ` — a regex count of route registration sites (`x.get('/p', ...)`, chained `x.route('/p').get(...)`). +3. Parser: `node measure.mjs [--routes] [--middleware] [--graph]` after `npm run build -w packages/express-parser`. +4. Every difference between the two counts, and every middleware classification, was checked by reading the project's source. + +The regex count is an approximation: it over-counts HTTP client calls with the same shape (`axios.post('/x', data)`) and misses paths built at runtime. + +## Tuning set (used while building the parser) + +These six projects were read while the parser was written, so the numbers below are on data it was tuned against. + +| Project | Commit | Lang / ORM | Regex sites | Routes found | +|---|---|---|---|---| +| hagopj13/node-express-boilerplate | 179ae84 | JS / Mongoose | 15 | 15 | +| danielfsousa/express-rest-boilerplate | b8bed6d | JS / Mongoose | 15 | 15 | +| binitghetiya/express-sequelize-api-boilerplate | 1bc3f4f | JS / Sequelize | 5 | 5 | +| sahat/hackathon-starter | b4f25d7 | JS / Mongoose | 101 | 101 | +| andregardi/jwt-express-typeorm | 9b4db23 | TS / TypeORM | 7 | 7 | +| gothinkster/node-express-realworld-example-app | 30b68e1 | TS / Prisma | 20 | 20 | + +Two further registrations in hackathon-starter take their path from a `Map` iterated at startup; the parser reports them as unresolved instead of guessing a path. + +## Unseen set (not read before measuring) + +Measured once with the parser as it stood (commit 29044d8), before anything was changed for them. + +| Project | Commit | Lang / ORM | Regex sites | Routes found | +|---|---|---|---|---| +| sfbrigade/bats-server | c0f2616 | JS / Sequelize (a production app) | 66 | 63 | +| GeekyAnts/express-typescript | 6b9bb70 | TS / Mongoose | 15 | 15 | +| sidhantpanda/docker-express-typescript-boilerplate | 4c7c586 | TS | 6 | 6 | +| antonio-lazaro/prisma-express-typescript-boilerplate | 346d60f | TS / Prisma | 15 | 15 | +| ascii-16/expressjs-typescript-prisma-boilerplate | c27ad65 | TS / Prisma | 2 | 2 | +| w3tecch/express-typescript-boilerplate | 1772701 | TS, routing-controllers | 0 | 0 | + +- **Routes: 101 of 101 real registrations.** The three bats-server sites the regex counted and the parser did not are HTTP client calls (`axios.post(...)` in `routes/webhooks/sffd.js`, an axios instance's `.get('/api/users/me')` in `auth/peak.js`); the parser skips them because their receiver is not an Express router. +- **routing-controllers is not supported.** w3tecch/express-typescript-boilerplate declares its routes with decorators (`@JsonController`, `@Get`). Neither the regex nor the parser sees them; the parser returns no routes rather than guessing. That is a gap, not a match. +- **Transactions (bats-server): every route that opens one was found** — 27 routes, from 28 `.transaction(` sites in `routes/`. The 28th is in a helper (`resetMciCapacities`) called only from routes that open their own transaction; a graph shows the first transaction of a route. + +### Middleware classification + +22 distinct middleware across the unseen projects, labelled by reading their code. + +| | Blind (commit 29044d8) | After fixes | +|---|---|---| +| All 22 | 9 correct | 19 correct | +| 15 security middleware (auth, authorization, optional auth, validation, rate limit, CSRF) | 9 correct | 15 correct | +| 7 infrastructure middleware | 0 correct | 4 correct | + +Blind misses that mattered: bats-server's `isAdminUser`, `isSuperUser`, `isC4SFUser` and `setParams` (authorization: role flags on the user, answered with 403) were left unknown, which would have reported its admin routes as missing authorization; `checkAuthorizationHeader` (optional auth) and `verifyAuthToken` were unknown; old-style `expressValidator()` was taken for per-route validation. + +The fixes are general rules (role-flag names and bodies, `const { authorization } = req.headers`, optional auth when a token read always ends in `next()`, compound token names, more infrastructure packages, `expressValidator()` as an installer). **The "after fixes" column is on the same projects the fixes were made for, so it is no longer a blind number.** The original tuning set classifies exactly as before the fixes. + +Still unknown after the fixes (all infrastructure, low impact): a `cookie-session` parser reached through an app property (`app.sessionParser`), an inline HTTPS redirect, and a `memory-cache` wrapper. diff --git a/research/express-corpus/count-routes.mjs b/research/express-corpus/count-routes.mjs new file mode 100644 index 0000000..1ec5804 --- /dev/null +++ b/research/express-corpus/count-routes.mjs @@ -0,0 +1,50 @@ +#!/usr/bin/env node +// Approximate count of Express route registration sites, used as the denominator +// when measuring @kidkender/archmind-express-parser on a project: +// x.get('/path', ...) / x.post(`/path`, ...) → 1 per call with a path literal and a handler +// x.route('/path').get(...).post(...) → 1 per chained verb +// Skips node_modules, tests, build output and front-end folders. +// +// It is a regex count, so it over-counts HTTP client calls with the same shape +// (`axios.post('/x', data)`) and misses paths built at runtime. Differences +// against the parser are checked by hand (see README.md). +// +// node count-routes.mjs [ ...] +import { readdirSync, readFileSync, statSync } from "fs" +import { join, relative } from "path" + +const SKIP = new Set(["node_modules", "dist", "build", "coverage", ".git", "public", "client", "frontend", "test", "tests", "__tests__", "views"]) +const VERBS = "get|post|put|patch|delete|all|options|head" + +function files(dir, out = []) { + for (const e of readdirSync(dir)) { + if (SKIP.has(e) || e.startsWith(".")) continue + const p = join(dir, e) + if (statSync(p).isDirectory()) files(p, out) + else if (/\.(js|ts|mjs|cjs)$/.test(e) && !/\.(test|spec)\./.test(e) && !e.endsWith(".d.ts")) out.push(p) + } + return out +} + +for (const project of process.argv.slice(2)) { + let direct = 0 + let chained = 0 + const perFile = {} + for (const f of files(project)) { + const src = readFileSync(f, "utf-8") + const d = (src.match(new RegExp(`\\.(${VERBS})\\(\\s*['"\`][^'"\`]*['"\`]\\s*,`, "g")) ?? []).length + let c = 0 + for (const m of src.matchAll(/\.route\(\s*['"`][^'"`]*['"`]\s*\)/g)) { + // the chain runs until the statement ends (`;`) or the next `x.route(` / `x.use(` + const rest = src.slice(m.index + m[0].length) + const end = rest.search(/;|\n\s*\w+\.(route|use)\(/) + const chain = end === -1 ? rest : rest.slice(0, end) + c += (chain.match(new RegExp(`(^|\\n)\\s*\\.\\s*(${VERBS})\\(|\\)\\s*\\.\\s*(${VERBS})\\(|^\\s*\\.(${VERBS})\\(`, "g")) ?? []).length + } + if (d + c) perFile[relative(project, f).replace(/\\/g, "/")] = d + c + direct += d + chained += c + } + console.log(`${project.split(/[\\/]/).pop()}\t${direct + chained}\t(direct ${direct}, route-chain ${chained})`) + for (const [f, n] of Object.entries(perFile)) console.log(` ${n}\t${f}`) +} diff --git a/research/express-corpus/measure.mjs b/research/express-corpus/measure.mjs new file mode 100644 index 0000000..a244594 --- /dev/null +++ b/research/express-corpus/measure.mjs @@ -0,0 +1,64 @@ +#!/usr/bin/env node +// Runs the built express-parser (packages/express-parser/dist) on projects and +// prints what it found, for comparison with count-routes.mjs. +// +// node measure.mjs [ ...] [--routes] [--middleware] [--graph] +// +// (default) one line per project: routes found, unresolved paths, time +// --routes every route: method, path, middleware names, handler and its file:line +// --middleware how often each middleware name was classified as each kind +// --graph service calls, transactions and ownership nodes per route +// +// Build the parser first: npm run build -w packages/express-parser +import { pathToFileURL, fileURLToPath } from "url" +import { dirname, join } from "path" + +const here = dirname(fileURLToPath(import.meta.url)) +const parser = await import(pathToFileURL(join(here, "../../packages/express-parser/dist/index.js")).href) + +const args = process.argv.slice(2) +const flags = new Set(args.filter((a) => a.startsWith("--"))) +const projects = args.filter((a) => !a.startsWith("--")) + +for (const project of projects) { + const name = project.split(/[\\/]/).filter(Boolean).pop() + const root = parser.findExpressRoot(project) + if (!root) { + console.log(`${name}\tnot detected as Express`) + continue + } + const sources = parser.readSourceFiles(root) + const t0 = Date.now() + const { routes, unresolvedPaths } = parser.extractRoutes(parser.createExpressProject(sources)) + console.log(`${name}\troutes=${routes.length}\tunresolvedPaths=${unresolvedPaths.length}\t${Date.now() - t0}ms`) + + if (flags.has("--routes")) { + for (const r of routes) { + const mw = r.middleware.map((m) => m.name).join(",") + console.log(` ${r.method.padEnd(7)} ${r.path.padEnd(44)} [${mw}] -> ${r.handler.symbol} @${r.handler.file}:${r.handler.line}`) + } + for (const u of unresolvedPaths) console.log(` unresolved ${u.file}:${u.line} ${u.text}`) + } + + if (flags.has("--middleware")) { + const counts = new Map() + for (const r of routes) { + for (const m of r.middleware) { + const kinds = parser.classifyMiddleware(m).kinds + if (kinds.every((k) => k === "infrastructure" || k === "error_handler")) continue + const key = `${m.name}=${kinds.join("+")}` + counts.set(key, (counts.get(key) ?? 0) + 1) + } + } + for (const [key, n] of [...counts].sort((a, b) => b[1] - a[1])) console.log(` ${String(n).padStart(4)} ${key}`) + } + + if (flags.has("--graph")) { + for (const g of parser.parseExpressSources(sources)) { + const extra = g.nodes + .filter((n) => ["ir:service_call", "ir:txn_boundary", "ir:txn_write"].includes(n.type) || n.id === "ownership") + .map((n) => `${n.type.replace("ir:", "")}:${n.symbol}`) + if (extra.length) console.log(` ${g.entrypoint.padEnd(44)} ${extra.join(" ")}`) + } + } +}