Skip to content

feat: Express.js parser (@kidkender/archmind-express-parser) - #16

Closed
Kidkender wants to merge 7 commits into
fix/buildfrom
feat/express-parser
Closed

Kidkender wants to merge 7 commits into
fix/buildfrom
feat/express-parser

Conversation

@Kidkender

@Kidkender Kidkender commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

New @kidkender/archmind-express-parser (0.1.0) — Express.js, JavaScript and TypeScript — wired into analysis, the CLI and the MCP server.

Stacked on #12 (it needs the dependency-ordered build); this PR's base is fix/build, so the diff shows only the Express work. GitHub retargets it to main once fix/build merges.

What it extracts

  • Routes and mounts across files: require / module.exports, ES modules and re-exports, router.route() chains, routers mounted from arrays in a forEach, registrar functions handed the app, routers built in one expression. Paths that do not resolve to a string are reported, not guessed.
  • Middleware chain in Express order (global, path-scoped, per-router, per-route, arrays), classified by npm package, name and — for project middleware — body into ir:auth_gate, ir:authz_check, ir:validation_gate; rate limiting, optional auth and CSRF as ir:unknown_middleware with that role; body parsers, logging, CORS left out.
  • Handlers 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 as ir:txn_write; ownership from archmind.json.
  • Wiring: Express is detected after every other framework (and never below a root that is another backend); the MCP server caches graphs and re-parses on file changes; archmind_get_dependents indexes Express service calls.
  • analysis: a node with role rate_limiting now makes a route throttled (Express rate limiters, Laravel throttle:) — otherwise every rate-limited login route reported no_rate_limiting.

Measured

  • Six projects read while building it: 163 of 163 route registration sites.
  • Six projects it had not seen (measured once before any change for them): 101 of 101 real registrations (the regex also counted three HTTP client calls the parser correctly skips), every transaction-opening route of a production Sequelize app, and 9 of 15 security middleware classified correctly — 15 of 15 after general rule fixes made on that same set (no longer a blind number; the tuning set classifies exactly as before).
  • Cross-framework conformance: Express matches NestJS and Laravel on auth-only, auth-authz, auth-validation, auth-service-call and auth-transaction, and uses only IR node types and edge relations.
  • Full details, commits and the measuring scripts: research/express-corpus/README.md.

Limits

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. See packages/express-parser/README.md.

Verified

Clean worktree: npm ci, build (23 workspaces), npm test — all pass (retrieval's cross-framework suite failed once on the first run and passed on rerun; that flakiness is fixed in #13). express-parser 72 tests. End to end: archmind trace / archmind findings on the corpus projects.

Merge note

fix/minor-issues also adds a CHANGELOG [Unreleased] section at the same spot; whichever merges second needs the two combined.

New @kidkender/archmind-express-parser (0.1.0), JavaScript and TypeScript:

- detect: isExpressProject / findExpressRoot — package.json depends on
  express and not on NestJS, at the root or one directory down (server/,
  backend/); node_modules is never taken for the app.
- scanner: .js/.cjs/.mjs/.ts/.cts/.mts server files, `/`-separated, skipping
  tests, declarations, build output and front-end folders.
- project: an in-memory ts-morph project over those files; module resolution
  between files will be done by the extractors, so require() and ES imports
  are handled alike.
- adapter: parseExpressSources (synthetic fixtures) and parseExpressProjectAt
  (reads archmind.json guards and ownershipSources). Route extraction comes
  next; for now it returns no graphs.
- scope: finds where a name is declared by walking lexical scopes (variables,
  destructuring, parameters, functions, classes, ES imports, import = require).
- evaluator: demand-driven values for routing: apps and routers (express(),
  express.Router(), Router(), require('express').Router()), CommonJS and ES
  modules (module.exports, exports.x, export default, re-exports, ".js"
  specifiers for TS sources), string constants, concatenation and templates,
  objects, arrays, class statics and instances. A registrar parameter
  (require('./routes')(app)) takes the values passed at its call sites; a
  wrapper (catchAsync(fn), fn.bind(x)) stands for the function it wraps.
- routes: collects verb, route() chain and use() registrations, evaluates a
  forEach callback once per array element so each path stays with its router,
  expands mounts into full paths and builds each route's middleware chain in
  Express order (path-scoped use, arrays of middleware, parent middleware
  before a mount). Paths that do not resolve to a string are reported.
- graph: one IR graph per route, middleware (ir:unknown_middleware until
  classified) then the handler, linked by precedes.

On the six corpus repos used to build it: 163 of 163 route registration sites
found (regex count), 2 static-file paths from a Map loop reported unresolved.
…d validation

classifyMiddleware decides, in order: archmind.json guards; (err, req, res,
next) error handlers; optional auth (auth.optional, credentialsRequired:
false), which blocks nothing; the npm package behind the value (passport,
express-jwt, celebrate, express-validator, express-rate-limit, csurf, helmet,
cors, body parsers, ...); the name (checkJwt, checkRole, isAdmin, validate*,
*Limiter; auth(...)/authorize(...) with roles is both an auth gate and an
authorization check); and for project middleware the body (jwt.verify or the
authorization header → auth; a role/permission check that answers 401/403 →
authorization; csrf; a middleware that never stops the request →
infrastructure).

Graphs now carry ir:auth_gate, ir:authz_check and ir:validation_gate; rate
limiting, optional auth and CSRF are ir:unknown_middleware with that role (no
IR type yet); infrastructure and error handlers are left out.

The evaluator records calls to package members (externalCall), so
`const limiter = rateLimit()` and `body("email").isEmail()` keep their package;
a method chain is named after the call it starts from.
…handler bodies

analyzeHandler reads the handler function:
- service calls: calls into project functions in service-like files
  (service, repository, provider, model, ...) or methods reached through a
  module, object or instance become ir:service_call nodes (ir:calls from the
  handler, at most 15); utilities, helpers in the handler's own file and
  req/res/next calls are left out.
- transactions, in the handler or one call below it: $transaction,
  withTransaction, startTransaction, and x.transaction(...) when x is a
  database handle by name or comes from an ORM package (sequelize, typeorm,
  knex, mongoose, prisma, ...).
- ownership: a call to a configured ownership source → ir:authz_check
  "ownership:<name>", as in the Go adapter.

Ownership and the transaction follow the handler in the precedes chain.

The evaluator resolves `this` in class methods, constructor parameter
properties, `this.x = ...` in constructors, typed properties and base
classes, so class controllers reach their services.
- analysis: NestJS → Spring Boot → Gin → Express → Laravel; analyzeExpress.
  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 —
  otherwise every rate-limited login route reported no_rate_limiting.
- CLI: framework "express", detected after every other signal; parseProject
  branch.
- MCP: detectFramework recognises Express (not when artisan is present);
  getGraphs caches Express graphs and re-parses when a JS/TS file changes
  (mtime, as for Go); tool descriptions name Express; get_dependents indexes
  Express service calls.
- analysis, CLI and MCP depend on express-parser and keep it external in
  their bundles.

express-parser:
- does not look below a root that is another backend (artisan, composer.json,
  go.mod, pom.xml, build.gradle, nest-cli.json), so a Laravel app with a Node
  server in server/ stays Laravel;
- reports node files relative to the project root when the app is one
  directory down;
- service symbols use Owner::method ("userService::createUser");
- an auth factory split into auth gate + authorization check carries its
  roles on the authorization node only (duplicate_authorization fired on
  every auth("perm") route).
…sactions

- research/cross-framework: Express versions of auth-only, auth-authz,
  auth-validation, auth-service-call and auth-transaction.
- cross-framework.test: for each pattern Express emits the expected semantic
  node types, matches NestJS and Laravel on the security layers plus the
  pattern's own concern, and uses only IR node types and edge relations.
  Not covered for Express: side effects, API resources, cron.
- Transactions now carry their writes as ir:txn_write (Entity::operation,
  linked by ir:wraps): TypeORM manager.save(Order, ...), Sequelize/Mongoose
  Order.create(...), Prisma tx.order.create(...) and the array form, and for
  an unmanaged transaction the calls in the same function that pass it
  ({ transaction: t } / { session }).
- Fix two regexes in handler.ts whose \b had been written as a backspace
  character (unmanaged-transaction option, and repo\b in the service path).
…ion, document

Measured on six projects not read before (research/express-corpus): 101 of 101
real route registrations, every route that opens a transaction in a production
Sequelize app, and 9 of 15 security middleware classified correctly blind.
Rules fixed from that (general, not per-project):

- authorization: role names with a User suffix (isAdminUser, isSuperUser) and
  bodies that read role flags off the user (req.user.isSuperUser) and answer
  403;
- authentication: `const { authorization } = req.headers`, "Bearer ", compound
  names (verifyAuthToken, checkAccessToken); a token read that always ends in
  next() with no top-level exit is optional auth, not a gate;
- infrastructure: express-ejs-layouts, express-status-monitor, nocache,
  cookie-session; old-style expressValidator() installs, body()/check()
  validate;
- transactions and ownership are looked for in every project function the
  handler calls, including helpers in the route file (only service-like ones
  become service-call nodes).

After the fixes: 15 of 15 security middleware on that set (no longer blind);
the tuning set classifies exactly as before.

Docs: packages/express-parser/README.md; research/express-corpus with the
projects, commits, method, results and the two measuring scripts; root README
and CHANGELOG (Unreleased).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant