From c3bcd759c4a96764ae8aaf99d6a65aa8c375b91d Mon Sep 17 00:00:00 2001 From: kidkender Date: Tue, 10 Nov 2026 16:12:53 +0700 Subject: [PATCH 01/25] fix(cli,nestjs): honor ignoreFindings in visualize and share the config reader - `archmind visualize` passed no options to explain(), so finding types listed in archmind.json `ignoreFindings` still appeared in the HTML report. It now reads the config and passes `{ ignore }`, like `archmind findings`. - nestjs-parser drops its private copy of loadUserConfig and uses the one in @kidkender/archmind-protocol (same behavior); requires protocol ^0.5.1. --- apps/cli/src/commands/visualize.ts | 13 ++++++++----- package-lock.json | 2 +- packages/nestjs-parser/package.json | 2 +- packages/nestjs-parser/src/adapter.ts | 15 ++------------- 4 files changed, 12 insertions(+), 20 deletions(-) diff --git a/apps/cli/src/commands/visualize.ts b/apps/cli/src/commands/visualize.ts index 6587e26..00778e0 100644 --- a/apps/cli/src/commands/visualize.ts +++ b/apps/cli/src/commands/visualize.ts @@ -2,18 +2,20 @@ import { writeFileSync } from "fs" import { join, resolve } from "path" import { execSync } from "child_process" import type { IntermediateExecutionGraph, ExecutionNode } from "@kidkender/archmind-protocol" -import { IR_NODE_TYPES, toIRNodeType } from "@kidkender/archmind-protocol" +import { IR_NODE_TYPES, toIRNodeType, loadUserConfig } from "@kidkender/archmind-protocol" import { parseProject, requireProject } from "../utils/parse-project.js" // --------------------------------------------------------------------------- // Lazy import explainer (optional dep — visualize still works without findings) // --------------------------------------------------------------------------- -function tryExplain(graph: IntermediateExecutionGraph): Finding[] { +function tryExplain(graph: IntermediateExecutionGraph, ignore?: string[]): Finding[] { try { // eslint-disable-next-line @typescript-eslint/no-require-imports - const { explain } = require("@kidkender/archmind-explainer") as { explain: (g: IntermediateExecutionGraph) => Finding[] } - return explain(graph) + const { explain } = require("@kidkender/archmind-explainer") as { + explain: (g: IntermediateExecutionGraph, query?: string, opts?: { ignore?: string[] }) => Finding[] + } + return explain(graph, undefined, { ignore }) } catch { return [] } @@ -510,11 +512,12 @@ export async function runVisualize(flags: Record): Promise const { graphs, routeCount } = parseProject(projectRoot) console.log(`Parsed ${routeCount} routes`) + const ignore = loadUserConfig(projectRoot)?.ignoreFindings const routes: RouteData[] = [] let criticalTotal = 0 for (const graph of graphs) { - const findings = tryExplain(graph) + const findings = tryExplain(graph, ignore) const route = buildRouteData(graph, findings) routes.push(route) criticalTotal += route.criticalCount diff --git a/package-lock.json b/package-lock.json index cb74b89..a64cd55 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6490,7 +6490,7 @@ "version": "0.7.1", "license": "MIT", "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.5.1", "js-yaml": "^4.3.2", "ts-morph": "^23.0.0" }, diff --git a/packages/nestjs-parser/package.json b/packages/nestjs-parser/package.json index f5a3753..968a782 100644 --- a/packages/nestjs-parser/package.json +++ b/packages/nestjs-parser/package.json @@ -36,7 +36,7 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.5.1", "js-yaml": "^4.3.2", "ts-morph": "^23.0.0" }, diff --git a/packages/nestjs-parser/src/adapter.ts b/packages/nestjs-parser/src/adapter.ts index 401437d..48a1667 100644 --- a/packages/nestjs-parser/src/adapter.ts +++ b/packages/nestjs-parser/src/adapter.ts @@ -1,6 +1,5 @@ -import { existsSync, readFileSync } from "fs" -import { join } from "path" -import type { IntermediateExecutionGraph, ArchMindUserConfig } from "@kidkender/archmind-protocol" +import { loadUserConfig } from "@kidkender/archmind-protocol" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" import type { SemanticAdapter } from "@kidkender/archmind-protocol" import type { Project } from "ts-morph" import { extractRoutes } from "./extractors/route.extractor.js" @@ -13,16 +12,6 @@ import type { NestJSSemanticRoute } from "./types.js" import type { GuardDescriptor } from "./types.js" import type { DTOSchema } from "@kidkender/archmind-protocol" -function loadUserConfig(projectRoot: string): ArchMindUserConfig | undefined { - const configPath = join(projectRoot, "archmind.json") - if (!existsSync(configPath)) return undefined - try { - return JSON.parse(readFileSync(configPath, "utf-8")) as ArchMindUserConfig - } catch { - return undefined - } -} - export class NestJSAdapter implements SemanticAdapter { parseProject(root: string): IntermediateExecutionGraph[] { const userConfig = loadUserConfig(root) From 8a90e63280f53e98e17c911a0d258cbb932587ae Mon Sep 17 00:00:00 2001 From: kidkender Date: Tue, 10 Nov 2026 16:12:53 +0700 Subject: [PATCH 02/25] feat(springboot-parser): read archmind.json guards for project annotations The Spring Boot adapter never loaded archmind.json, so `guards` had no effect on Spring Boot projects. It now reads the config through loadUserConfig: annotation names under `guards.auth_gate` emit ir:auth_gate, names under `guards.authz_check` emit ir:auth_gate -> ir:authz_check. The config wins over the built-in rules, so a listed Shiro `@RequiresRoles` is no longer ir:unknown_middleware. A malformed archmind.json is ignored. Requires protocol ^0.5.1. docs: bring next-version-ideas.md in line with v0.9.1 (benchmark CLI, graph diff, CI and lens shipped; modular Laravel partial; new items #10 and #11; reordered priorities). --- docs/next-version-ideas.md | 50 ++++++++--- package-lock.json | 2 +- packages/springboot-parser/README.md | 5 ++ .../__tests__/adapter-user-config.test.ts | 89 +++++++++++++++++++ packages/springboot-parser/package.json | 2 +- packages/springboot-parser/src/adapter.ts | 5 +- .../src/controller-parser.ts | 18 +++- packages/springboot-parser/src/ir-emitter.ts | 1 + packages/springboot-parser/src/types.ts | 4 +- 9 files changed, 159 insertions(+), 17 deletions(-) create mode 100644 packages/springboot-parser/__tests__/adapter-user-config.test.ts diff --git a/docs/next-version-ideas.md b/docs/next-version-ideas.md index 6316fac..88ddb7c 100644 --- a/docs/next-version-ideas.md +++ b/docs/next-version-ideas.md @@ -2,6 +2,7 @@ > Generated: 2026-06-30 > Updated: 2026-07-03 — after v0.5.0 shipped (Spring Boot parser, AQL, Architecture Constraints, AI Context API, `archmind visualize`) +> Updated: 2026-11-10 — statuses checked against the code at v0.9.1 --- @@ -13,6 +14,10 @@ - ✅ **AI Context API** (`@kidkender/archmind-context`) — `buildSemanticContext()`, exposed via `archmind_get_context` MCP tool - ✅ **`archmind visualize`** — Execution Timeline HTML report - ✅ **Framework #4: Go/Gin** (`@kidkender/archmind-go-parser`, v0.8.x) — route, auth-gate (including runtime skip-lists), authz-check, validation-gate, and GORM transaction-boundary detection for Gin projects. Isolation/tenant scoping is not implemented yet. +- ✅ **`@kidkender/archmind-lens`** (v0.9.0–0.9.1) — Go symbol-to-entry-point call graph, exposed as MCP `archmind_symbol_context`. +- ✅ **Benchmark CLI (#2)** — `archmind benchmark` (`apps/cli/src/commands/benchmark.ts`) reads the pain specs and scores node/edge recall. +- ✅ **Graph Diff for PR review (#1)** — `archmind diff --format markdown` plus the sticky-comment workflow in `docs/ci-templates/topology-guard.yml`. +- ✅ **CI** — `.github/workflows/ci.yml` builds and tests on every push and PR to `main`. These shipped features open up new follow-on ideas below (#5, #7) that weren't possible before. @@ -22,7 +27,7 @@ These shipped features open up new follow-on ideas below (#5, #7) that weren't p **Priority:** High impact, feasible **Effort:** Medium -**Status:** Not started +**Status:** ✅ Done — `archmind diff --format markdown` + `docs/ci-templates/topology-guard.yml` (sticky PR comment) Hiện tại CI chỉ fail/pass. Next step là sinh ra **PR comment** mô tả chính xác cái gì thay đổi trong execution graph — không phải diff code mà diff topology. @@ -48,7 +53,7 @@ PR #42 — Execution Graph Changes **Priority:** High value, low effort (corpus đã có) **Effort:** Low -**Status:** Not started +**Status:** ✅ Done — `archmind benchmark` (`apps/cli/src/commands/benchmark.ts`). Still open: running it in CI on every PR. `research/semantic-pains` đã có 4 test cases với format đầy đủ, nhưng `duck benchmark run` chưa implement. Đây là low-hanging fruit để tự validate và publish kết quả công khai. @@ -176,7 +181,7 @@ archmind serve --project . --port 4000 **Priority:** Medium — real gap found via cross-repo benchmarking, not yet scoped into any plan **Effort:** Medium -**Status:** Not started +**Status:** Partial — `route-parser.ts` resolves module-style route namespaces; `project-config.ts` has no `modules/` handling and akaunting has not been re-measured Benchmarked against akaunting (642 routes) as a fresh, previously-unseen repo — archMind parsed cleanly (no crashes) but stayed almost silent (6/58 auth-gate/unknown-middleware nodes, 0 service_call/guard/txn/branch nodes despite 642 routes). Root cause: akaunting is a modular Laravel app (`nwidart/laravel-modules` or similar) — real controllers live under `modules/*/Http/Controllers/`, not `app/Http/Controllers/` as the parser assumes. This is a distinct architecture gap from the 6 gaps already fixed for IR v1.5 (koel/BookStack-driven), confirmed independently on invoiceninja and monica (both generalized cleanly with zero changes). @@ -202,7 +207,29 @@ Every parser module still wraps its `_parser.parse()` call in a bare `catch { re **Remaining deliverable:** - Replace the blanket `catch { return emptyDefaults }` in each parser module with a narrower catch (file-not-found only) so a genuine future parse failure surfaces loudly instead of reading as "no findings" — not done yet; the `maxWorkers` fix removed the trigger but the swallow-everything pattern itself is still there -**Why:** This is very likely *why* there's no CI on this repo at all — a red/green result that changes every run isn't a gate anyone can trust. +**Why:** This is very likely *why* there's no CI on this repo at all — a red/green result that changes every run isn't a gate anyone can trust. (CI now exists: `.github/workflows/ci.yml`.) + +Count at v0.9.1 of bare `catch {` in parser sources (tests excluded): laravel 36, nestjs 18, springboot 13, go 4. Not all of them wrap a parse; the ones that read a file and parse it in one `try` (e.g. `laravel-parser/src/controller-parser.ts`) are the target. + +--- + +## 10. Spring Boot does not read `archmind.json` + +**Priority:** Medium +**Effort:** Low +**Status:** ✅ Done (2026-11-10) — the adapter reads `archmind.json`; `guards.auth_gate` / `guards.authz_check` classify the project's own annotation names. `ownershipSources` stays Go-only. + +`springboot-parser` never loaded the user config, so `guards`, `authorization.ownershipSources` and the other adapter-level settings have no effect on Spring Boot projects (`ignoreFindings` still works, because `analysis`, the CLI and the MCP server apply it). Wire `loadUserConfig` from `@kidkender/archmind-protocol` into the adapter, as the Go and NestJS adapters do. + +--- + +## 11. Gin layouts still missed by go-parser + +**Priority:** Medium +**Effort:** Medium +**Status:** Open + +After 0.3.0: `gin-vue-admin` ~201/250 routes, `go-admin` 99/109. Patterns from the 0.8.2 spot-check still not handled: engine held in a struct field and mutated by a receiver method, engine wrapped in a custom type with its own `.GET()`/`.POST()`, functional-options chains, Wire-style DI. Lens limits: embedded interfaces, two types with the same name in different packages. --- @@ -210,12 +237,15 @@ Every parser module still wraps its `_parser.parse()` call in a bare `catch { re | Idea | Impact | Effort | Recommended Order | |------|--------|--------|-------------------| -| Tree-sitter flaky tests (#9) | Critical | Low (one deliverable left) | **1st** — narrow the remaining swallow-catch | -| AQL/Constraints in CI (#5) | High | Low-Medium | **2nd** — reuses shipped engine | -| Benchmark CLI (#2) | High | Low | **3rd** | -| Graph Diff PR Comment (#1) | High | Medium | **4th** | -| Modular Laravel support (#8) | Medium | Medium | **5th** | +| Narrow swallow-catch in parsers (#9) | High | Low-Medium | **1st** | +| Go tenant scoping | Medium | Medium | **3rd** | +| Remaining Gin layouts + lens limits (#11) | Medium | Medium | **4th** | +| Modular Laravel support (#8, partial) | Medium | Medium | **5th** | | Auto-fix Suggestions (#4) | Medium | Medium | **6th** | -| Framework #5 + adapter kit (#3) | High | High | **7th** — next new framework beyond Go | +| Framework #5 + adapter kit (#3) | High | High | **7th** | | Web UI Visualizer (#6) | Medium | High | **8th** | | OTel Runtime Expansion (#7) | High | High | **9th** | +| ~~AQL/Constraints in CI (#5)~~ | | | Done | +| ~~Benchmark CLI (#2)~~ | | | Done | +| ~~Graph Diff PR Comment (#1)~~ | | | Done | +| ~~Spring Boot reads `archmind.json` (#10)~~ | | | Done | diff --git a/package-lock.json b/package-lock.json index a64cd55..89be1e3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6632,7 +6632,7 @@ "version": "0.4.0", "license": "MIT", "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.5.1", "tree-sitter": "^0.21.0", "tree-sitter-java": "^0.23.5" }, diff --git a/packages/springboot-parser/README.md b/packages/springboot-parser/README.md index 12225cd..3839fe2 100644 --- a/packages/springboot-parser/README.md +++ b/packages/springboot-parser/README.md @@ -66,6 +66,11 @@ const methods = parseControllerFile("/path/to/OrderController.java") ### Security - **Per-method annotations:** `@PreAuthorize`, `@Secured`, `@RolesAllowed` +- **Project-specific annotations from `archmind.json`:** names listed under `guards.auth_gate` become `ir:auth_gate`; names under `guards.authz_check` become `ir:auth_gate` → `ir:authz_check`. They take precedence over the built-in rules, so a known-but-unclassified annotation such as Shiro's `@RequiresRoles` stops being `ir:unknown_middleware` once it is listed: + + ```json + { "guards": { "auth_gate": ["RequireLogin"], "authz_check": ["RequiresRoles", "CheckPermission"] } } + ``` - **Global `SecurityFilterChain` rules:** parses `requestMatchers().hasRole()` / `hasAnyRole()` / `permitAll()` / `denyAll()` chains and applies them to matching routes automatically ### Validation diff --git a/packages/springboot-parser/__tests__/adapter-user-config.test.ts b/packages/springboot-parser/__tests__/adapter-user-config.test.ts new file mode 100644 index 0000000..70f18d2 --- /dev/null +++ b/packages/springboot-parser/__tests__/adapter-user-config.test.ts @@ -0,0 +1,89 @@ +import { mkdtempSync, writeFileSync, rmSync } from "fs" +import { tmpdir } from "os" +import { join } from "path" +import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" +import { parseSpringBootProject } from "../src/adapter.js" + +const CONTROLLER = ` + package com.example.web; + import org.springframework.web.bind.annotation.*; + + @RestController + @RequestMapping("/api/orders") + public class OrderController { + @RequireLogin + @GetMapping + public String list() { return "ok"; } + + @RequiresRoles("admin") + @DeleteMapping("/{id}") + public void remove(@PathVariable Long id) { } + + @TeamOnly + @PostMapping + public void create(@RequestBody String body) { } + } +` + +function nodeTypes(graphs: ReturnType, method: string): string[] { + const g = graphs.find((x) => x.method === method) + if (!g) throw new Error(`no graph for ${method}`) + return g.nodes.map((n) => n.type) +} + +describe("parseSpringBootProject — archmind.json guards", () => { + let dir: string + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "archmind-sb-config-")) + writeFileSync(join(dir, "OrderController.java"), CONTROLLER) + }) + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }) + }) + + test("without archmind.json, known-but-unclassified annotations stay ir:unknown_middleware", () => { + const graphs = parseSpringBootProject(dir) + + expect(nodeTypes(graphs, "GET")).toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + expect(nodeTypes(graphs, "DELETE")).toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + // @TeamOnly is not a recognised name at all + expect(nodeTypes(graphs, "POST")).not.toContain(IR_NODE_TYPES.AUTH_GATE) + expect(nodeTypes(graphs, "POST")).not.toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + }) + + test("guards.auth_gate and guards.authz_check classify the project's own annotations", () => { + writeFileSync(join(dir, "archmind.json"), JSON.stringify({ + guards: { auth_gate: ["RequireLogin"], authz_check: ["RequiresRoles", "TeamOnly"] }, + })) + + const graphs = parseSpringBootProject(dir) + + const get = nodeTypes(graphs, "GET") + expect(get).toContain(IR_NODE_TYPES.AUTH_GATE) + expect(get).not.toContain(IR_NODE_TYPES.AUTHZ_CHECK) + expect(get).not.toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + + const del = nodeTypes(graphs, "DELETE") + expect(del).toContain(IR_NODE_TYPES.AUTH_GATE) + expect(del).toContain(IR_NODE_TYPES.AUTHZ_CHECK) + expect(del).not.toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + + const post = nodeTypes(graphs, "POST") + expect(post).toContain(IR_NODE_TYPES.AUTH_GATE) + expect(post).toContain(IR_NODE_TYPES.AUTHZ_CHECK) + + const authz = graphs.find((g) => g.method === "DELETE")!.nodes + .find((n) => n.type === IR_NODE_TYPES.AUTHZ_CHECK)! + expect(authz.symbol).toBe(`@RequiresRoles(admin)`) + }) + + test("a malformed archmind.json is ignored", () => { + writeFileSync(join(dir, "archmind.json"), "{ not json") + + const graphs = parseSpringBootProject(dir) + + expect(nodeTypes(graphs, "GET")).toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + }) +}) diff --git a/packages/springboot-parser/package.json b/packages/springboot-parser/package.json index 8c6d7f3..bfe0a4f 100644 --- a/packages/springboot-parser/package.json +++ b/packages/springboot-parser/package.json @@ -22,7 +22,7 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.5.1", "tree-sitter": "^0.21.0", "tree-sitter-java": "^0.23.5" }, diff --git a/packages/springboot-parser/src/adapter.ts b/packages/springboot-parser/src/adapter.ts index 1438c05..c364239 100644 --- a/packages/springboot-parser/src/adapter.ts +++ b/packages/springboot-parser/src/adapter.ts @@ -1,7 +1,7 @@ import { randomUUID } from "crypto" import type { IntermediateExecutionGraph, ExecutionNode, ExecutionEdge } from "@kidkender/archmind-protocol" import type { SemanticAdapter } from "@kidkender/archmind-protocol" -import { IR_NODE_TYPES, IR_EDGE_RELATIONS, IR_VERSION } from "@kidkender/archmind-protocol" +import { IR_NODE_TYPES, IR_EDGE_RELATIONS, IR_VERSION, loadUserConfig } from "@kidkender/archmind-protocol" import { findJavaFiles, isEntrypointFile } from "./scanner.js" import { parseControllerFile } from "./controller-parser.js" import { emitGraph } from "./ir-emitter.js" @@ -11,6 +11,7 @@ import { buildServiceTransactionIndex, type ServiceTransactionIndex } from "./se export class SpringBootAdapter implements SemanticAdapter { parseProject(root: string): IntermediateExecutionGraph[] { + const userConfig = loadUserConfig(root) const allFiles = findJavaFiles(root) const controllerFiles = allFiles.filter(isEntrypointFile) @@ -23,7 +24,7 @@ export class SpringBootAdapter implements SemanticAdapter { for (const file of controllerFiles) { try { - const methods = parseControllerFile(file, baseClassIndex) + const methods = parseControllerFile(file, baseClassIndex, userConfig) const controllerModule = moduleRootOf(file) for (const m of methods) { const graph = emitGraph(m, root) diff --git a/packages/springboot-parser/src/controller-parser.ts b/packages/springboot-parser/src/controller-parser.ts index 819eac9..20eda29 100644 --- a/packages/springboot-parser/src/controller-parser.ts +++ b/packages/springboot-parser/src/controller-parser.ts @@ -2,6 +2,7 @@ import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import Java from "tree-sitter-java" +import type { ArchMindUserConfig } from "@kidkender/archmind-protocol" import { moduleRootOf } from "./security-config-parser.js" import type { SpringControllerMethod, AuthAnnotation, ServiceCall, DataAccessCall, EventPublication, HttpMethod, @@ -55,6 +56,7 @@ const MESSAGING_LISTENER_ANNS: Record = { export function parseControllerFile( filePath: string, baseClassIndex?: Map, + userConfig?: ArchMindUserConfig, ): SpringControllerMethod[] { let source: string try { @@ -131,7 +133,7 @@ export function parseControllerFile( const methodTxn = classTxn || hasAnnotation(mods, new Set(["Transactional"])) const readOnly = isReadOnlyTxn(mods) - const authAnnotations = extractAuthAnnotations(mods) + const authAnnotations = extractAuthAnnotations(mods, userConfig) const { hasValidation, validatedParamTypes } = extractValidationInfo(methodNode) const body = methodNode.childForFieldName("body") ?? @@ -365,13 +367,25 @@ const UNKNOWN_SECURITY_ANN_NAMES = new Set([ "CheckPermission", // common custom naming ]) -function extractAuthAnnotations(modifiers: Parser.SyntaxNode): AuthAnnotation[] { +function extractAuthAnnotations(modifiers: Parser.SyntaxNode, userConfig?: ArchMindUserConfig): AuthAnnotation[] { const out: AuthAnnotation[] = [] + const customAuthGate = userConfig?.guards?.auth_gate + const customAuthzCheck = userConfig?.guards?.authz_check for (const child of modifiers.children) { if (child.type !== "annotation" && child.type !== "marker_annotation") continue const name = getAnnotationName(child) if (!name) continue + // archmind.json `guards` names the project's own security annotations. + // The project knows their meaning, so this wins over the built-in rules. + const isCustomAuthz = customAuthzCheck?.includes(name) ?? false + const isCustomAuth = !isCustomAuthz && (customAuthGate?.includes(name) ?? false) + if (isCustomAuthz || isCustomAuth) { + const expr = getAnnotationStringArg(child) ?? "" + out.push({ kind: "custom", expression: `@${name}${expr ? `(${expr})` : ""}`, isAuthOnly: isCustomAuth }) + continue + } + if (name === "PreAuthorize") { const expr = getAnnotationStringArg(child) ?? "" const isAuthOnly = /^\s*isAuthenticated\(\)\s*$/.test(expr) || diff --git a/packages/springboot-parser/src/ir-emitter.ts b/packages/springboot-parser/src/ir-emitter.ts index ede05ea..015f491 100644 --- a/packages/springboot-parser/src/ir-emitter.ts +++ b/packages/springboot-parser/src/ir-emitter.ts @@ -230,5 +230,6 @@ function formatAuthSymbol(ann: AuthAnnotation): string { case "rolesAllowed": return `@RolesAllowed("${ann.expression}")` // "unknown" is handled earlier (emitted as ir:unknown_middleware) and never reaches here. case "unknown": return ann.expression + case "custom": return ann.expression } } diff --git a/packages/springboot-parser/src/types.ts b/packages/springboot-parser/src/types.ts index 55defc9..0c55f29 100644 --- a/packages/springboot-parser/src/types.ts +++ b/packages/springboot-parser/src/types.ts @@ -11,7 +11,9 @@ export interface AuthAnnotation { // as ir:unknown_middleware instead of a guessed auth_gate/authz_check so the // LLM sees "there IS a security signal here, but I can't tell you its shape" // rather than silently reading it as no-auth. - kind: "preAuthorize" | "secured" | "rolesAllowed" | "unknown" + // "custom" = an annotation the project named in archmind.json `guards` + // (auth_gate → isAuthOnly true, authz_check → isAuthOnly false). + kind: "preAuthorize" | "secured" | "rolesAllowed" | "unknown" | "custom" expression: string // raw annotation value, e.g. "hasRole('ADMIN')" isAuthOnly: boolean // true when the expression only checks isAuthenticated() } From 27a0dde83e76691d8282432c432042590b70c545 Mon Sep 17 00:00:00 2001 From: kidkender Date: Tue, 10 Nov 2026 16:21:19 +0700 Subject: [PATCH 03/25] fix(laravel-parser,springboot-parser): report parse failures and parse files over 32 KiB Every parser wrapped readFileSync and tree-sitter's parse() in one bare `catch { return }`, so a parse failure read as "this file has nothing in it". That also hid a real bug: tree-sitter 0.21 throws "Invalid argument" for input past its default 32 KiB buffer, and only route-parser passed a bufferSize, so controllers and services larger than 32 KiB silently produced no auth, transaction, isolation or guard nodes. All read+parse sites now go through php-source.ts / java-source.ts: - an unreadable file (missing, a directory, no access) yields nothing, as before - the parse buffer is sized to the source - a parse failure is printed on stderr with the file path and the file is skipped Catches around JSON.parse of composer.json / archmind.json and readdirSync are unchanged. The pass-level catches in graph-augmenter.ts are left for later. --- docs/next-version-ideas.md | 4 +- .../src/__tests__/php-source.test.ts | 80 +++++++++++++++++++ .../laravel-parser/src/audit-log-parser.ts | 13 +-- .../laravel-parser/src/bootstrap-parser.ts | 13 +-- .../laravel-parser/src/constant-resolver.ts | 13 +-- .../laravel-parser/src/controller-parser.ts | 35 +++----- .../src/event-listener-mapper.ts | 12 +-- .../laravel-parser/src/guard-clause-parser.ts | 13 +-- .../laravel-parser/src/isolation-parser.ts | 13 +-- packages/laravel-parser/src/kernel-parser.ts | 24 ++---- packages/laravel-parser/src/php-source.ts | 45 +++++++++++ .../laravel-parser/src/queue-job-parser.ts | 17 ++-- .../laravel-parser/src/resource-parser.ts | 13 +-- packages/laravel-parser/src/route-parser.ts | 15 +--- .../src/route-service-provider-parser.ts | 13 +-- .../laravel-parser/src/schedule-parser.ts | 13 +-- .../laravel-parser/src/transaction-parser.ts | 13 +-- .../__tests__/java-source.test.ts | 52 ++++++++++++ .../src/controller-parser.ts | 18 +---- packages/springboot-parser/src/java-source.ts | 45 +++++++++++ .../src/service-transaction-index.ts | 18 ++--- 21 files changed, 299 insertions(+), 183 deletions(-) create mode 100644 packages/laravel-parser/src/__tests__/php-source.test.ts create mode 100644 packages/laravel-parser/src/php-source.ts create mode 100644 packages/springboot-parser/__tests__/java-source.test.ts create mode 100644 packages/springboot-parser/src/java-source.ts diff --git a/docs/next-version-ideas.md b/docs/next-version-ideas.md index 88ddb7c..fa55f74 100644 --- a/docs/next-version-ideas.md +++ b/docs/next-version-ideas.md @@ -198,7 +198,7 @@ Benchmarked against akaunting (642 routes) as a fresh, previously-unseen repo **Priority:** High — undermines trust in the whole test suite and any CI built on top of it **Effort:** Medium -**Status:** Root cause corrected + primary fix shipped 2026-09-03 (branch `fix/retrieval-flaky-tests-ci`); one deliverable still open +**Status:** ✅ Done (2026-11-10) for laravel-parser and springboot-parser — read+parse sites go through `php-source.ts` / `java-source.ts`: an unreadable file yields nothing, a parse failure is printed on stderr with the file path and the file is skipped. This also fixed files over 32 KiB (tree-sitter 0.21 throws "Invalid argument" past its default buffer; only `route-parser.ts` passed `bufferSize`, so every other parser silently returned nothing for large controllers and services). Still open: the broad `catch { /* skip */ }` around whole passes in `graph-augmenter.ts`. Initial hypothesis (below, kept for record) was a `tree-sitter@^0.21.0` / `tree-sitter-php@^0.23.12` ABI skew. **That was wrong** — disproved empirically: a plain-Node script reusing the same `Parser` singleton for 500 heavy parses in a row had zero failures. The real cause: Jest reuses one worker *process* across multiple test files in the same package; each file re-imports that package's module-level `new Parser()` singleton, and repeatedly re-loading the native tree-sitter addon into the same process is what makes `_parser.parse(source)` intermittently throw — not the grammar/core version pairing itself. Confirmed by setting `maxWorkers` high enough (in `laravel-parser`'s and `springboot-parser`'s `jest.config.js`) that every test file always gets its own process: 5/5 and then 3/3 repeated full-suite runs came back completely clean, both isolated and via `npm test`. @@ -237,7 +237,6 @@ After 0.3.0: `gin-vue-admin` ~201/250 routes, `go-admin` 99/109. Patterns from t | Idea | Impact | Effort | Recommended Order | |------|--------|--------|-------------------| -| Narrow swallow-catch in parsers (#9) | High | Low-Medium | **1st** | | Go tenant scoping | Medium | Medium | **3rd** | | Remaining Gin layouts + lens limits (#11) | Medium | Medium | **4th** | | Modular Laravel support (#8, partial) | Medium | Medium | **5th** | @@ -249,3 +248,4 @@ After 0.3.0: `gin-vue-admin` ~201/250 routes, `go-admin` 99/109. Patterns from t | ~~Benchmark CLI (#2)~~ | | | Done | | ~~Graph Diff PR Comment (#1)~~ | | | Done | | ~~Spring Boot reads `archmind.json` (#10)~~ | | | Done | +| ~~Narrow swallow-catch in parsers (#9)~~ | | | Done (graph-augmenter pass-level catches remain) | diff --git a/packages/laravel-parser/src/__tests__/php-source.test.ts b/packages/laravel-parser/src/__tests__/php-source.test.ts new file mode 100644 index 0000000..29ea882 --- /dev/null +++ b/packages/laravel-parser/src/__tests__/php-source.test.ts @@ -0,0 +1,80 @@ +import { describe, test, expect, jest, beforeEach, afterEach } from "@jest/globals" +import { mkdtempSync, writeFileSync, rmSync } from "fs" +import { tmpdir } from "os" +import { join } from "path" +import type Parser from "tree-sitter" +import { parseOptionsFor, parseSource, parsePhpFile } from "../php-source.js" +import { parseTransactions } from "../transaction-parser.js" + +// A controller well past tree-sitter 0.21's default 32 KiB parse buffer: the +// transaction sits after ~40 KB of filler methods. +function largeController(): string { + const filler = Array.from({ length: 400 }, (_, i) => + ` public function helper${i}()\n {\n return ['key${i}' => 'value value value value value value value value value'];\n }\n`, + ).join("\n") + return ` { + let dir: string + let warn: ReturnType + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "archmind-php-source-")) + warn = jest.spyOn(console, "warn").mockImplementation(() => {}) + }) + + afterEach(() => { + warn.mockRestore() + rmSync(dir, { recursive: true, force: true }) + }) + + test("sizes the parse buffer only for sources of 32 KiB or more", () => { + expect(parseOptionsFor(" { + const source = largeController() + expect(source.length).toBeGreaterThan(32 * 1024) + const file = join(dir, "BigController.php") + writeFileSync(file, source) + + const result = parseTransactions(file, "store") + + expect(result.hasTransaction).toBe(true) + expect(warn).not.toHaveBeenCalled() + }) + + test("a missing file yields null without a warning", () => { + const fakeParser = { parse: () => { throw new Error("should not be called") } } as unknown as Parser + expect(parsePhpFile(fakeParser, join(dir, "Missing.php"))).toBeNull() + expect(warn).not.toHaveBeenCalled() + }) + + test("a parse failure is reported with the file path and yields null", () => { + const failing = { parse: () => { throw new Error("Invalid argument") } } as unknown as Parser + + expect(parseSource(failing, " - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return [] - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return [] + const { source, tree } = parsed const scanRoot = methodName ? findMethod(tree.rootNode, methodName) : tree.rootNode if (!scanRoot) return [] diff --git a/packages/laravel-parser/src/bootstrap-parser.ts b/packages/laravel-parser/src/bootstrap-parser.ts index 724e3ba..d62b99a 100644 --- a/packages/laravel-parser/src/bootstrap-parser.ts +++ b/packages/laravel-parser/src/bootstrap-parser.ts @@ -1,9 +1,9 @@ -import { readFileSync } from "fs" import { join, relative, normalize } from "path" // @ts-ignore import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" import type { AliasMap } from "./kernel-parser.js" @@ -30,14 +30,9 @@ type AstNode = { type: string; children: AstNode[]; namedChildren: AstNode[]; te * Returns empty aliasMap and routeFiles if the file cannot be read or parsed. */ export function parseBootstrap(filePath: string, projectRoot: string): BootstrapParseResult { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return { aliasMap: {}, routeFiles: [], routePrefixes: new Map() } - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return { aliasMap: {}, routeFiles: [], routePrefixes: new Map() } + const { source, tree } = parsed const root = tree.rootNode as AstNode const aliasMap = extractAliasMap(root) diff --git a/packages/laravel-parser/src/constant-resolver.ts b/packages/laravel-parser/src/constant-resolver.ts index c91d206..4e92d1c 100644 --- a/packages/laravel-parser/src/constant-resolver.ts +++ b/packages/laravel-parser/src/constant-resolver.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore — tree-sitter-php has no bundled types import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" // Resolved PHP class constants: ClassName → { CONST_NAME → "value" } export type ConstantMap = Record> @@ -10,14 +10,9 @@ const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) export function parseConstantClass(filePath: string): ConstantMap { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return {} - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return {} + const { source, tree } = parsed const map: ConstantMap = {} walkNode(tree.rootNode, null, map) return map diff --git a/packages/laravel-parser/src/controller-parser.ts b/packages/laravel-parser/src/controller-parser.ts index 9fb9121..eacbcef 100644 --- a/packages/laravel-parser/src/controller-parser.ts +++ b/packages/laravel-parser/src/controller-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" import { extractReturnedResources } from "./resource-parser.js" import { classifyDispatch } from "./transaction-parser.js" import { isGuardClauseMethodNode } from "./guard-clause-parser.js" @@ -122,14 +122,9 @@ export function parseControllerMethod( filePath: string, methodName: string ): ControllerL1 | null { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return null - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return null + const { source, tree } = parsed const root = tree.rootNode const useMap = extractUseMap(root) @@ -241,14 +236,9 @@ export function parseControllerMethod( * Returns undefined if the file can't be parsed or has no authorize() method. */ export function parseFormRequestAuthorize(filePath: string): string | undefined { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return undefined - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return undefined + const { source, tree } = parsed const methodNode = findMethod(tree.rootNode, "authorize") if (!methodNode) return undefined @@ -1056,14 +1046,9 @@ export function detectParamDrivenBranch( argPosition: number, requestParamName: string ): ConditionalBranch | null { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return null - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return null + const { source, tree } = parsed const root = tree.rootNode const methodNode = findMethod(root, methodName) if (!methodNode) return null diff --git a/packages/laravel-parser/src/event-listener-mapper.ts b/packages/laravel-parser/src/event-listener-mapper.ts index e48cbe7..55f7664 100644 --- a/packages/laravel-parser/src/event-listener-mapper.ts +++ b/packages/laravel-parser/src/event-listener-mapper.ts @@ -4,6 +4,7 @@ import { join } from "path" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" import { extractUseMap } from "./controller-parser.js" import { fqcnToPath } from "./project-config.js" @@ -43,14 +44,9 @@ export function parseEventListeners( const providerPath = join(projectRoot, "app/Providers/EventServiceProvider.php") if (!existsSync(providerPath)) return new Map() - let source: string - let tree: ReturnType - try { - source = readFileSync(providerPath, "utf-8") - tree = _parser.parse(source) - } catch { - return new Map() - } + const parsed = parsePhpFile(_parser, providerPath) + if (!parsed) return new Map() + const { source, tree } = parsed const root = tree.rootNode as AstNode // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/packages/laravel-parser/src/guard-clause-parser.ts b/packages/laravel-parser/src/guard-clause-parser.ts index ae279b2..caac970 100644 --- a/packages/laravel-parser/src/guard-clause-parser.ts +++ b/packages/laravel-parser/src/guard-clause-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -38,14 +38,9 @@ const NO_GUARD: GuardClauseResult = { isGuardClause: false, reason: null, condit * inside the method does not false-positive as a guard clause. */ export function detectGuardClause(filePath: string, methodName: string): GuardClauseResult { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return NO_GUARD - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return NO_GUARD + const { source, tree } = parsed const methodNode = findMethod(tree.rootNode, methodName) if (!methodNode) return NO_GUARD diff --git a/packages/laravel-parser/src/isolation-parser.ts b/packages/laravel-parser/src/isolation-parser.ts index 677c97a..e4958da 100644 --- a/packages/laravel-parser/src/isolation-parser.ts +++ b/packages/laravel-parser/src/isolation-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -65,14 +65,9 @@ export function parseIsolation(filePath: string, opts: IsolationOptions = {}, me const tenantSignals = new Set(opts.tenantSignals ?? DEFAULT_TENANT_SIGNALS) const tenantContainerKeys = opts.tenantContainerKeys ?? DEFAULT_TENANT_CONTAINER_KEYS - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return { modelQueries: [], modelWrites: [], readsTenantFromContainer: false } - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return { modelQueries: [], modelWrites: [], readsTenantFromContainer: false } + const { source, tree } = parsed const scanRoot = methodName ? findMethod(tree.rootNode, methodName) : tree.rootNode if (!scanRoot) return { modelQueries: [], modelWrites: [], readsTenantFromContainer: false } diff --git a/packages/laravel-parser/src/kernel-parser.ts b/packages/laravel-parser/src/kernel-parser.ts index a423f08..0d34a38 100644 --- a/packages/laravel-parser/src/kernel-parser.ts +++ b/packages/laravel-parser/src/kernel-parser.ts @@ -1,8 +1,8 @@ // @ts-ignore — tree-sitter lacks ambient declarations in this workspace import Parser from "tree-sitter" -import { readFileSync } from "fs" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -20,14 +20,9 @@ export type MiddlewareGroupMap = Record * Returns an empty map if the file cannot be read or no aliases are found. */ export function parseKernel(filePath: string): AliasMap { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return {} - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return {} + const { source, tree } = parsed const out: AliasMap = {} findAliasProperty(tree.rootNode, out) return out @@ -38,14 +33,9 @@ export function parseKernel(filePath: string): AliasMap { * Returns an empty map if the file cannot be read or no groups are found. */ export function parseMiddlewareGroups(filePath: string): MiddlewareGroupMap { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return {} - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return {} + const { source, tree } = parsed const out: MiddlewareGroupMap = {} findMiddlewareGroupsProperty(tree.rootNode, out) return out diff --git a/packages/laravel-parser/src/php-source.ts b/packages/laravel-parser/src/php-source.ts new file mode 100644 index 0000000..1e4351a --- /dev/null +++ b/packages/laravel-parser/src/php-source.ts @@ -0,0 +1,45 @@ +import { readFileSync } from "fs" +import type Parser from "tree-sitter" + +/** + * tree-sitter 0.21 parses a string through a fixed-size buffer (32 KiB by + * default) and throws "Invalid argument" for longer input. Size the buffer to + * the source so large files (big controllers, fat services) are parsed instead + * of failing. + */ +export function parseOptionsFor(source: string): { bufferSize: number } | undefined { + return source.length >= 32 * 1024 ? { bufferSize: source.length * 2 } : undefined +} + +/** + * Parses `source` with `parser`. A parse failure is reported on stderr with the + * file path and yields null, so the caller skips the file — it no longer reads + * as "this file has nothing in it". + */ +export function parseSource(parser: Parser, source: string, filePath: string): Parser.Tree | null { + try { + return parser.parse(source, undefined, parseOptionsFor(source)) + } catch (err) { + const reason = err instanceof Error ? err.message : String(err) + console.warn(`[archmind] laravel-parser: could not parse ${filePath}: ${reason} (file skipped)`) + return null + } +} + +/** Reads a file. A file that cannot be read (missing, a directory, no access) yields null. */ +export function readSource(filePath: string): string | null { + try { + return readFileSync(filePath, "utf-8") + } catch { + return null + } +} + +/** Reads and parses a PHP file; null when it cannot be read or parsed (see parseSource). */ +export function parsePhpFile(parser: Parser, filePath: string): { source: string; tree: Parser.Tree } | null { + const source = readSource(filePath) + if (source === null) return null + const tree = parseSource(parser, source, filePath) + if (!tree) return null + return { source, tree } +} diff --git a/packages/laravel-parser/src/queue-job-parser.ts b/packages/laravel-parser/src/queue-job-parser.ts index 13a4ea8..9e3fe07 100644 --- a/packages/laravel-parser/src/queue-job-parser.ts +++ b/packages/laravel-parser/src/queue-job-parser.ts @@ -10,6 +10,7 @@ import { join } from "path" import Parser from "tree-sitter" // @ts-ignore — tree-sitter-php lacks ambient declarations in this workspace import PHP from "tree-sitter-php" +import { parseSource, readSource } from "./php-source.js" import type { IntermediateExecutionGraph, ExecutionNode } from "@kidkender/archmind-protocol" import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" @@ -21,21 +22,13 @@ const SKIP_DIRS = new Set(["node_modules", "vendor", "storage", "bootstrap", ".g /** Parse a single file for a ShouldQueue job class. Returns null if not a queued job. */ export function parseQueuedJob(filePath: string): IntermediateExecutionGraph | null { - let source: string - try { - source = readFileSync(filePath, "utf-8") - } catch { - return null - } + const source = readSource(filePath) + if (source === null) return null // Cheap string pre-filter before paying for a tree-sitter parse. if (!source.includes("ShouldQueue")) return null - let tree: ReturnType - try { - tree = _parser.parse(source) - } catch { - return null - } + const tree = parseSource(_parser, source, filePath) + if (!tree) return null const cls = findShouldQueueClass(tree.rootNode) if (!cls) return null diff --git a/packages/laravel-parser/src/resource-parser.ts b/packages/laravel-parser/src/resource-parser.ts index 538ffea..6be1c9d 100644 --- a/packages/laravel-parser/src/resource-parser.ts +++ b/packages/laravel-parser/src/resource-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -36,14 +36,9 @@ const SENSITIVE_PATTERNS = /secret|token|password|passwd|internal|admin_|_admin| * Returns null if the file can't be parsed or has no toArray() method. */ export function parseApiResource(filePath: string): ApiResourceInfo | null { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return null - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return null + const { source, tree } = parsed const root = tree.rootNode const className = extractClassName(root) diff --git a/packages/laravel-parser/src/route-parser.ts b/packages/laravel-parser/src/route-parser.ts index 2a7e249..e1e75b4 100644 --- a/packages/laravel-parser/src/route-parser.ts +++ b/packages/laravel-parser/src/route-parser.ts @@ -1,8 +1,8 @@ -import { readFileSync } from "fs" import { dirname, join } from "path" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" import type { IntermediateExecutionGraph, ExecutionNode, @@ -80,16 +80,9 @@ function processFile( out: IntermediateExecutionGraph[], opts: ParseOptions ): void { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - // Large files (> 32KB) require a bigger internal parse buffer - const bufferSize = source.length > 32_768 ? 1024 * 1024 : undefined - tree = _parser.parse(source, undefined, bufferSize ? { bufferSize } : undefined) - } catch { - return - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return + const { tree } = parsed const useMap = extractUseMap(tree.rootNode) walkBlock(tree.rootNode, ctx, out, filePath, opts, useMap) } diff --git a/packages/laravel-parser/src/route-service-provider-parser.ts b/packages/laravel-parser/src/route-service-provider-parser.ts index 26846e1..38cfc32 100644 --- a/packages/laravel-parser/src/route-service-provider-parser.ts +++ b/packages/laravel-parser/src/route-service-provider-parser.ts @@ -1,8 +1,8 @@ -import { readFileSync } from "fs" import { dirname, join, normalize, relative } from "path" import Parser from "tree-sitter" // @ts-ignore — tree-sitter lacks ambient declarations in this workspace import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -67,14 +67,9 @@ function parseProvider( const middleware: RouteWrappingMap = new Map() const namespace: RouteNamespaceMap = new Map() const prefix: RoutePrefixMap = new Map() - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return { middleware, namespace, prefix } - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return { middleware, namespace, prefix } + const { source, tree } = parsed const classNamespaceProperty = findClassNamespaceProperty(tree.rootNode) walk(tree.rootNode, filePath, projectRoot, middleware, namespace, prefix, classNamespaceProperty) return { middleware, namespace, prefix } diff --git a/packages/laravel-parser/src/schedule-parser.ts b/packages/laravel-parser/src/schedule-parser.ts index e3da3b8..450cd7b 100644 --- a/packages/laravel-parser/src/schedule-parser.ts +++ b/packages/laravel-parser/src/schedule-parser.ts @@ -5,10 +5,10 @@ // Mirrors the Spring Boot @Scheduled and NestJS @Cron entrypoint kind so all // three frameworks emit an equivalent EntrypointDescriptor{type:"cron"}. // --------------------------------------------------------------------------- -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore — tree-sitter-php lacks ambient declarations in this workspace import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" import type { IntermediateExecutionGraph, ExecutionNode } from "@kidkender/archmind-protocol" import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" @@ -50,14 +50,9 @@ export interface ScheduledEntry { } export function parseSchedule(filePath: string): IntermediateExecutionGraph[] { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return [] - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return [] + const { source, tree } = parsed const scheduleMethod = findScheduleMethod(tree.rootNode) if (!scheduleMethod) return [] diff --git a/packages/laravel-parser/src/transaction-parser.ts b/packages/laravel-parser/src/transaction-parser.ts index 2883356..60c7f15 100644 --- a/packages/laravel-parser/src/transaction-parser.ts +++ b/packages/laravel-parser/src/transaction-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -69,14 +69,9 @@ export interface TransactionParseResult { * `delete()`'s graph — IR v1.5 Phase 3 fix). */ export function parseTransactions(filePath: string, methodName?: string): TransactionParseResult { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return { hasTransaction: false, blocks: [] } - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return { hasTransaction: false, blocks: [] } + const { source, tree } = parsed const scanRoot = methodName ? findMethod(tree.rootNode, methodName) : tree.rootNode if (!scanRoot) return { hasTransaction: false, blocks: [] } diff --git a/packages/springboot-parser/__tests__/java-source.test.ts b/packages/springboot-parser/__tests__/java-source.test.ts new file mode 100644 index 0000000..c78c5cd --- /dev/null +++ b/packages/springboot-parser/__tests__/java-source.test.ts @@ -0,0 +1,52 @@ +import { mkdtempSync, writeFileSync, rmSync } from "fs" +import { tmpdir } from "os" +import { join } from "path" +import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" +import { parseSpringBootProject } from "../src/adapter.js" + +// A controller well past tree-sitter 0.21's default 32 KiB parse buffer; the +// mapped, secured method comes after ~40 KB of filler. +function largeController(): string { + const filler = Array.from({ length: 400 }, (_, i) => + ` private String helper${i}() { return "value value value value value value value value value ${i}"; }`, + ).join("\n") + return ` +package com.example.web; +import org.springframework.web.bind.annotation.*; +import org.springframework.security.access.prepost.PreAuthorize; + +@RestController +@RequestMapping("/api/reports") +public class ReportController { +${filler} + + @PreAuthorize("hasRole('ADMIN')") + @DeleteMapping("/{id}") + public void remove(@PathVariable Long id) { } +} +` +} + +describe("parseSpringBootProject — large source files", () => { + let dir: string + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "archmind-sb-large-")) + }) + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }) + }) + + test("a controller larger than 32 KiB is parsed with its auth annotations", () => { + const source = largeController() + expect(source.length).toBeGreaterThan(32 * 1024) + writeFileSync(join(dir, "ReportController.java"), source) + + const graphs = parseSpringBootProject(dir) + + expect(graphs).toHaveLength(1) + expect(graphs[0]!.path).toContain("/api/reports") + expect(graphs[0]!.nodes.map((n) => n.type)).toContain(IR_NODE_TYPES.AUTHZ_CHECK) + }) +}) diff --git a/packages/springboot-parser/src/controller-parser.ts b/packages/springboot-parser/src/controller-parser.ts index 20eda29..502e1b5 100644 --- a/packages/springboot-parser/src/controller-parser.ts +++ b/packages/springboot-parser/src/controller-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import Java from "tree-sitter-java" +import { parseJavaFile } from "./java-source.js" import type { ArchMindUserConfig } from "@kidkender/archmind-protocol" import { moduleRootOf } from "./security-config-parser.js" import type { @@ -58,19 +58,9 @@ export function parseControllerFile( baseClassIndex?: Map, userConfig?: ArchMindUserConfig, ): SpringControllerMethod[] { - let source: string - try { - source = readFileSync(filePath, "utf-8") - } catch { - return [] - } - - let tree: ReturnType - try { - tree = _parser.parse(source) - } catch { - return [] - } + const parsed = parseJavaFile(_parser, filePath) + if (!parsed) return [] + const { source, tree } = parsed const root = tree.rootNode const out: SpringControllerMethod[] = [] diff --git a/packages/springboot-parser/src/java-source.ts b/packages/springboot-parser/src/java-source.ts new file mode 100644 index 0000000..5d2dc24 --- /dev/null +++ b/packages/springboot-parser/src/java-source.ts @@ -0,0 +1,45 @@ +import { readFileSync } from "fs" +import type Parser from "tree-sitter" + +/** + * tree-sitter 0.21 parses a string through a fixed-size buffer (32 KiB by + * default) and throws "Invalid argument" for longer input. Size the buffer to + * the source so large files (big controllers, generated code) are parsed instead + * of failing. + */ +export function parseOptionsFor(source: string): { bufferSize: number } | undefined { + return source.length >= 32 * 1024 ? { bufferSize: source.length * 2 } : undefined +} + +/** + * Parses `source` with `parser`. A parse failure is reported on stderr with the + * file path and yields null, so the caller skips the file — it no longer reads + * as "this file has nothing in it". + */ +export function parseSource(parser: Parser, source: string, filePath: string): Parser.Tree | null { + try { + return parser.parse(source, undefined, parseOptionsFor(source)) + } catch (err) { + const reason = err instanceof Error ? err.message : String(err) + console.warn(`[archmind] springboot-parser: could not parse ${filePath}: ${reason} (file skipped)`) + return null + } +} + +/** Reads a file. A file that cannot be read (missing, a directory, no access) yields null. */ +export function readSource(filePath: string): string | null { + try { + return readFileSync(filePath, "utf-8") + } catch { + return null + } +} + +/** Reads and parses a Java file; null when it cannot be read or parsed (see parseSource). */ +export function parseJavaFile(parser: Parser, filePath: string): { source: string; tree: Parser.Tree } | null { + const source = readSource(filePath) + if (source === null) return null + const tree = parseSource(parser, source, filePath) + if (!tree) return null + return { source, tree } +} diff --git a/packages/springboot-parser/src/service-transaction-index.ts b/packages/springboot-parser/src/service-transaction-index.ts index a0c42b3..0c7c470 100644 --- a/packages/springboot-parser/src/service-transaction-index.ts +++ b/packages/springboot-parser/src/service-transaction-index.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import Java from "tree-sitter-java" +import { parseSource, readSource } from "./java-source.js" import { moduleRootOf } from "./security-config-parser.js" const _parser = new Parser() @@ -39,20 +39,12 @@ export function buildServiceTransactionIndex(javaFiles: string[]): ServiceTransa const interfaceToImpls = new Map() for (const file of javaFiles) { - let source: string - try { - source = readFileSync(file, "utf-8") - } catch { - continue - } + const source = readSource(file) + if (source === null) continue if (!source.includes("@Transactional") && !source.includes("implements")) continue - let tree: Parser.Tree - try { - tree = _parser.parse(source) - } catch { - continue - } + const tree = parseSource(_parser, source, file) + if (!tree) continue const module = moduleRootOf(file) From 75449ecda1379b0dd58f94bcd18c51a870e9a662 Mon Sep 17 00:00:00 2001 From: kidkender Date: Tue, 10 Nov 2026 16:46:22 +0700 Subject: [PATCH 04/25] feat(go-parser): detect tenant isolation for Gin + GORM go-parser emitted none of the nodes the missing_tenant_scope detector needs, so the finding never fired on Gin projects. On a route that resolves a tenant (a middleware whose name carries a tenant key, a c.Get("tenant_id")-style read from the Gin context, or an accessor such as GetTenantID(c) / tenant.FromContext(ctx)), go-parser now emits an ir:tenant_context node and classifies every GORM query in the handler and up to two calls below it (handler -> service -> repository, through struct fields): ir:scoped_query when its Where/Scopes/Joins arguments carry a tenant signal, otherwise ir:unscoped_query / ir:unscoped_write with a missing_tenant_scope edge. A write whose record literal sets the tenant counts as scoped. Routes that resolve no tenant get none of these nodes, so single-tenant apps and existing topology baselines are unaffected. Signals are configurable in archmind.json `isolation.tenantSignals` / `isolation.tenantContextKeys` (defaults: tenant, organization_id, org_id). explainer: missing_tenant_scope also accepts ir:tenant_context as the tenant node (ir:runtime_inject would have raised hidden_runtime_dependency on every tenant route), and gives GORM-style advice for Gin graphs. Limits: syntactic only; GORM global scopes, callbacks, plugins and Scopes(fn) without a tenant name are not seen; at most 25 query nodes per route. --- .../__tests__/missing-tenant-scope.test.ts | 37 +++ .../pattern-detectors/missing-tenant-scope.ts | 62 +++-- packages/go-parser/README.md | 6 +- .../go-parser/src/__tests__/isolation.test.ts | 253 ++++++++++++++++++ packages/go-parser/src/adapter.ts | 3 +- packages/go-parser/src/graph-builder.ts | 174 +++++++++++- packages/go-parser/src/isolation-parser.ts | 242 +++++++++++++++++ packages/protocol/src/config.ts | 10 + 8 files changed, 765 insertions(+), 22 deletions(-) create mode 100644 packages/go-parser/src/__tests__/isolation.test.ts create mode 100644 packages/go-parser/src/isolation-parser.ts diff --git a/packages/explainer/src/__tests__/missing-tenant-scope.test.ts b/packages/explainer/src/__tests__/missing-tenant-scope.test.ts index 85c66eb..44134f4 100644 --- a/packages/explainer/src/__tests__/missing-tenant-scope.test.ts +++ b/packages/explainer/src/__tests__/missing-tenant-scope.test.ts @@ -1,6 +1,8 @@ import { describe, test, expect } from "@jest/globals" import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" +import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" import { detectMissingTenantScope } from "../pattern-detectors/missing-tenant-scope.js" +import { explain } from "../index.js" import { FINDING_TYPES } from "../findings/types.js" function makeGraph( @@ -131,3 +133,38 @@ describe("detectMissingTenantScope", () => { expect(detectMissingTenantScope([], graph)).toHaveLength(0) }) }) + +describe("detectMissingTenantScope — Gin graphs (ir:tenant_context)", () => { + function ginGraph(): IntermediateExecutionGraph { + return { + entrypoint: "GET /api/v1/orders/:id", + method: "GET", + path: "/api/v1/orders/:id", + annotations: [], + framework: "gin", + nodes: [ + { id: "handler", type: IR_NODE_TYPES.BUSINESS_HANDLER, symbol: "handler.Get" }, + { id: "tenant_ctx", type: IR_NODE_TYPES.TENANT_CONTEXT, symbol: `tenant context: c.GetString("tenant_id")`, role: "runtime" }, + { id: "iso_0", type: IR_NODE_TYPES.UNSCOPED_QUERY, symbol: "Order::First", role: "data_access" }, + ], + edges: [ + { from: "handler", to: "iso_0", relation: "calls", traceability: "static" }, + { from: "iso_0", to: "tenant_ctx", relation: "missing_tenant_scope", traceability: "semantic" }, + ], + } + } + + test("an unscoped GORM query linked to the tenant context is a finding with Go advice", () => { + const [f] = detectMissingTenantScope([], ginGraph()) + expect(f?.type).toBe(FINDING_TYPES.MISSING_TENANT_SCOPE) + expect(f?.provenance.supporting_nodes).toEqual(["iso_0", "tenant_ctx"]) + expect(f?.recommendations?.some((r) => r.includes(`Where("tenant_id = ?"`))).toBe(true) + expect(f?.recommendations?.some((r) => r.includes("AppServiceProvider"))).toBe(false) + }) + + test("the tenant context node does not also raise hidden_runtime_dependency", () => { + const types = explain(ginGraph()).map((x) => x.type) + expect(types).toContain(FINDING_TYPES.MISSING_TENANT_SCOPE) + expect(types).not.toContain(FINDING_TYPES.HIDDEN_RUNTIME_DEPENDENCY) + }) +}) diff --git a/packages/explainer/src/pattern-detectors/missing-tenant-scope.ts b/packages/explainer/src/pattern-detectors/missing-tenant-scope.ts index 8d21520..d5b30ea 100644 --- a/packages/explainer/src/pattern-detectors/missing-tenant-scope.ts +++ b/packages/explainer/src/pattern-detectors/missing-tenant-scope.ts @@ -1,5 +1,6 @@ import type { SemanticFact } from "../fact-extraction/types.js" import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" +import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" import { query } from "@kidkender/archmind-graph-query" import type { Finding, Evidence, ReasoningStep } from "../findings/types.js" import { FINDING_TYPES } from "../findings/types.js" @@ -13,13 +14,15 @@ interface UnscopedQueryGroup { function findUnscopedGroups(graph: IntermediateExecutionGraph): UnscopedQueryGroup[] { const q = query(graph) - // missing_tenant_scope edges: unscoped_query → runtime_injection + // missing_tenant_scope edges: unscoped_query → the node that resolves the tenant + // (runtime_injection in Laravel graphs, ir:tenant_context in Gin graphs) const missingEdges = q.edges().ofRelation("missing_tenant_scope") const groups: UnscopedQueryGroup[] = [] for (const edge of missingEdges.toArray()) { const unscopedNode = missingEdges.from(edge.from).fromNodes().ofType("unscoped_query").first() - const injectionNode = missingEdges.to(edge.to).toNodes().ofType("runtime_injection").first() + const injectionNode = missingEdges.to(edge.to).toNodes() + .ofType(IR_NODE_TYPES.RUNTIME_INJECT, IR_NODE_TYPES.TENANT_CONTEXT).first() if (!unscopedNode || !injectionNode) continue groups.push({ unscopedNodeId: unscopedNode.id, @@ -51,7 +54,9 @@ export function detectMissingTenantScope( { type: "tenant_context_present", node: group.injectionNodeId, - description: "Tenant is resolved and injected into the container — this is a tenant-scoped route", + description: graph.framework === "gin" + ? "Tenant is resolved for this request — this is a tenant-scoped route" + : "Tenant is resolved and injected into the container — this is a tenant-scoped route", }, { type: "unscoped_query_detected", @@ -70,7 +75,9 @@ export function detectMissingTenantScope( const evidence: Evidence[] = [ { nodeId: group.injectionNodeId, - description: "Tenant injected into container — confirms this route is tenant-scoped", + description: graph.framework === "gin" + ? "Tenant resolved for this request — confirms this route is tenant-scoped" + : "Tenant injected into container — confirms this route is tenant-scoped", }, { nodeId: group.unscopedNodeId, @@ -99,19 +106,44 @@ export function detectMissingTenantScope( summary: `${group.unscopedSymbol} fetches by raw ID with no tenant constraint — any authenticated user can access another tenant's ${modelClass ?? "model"} by guessing the ID`, reasoning, evidence, - uncertainty: [ - { - kind: "unverifiable_condition", - description: `If ${modelClass} has a registered global TenantScope (via booted() or AppServiceProvider), ${operation ?? "find"} is automatically scoped and this finding does not apply — global scopes are not visible at the call site`, - }, - ], - recommendations: [ - `Option A: ${modelClass}::where('tenant_id', app('tenant')->id)->${operation ?? "findOrFail"}($id)`, - `Option B: Add a global TenantScope to ${modelClass}'s booted() method`, - `Option C: Use scoped route model binding in AppServiceProvider`, - ], + ...(graph.framework === "gin" ? ginAdvice(modelClass, operation) : laravelAdvice(modelClass, operation)), }) } return findings } + +type Advice = Pick + +function laravelAdvice(modelClass: string | undefined, operation: string | undefined): Advice { + return { + uncertainty: [ + { + kind: "unverifiable_condition", + description: `If ${modelClass} has a registered global TenantScope (via booted() or AppServiceProvider), ${operation ?? "find"} is automatically scoped and this finding does not apply — global scopes are not visible at the call site`, + }, + ], + recommendations: [ + `Option A: ${modelClass}::where('tenant_id', app('tenant')->id)->${operation ?? "findOrFail"}($id)`, + `Option B: Add a global TenantScope to ${modelClass}'s booted() method`, + `Option C: Use scoped route model binding in AppServiceProvider`, + ], + } +} + +function ginAdvice(modelClass: string | undefined, operation: string | undefined): Advice { + const model = modelClass && modelClass !== "gorm" ? modelClass : "the model" + return { + uncertainty: [ + { + kind: "unverifiable_condition", + description: `If ${model} is scoped by a GORM callback, a plugin or a Scopes() function that does not name the tenant, ${operation ?? "the query"} may already be constrained — those are not visible at the call site`, + }, + ], + recommendations: [ + `Option A: add the tenant to the query, e.g. db.Where("tenant_id = ?", tenantID).${operation ?? "First"}(...)`, + `Option B: a reusable scope, e.g. db.Scopes(TenantScope(tenantID)).${operation ?? "First"}(...)`, + `Option C: register a GORM callback that adds the tenant condition to every query on ${model}`, + ], + } +} diff --git a/packages/go-parser/README.md b/packages/go-parser/README.md index 4f2f84c..477b2fc 100644 --- a/packages/go-parser/README.md +++ b/packages/go-parser/README.md @@ -36,6 +36,7 @@ Most of ArchMind uses it through `@kidkender/archmind-analysis`, the CLI (`archm - **Authorization checks**: role/policy middleware, and **ownership** checks. A handler that calls one of the functions named in `archmind.json` → `authorization.ownershipSources` (for example `["currentCharacter"]`) is treated as authorizing by ownership. - **Validation gates**: `ShouldBindJSON`, `ShouldBindQuery` and `ShouldBindUri` resolved to the DTO struct and its `binding` tags. - **Transaction boundaries**: GORM `.Transaction(func...)` closures, followed one hop into a directly called service method. +- **Tenant isolation**: on a route that resolves a tenant (a middleware whose name carries a tenant key, a `c.Get("tenant_id")`-style read from the Gin context, or an accessor such as `GetTenantID(c)` / `tenant.FromContext(ctx)`), an `ir:tenant_context` node, and every GORM query in the handler and up to two calls below it (handler → service → repository) as `ir:scoped_query` or `ir:unscoped_query` / `ir:unscoped_write`. An unscoped query gets a `missing_tenant_scope` edge, which the explainer reports as a `missing_tenant_scope` finding. Routes that resolve no tenant get none of these nodes. - A handler wired up as a local variable (`h := handler.NewXxx(...)`) is resolved to its type. Nodes carry the `file` and `line` where the parser found them. @@ -51,14 +52,17 @@ The tree-sitter helpers other packages build on: `parseGo`, `walk`, `receiverTyp ```json { "authorization": { "ownershipSources": ["currentCharacter", "UserId"] }, + "isolation": { "tenantSignals": ["tenant", "organization_id"], "tenantContextKeys": ["tenant", "organization"] }, "ignoreFindings": ["missing_authorization"] } ``` +`isolation` matches identifier and string tokens, ignoring case and `_`: `tenant` matches `tenant_id`, `TenantID` and `TenantScope`. `tenantSignals` mark a query as constrained (in its `Where` / `Scopes` / `Joins` arguments, or, for a write, in the statements that build the record); `tenantContextKeys` mark where the request's tenant comes from. The values shown are the defaults (`org_id` is in both lists too). + ## Limits - Scoped to the Gin + GORM + `internal/{handler,service,middleware,model,dto}` layout it was built against, and checked on other public Gin repositories. Some architectures still return no routes (an engine held in a struct field and mutated by a method, a custom wrapper type with its own `.GET()`, deeply functional-options setups, Wire-style injection). -- Tenant isolation is not implemented for Go. +- Tenant isolation is syntactic: a GORM global scope, a callback (`db.Callback()`), a plugin, or a `Scopes(fn)` whose name carries no tenant signal is not seen, so a query constrained that way reads as unscoped. Queries more than two calls below the handler, or behind an interface whose implementation is not named `T`, `t`, `TImpl` or `tImpl`, are not found. At most 25 query nodes per route. ## License diff --git a/packages/go-parser/src/__tests__/isolation.test.ts b/packages/go-parser/src/__tests__/isolation.test.ts new file mode 100644 index 0000000..abfdd5b --- /dev/null +++ b/packages/go-parser/src/__tests__/isolation.test.ts @@ -0,0 +1,253 @@ +import { describe, test, expect } from "@jest/globals" +import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" +import { parseGinProject } from "../graph-builder.js" +import type { GoSourceFile } from "../route-parser.js" +import { tokenMatcher } from "../isolation-parser.js" + +// A multi-tenant Gin + GORM API: the handler reads the tenant from the Gin +// context, the service passes it on, the repository runs the query. Each GORM +// query on a route that resolves a tenant becomes scoped or unscoped. + +function mainGo(globalMiddleware: string): GoSourceFile { + return { + path: "cmd/server/main.go", + content: ` +package main + +func main() { + r := gin.Default() + ${globalMiddleware} + api := r.Group("/api/v1") + RegisterOrderRoutes(api, orderHandler) +} +`, + } +} + +const ROUTES_GO: GoSourceFile = { + path: "routes/order.go", + content: ` +package routes + +func RegisterOrderRoutes(router gin.IRouter, handler *handler.OrderHandler) { + orders := router.Group("/orders") + orders.GET("/:id", handler.Get) + orders.GET("/:id/raw", handler.GetRaw) + orders.DELETE("/:id", handler.Delete) + orders.POST("", handler.Create) +} +`, +} + +const MIDDLEWARE_GO: GoSourceFile = { + path: "internal/middleware/tenant.go", + content: ` +package middleware + +func TenantMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + c.Set("tenant_id", c.GetHeader("X-Tenant")) + c.Next() + } +} +`, +} + +function handlerGo(readsTenant: boolean): GoSourceFile { + const tenant = readsTenant ? `tenantID := c.GetString("tenant_id")` : `tenantID := ""` + return { + path: "internal/handler/order.go", + content: ` +package handler + +type OrderHandler struct { + orderService *service.OrderService +} + +func (h *OrderHandler) Get(c *gin.Context) { + ${tenant} + h.orderService.Get(tenantID, c.Param("id")) +} + +func (h *OrderHandler) GetRaw(c *gin.Context) { + ${tenant} + h.orderService.GetRaw(c.Param("id")) +} + +func (h *OrderHandler) Delete(c *gin.Context) { + ${tenant} + h.orderService.Delete(c.Param("id")) +} + +func (h *OrderHandler) Create(c *gin.Context) { + ${tenant} + h.orderService.Create(tenantID) +} +`, + } +} + +const SERVICE_GO: GoSourceFile = { + path: "internal/service/order.go", + content: ` +package service + +type OrderService struct { + repo *repository.OrderRepository +} + +func (s *OrderService) Get(tenantID string, id string) (*model.Order, error) { + return s.repo.FindForTenant(tenantID, id) +} + +func (s *OrderService) GetRaw(id string) (*model.Order, error) { + return s.repo.FindByID(id) +} + +func (s *OrderService) Delete(id string) error { + return s.repo.Delete(id) +} + +func (s *OrderService) Create(tenantID string) error { + return s.repo.Create(tenantID) +} +`, +} + +const REPOSITORY_GO: GoSourceFile = { + path: "internal/repository/order.go", + content: ` +package repository + +type OrderRepository struct { + db *gorm.DB +} + +func (r *OrderRepository) FindForTenant(tenantID string, id string) (*model.Order, error) { + var order model.Order + err := r.db.Where("tenant_id = ? AND id = ?", tenantID, id).First(&order).Error + return &order, err +} + +func (r *OrderRepository) FindByID(id string) (*model.Order, error) { + var order model.Order + err := r.db.First(&order, id).Error + return &order, err +} + +func (r *OrderRepository) Delete(id string) error { + return r.db.Delete(&model.Order{}, id).Error +} + +func (r *OrderRepository) Create(tenantID string) error { + order := model.Order{TenantID: tenantID, Status: "new"} + return r.db.Create(&order).Error +} +`, +} + +function graphFor(graphs: IntermediateExecutionGraph[], entry: string): IntermediateExecutionGraph { + const g = graphs.find((x) => x.entrypoint === entry) + if (!g) throw new Error(`no graph for ${entry}; have ${graphs.map((x) => x.entrypoint).join(", ")}`) + return g +} + +function typesOf(g: IntermediateExecutionGraph): string[] { + return g.nodes.map((n) => n.type) +} + +describe("parseGinProject — tenant isolation", () => { + const tenantApp = [mainGo(""), ROUTES_GO, MIDDLEWARE_GO, handlerGo(true), SERVICE_GO, REPOSITORY_GO] + + test("a query constrained by tenant_id two calls below the handler is ir:scoped_query", () => { + const g = graphFor(parseGinProject(tenantApp), "GET /api/v1/orders/:id") + + const ctx = g.nodes.find((n) => n.type === IR_NODE_TYPES.TENANT_CONTEXT) + expect(ctx?.symbol).toContain("tenant") + expect(ctx?.symbol).toContain(`c.GetString("tenant_id")`) + + const scoped = g.nodes.filter((n) => n.type === IR_NODE_TYPES.SCOPED_QUERY) + expect(scoped.map((n) => n.symbol)).toEqual(["Order::First"]) + expect(scoped[0]!.file).toBe("internal/repository/order.go") + expect(typesOf(g)).not.toContain(IR_NODE_TYPES.UNSCOPED_QUERY) + expect(g.edges.some((e) => e.relation === "missing_tenant_scope")).toBe(false) + }) + + test("a lookup by id alone is ir:unscoped_query with a missing_tenant_scope edge", () => { + const g = graphFor(parseGinProject(tenantApp), "GET /api/v1/orders/:id/raw") + + const unscoped = g.nodes.find((n) => n.type === IR_NODE_TYPES.UNSCOPED_QUERY) + expect(unscoped?.symbol).toBe("Order::First") + const ctx = g.nodes.find((n) => n.type === IR_NODE_TYPES.TENANT_CONTEXT)! + expect(g.edges).toContainEqual(expect.objectContaining({ + from: unscoped!.id, to: ctx.id, relation: "missing_tenant_scope", + })) + }) + + test("a delete by id alone is ir:unscoped_write", () => { + const g = graphFor(parseGinProject(tenantApp), "DELETE /api/v1/orders/:id") + + const write = g.nodes.find((n) => n.type === IR_NODE_TYPES.UNSCOPED_WRITE) + expect(write?.symbol).toBe("Order::Delete") + }) + + test("a create whose struct literal sets TenantID is scoped and gets no node", () => { + const g = graphFor(parseGinProject(tenantApp), "POST /api/v1/orders") + + expect(typesOf(g)).toContain(IR_NODE_TYPES.TENANT_CONTEXT) + expect(typesOf(g)).not.toContain(IR_NODE_TYPES.UNSCOPED_WRITE) + }) + + test("a single-tenant app gets no isolation nodes at all", () => { + const graphs = parseGinProject([mainGo(""), ROUTES_GO, handlerGo(false), SERVICE_GO, REPOSITORY_GO]) + + for (const g of graphs) { + expect(typesOf(g)).not.toContain(IR_NODE_TYPES.TENANT_CONTEXT) + expect(typesOf(g)).not.toContain(IR_NODE_TYPES.UNSCOPED_QUERY) + expect(typesOf(g)).not.toContain(IR_NODE_TYPES.UNSCOPED_WRITE) + expect(typesOf(g)).not.toContain(IR_NODE_TYPES.SCOPED_QUERY) + } + }) + + test("a tenant middleware on the route is enough to mark the tenant context", () => { + const graphs = parseGinProject([ + mainGo("r.Use(middleware.TenantMiddleware())"), ROUTES_GO, MIDDLEWARE_GO, handlerGo(false), SERVICE_GO, REPOSITORY_GO, + ]) + const g = graphFor(graphs, "GET /api/v1/orders/:id/raw") + + const ctx = g.nodes.find((n) => n.type === IR_NODE_TYPES.TENANT_CONTEXT) + expect(ctx?.symbol).toContain("TenantMiddleware") + expect(typesOf(g)).toContain(IR_NODE_TYPES.UNSCOPED_QUERY) + }) + + test("archmind.json isolation signals replace the defaults", () => { + const handler: GoSourceFile = { + path: "internal/handler/order.go", + content: handlerGo(true).content.replace(/c\.GetString\("tenant_id"\)/g, `c.GetString("workspace_id")`), + } + const repository: GoSourceFile = { + path: REPOSITORY_GO.path, + content: REPOSITORY_GO.content.replace(`"tenant_id = ? AND id = ?"`, `"workspace_id = ? AND id = ?"`), + } + const graphs = parseGinProject( + [mainGo(""), ROUTES_GO, handler, SERVICE_GO, repository], + { isolation: { tenantSignals: ["workspace_id"], tenantContextKeys: ["workspace"] } }, + ) + + expect(typesOf(graphFor(graphs, "GET /api/v1/orders/:id"))).toContain(IR_NODE_TYPES.SCOPED_QUERY) + expect(typesOf(graphFor(graphs, "GET /api/v1/orders/:id/raw"))).toContain(IR_NODE_TYPES.UNSCOPED_QUERY) + }) +}) + +describe("tokenMatcher", () => { + test("matches identifier and string tokens, ignoring case and underscores", () => { + const match = tokenMatcher(["tenant", "org_id"]) + expect(match(`Where("tenant_id = ?", id)`)).toBe(true) + expect(match("order.TenantID")).toBe(true) + expect(match("Scopes(TenantScope(t))")).toBe(true) + expect(match(`Where("OrgID = ?", x)`)).toBe(true) + expect(match(`Where("org", id)`)).toBe(false) + expect(match("First(&order, id)")).toBe(false) + }) +}) diff --git a/packages/go-parser/src/adapter.ts b/packages/go-parser/src/adapter.ts index d568534..ec07ae0 100644 --- a/packages/go-parser/src/adapter.ts +++ b/packages/go-parser/src/adapter.ts @@ -12,13 +12,14 @@ export { isGinProject } from "./scanner.js" * list (used directly in tests with synthetic fixtures). * * Reads the project's archmind.json for settings (`authorization. - * ownershipSources`); anything passed in `opts` takes precedence. + * ownershipSources`, `isolation`); anything passed in `opts` takes precedence. */ export function parseGinProjectAt(root: string, opts: ParseGinOptions = {}): IntermediateExecutionGraph[] { const userConfig = loadUserConfig(root) const files = readGoProjectFiles(root) return parseGinProject(files, { ownershipSources: userConfig?.authorization?.ownershipSources, + isolation: userConfig?.isolation, ...opts, }) } diff --git a/packages/go-parser/src/graph-builder.ts b/packages/go-parser/src/graph-builder.ts index c15fa2b..01a3486 100644 --- a/packages/go-parser/src/graph-builder.ts +++ b/packages/go-parser/src/graph-builder.ts @@ -3,11 +3,16 @@ import type { IntermediateExecutionGraph, ExecutionNode, ExecutionEdge } from "@ import type { RouteInfo, MiddlewareRef, GoSourceFile } from "./route-parser.js" import { extractRoutes, type ExtractRoutesOptions } from "./route-parser.js" import { irTypeForMiddleware, resolveSkipListForMiddleware, type SkipEntry } from "./middleware-mapper.js" -import { parseGo, findFunctionDecls, functionName, callParts, findCalls, type SyntaxNode } from "./ast.js" +import { parseGo, findFunctionDecls, functionName, callParts, findCalls, receiverTypeName, type SyntaxNode } from "./ast.js" import { buildConstRegistry, resolveConstExpr } from "./const-resolver.js" import { buildMethodRegistry, findBindCalls, resolveVarDtoType, type HandlerMethod } from "./handler-parser.js" import { resolveDtoBinding, findStructFieldTypes } from "./dto-binding-parser.js" import { findTransactionBoundaries } from "./transaction-parser.js" +import { + findTenantContextRead, findGormOperations, tokenMatcher, + DEFAULT_TENANT_SIGNALS, DEFAULT_TENANT_CONTEXT_KEYS, + type IsolationOptions, type TokenMatcher, type GormOperation, +} from "./isolation-parser.js" const ADAPTER_VERSION = "0.1.0" @@ -19,6 +24,8 @@ export interface ParseGinOptions extends ExtractRoutesOptions { * to the caller instead of checking a role. */ ownershipSources?: string[] + /** Tenant isolation signals (archmind.json `isolation`); defaults cover tenant_id / organization_id. */ + isolation?: IsolationOptions } interface ParsedFile { @@ -251,13 +258,146 @@ function findIdentityCall(method: HandlerMethod, sources: ReadonlySet): return null } +// --------------------------------------------------------------------------- +// Tenant isolation +// --------------------------------------------------------------------------- + +interface IsolationContext { + methodRegistry: ReturnType + fieldTypesOf: (typeName: string) => Map + keyMatch: TokenMatcher + signalMatch: TokenMatcher +} + +/** How far below the handler queries are looked for: handler → service → repository. */ +const ISOLATION_MAX_DEPTH = 2 +/** Query nodes kept per route, so one huge handler cannot flood the graph. */ +const ISOLATION_MAX_QUERIES = 25 + +/** A method by receiver type, falling back to the usual implementation names of an interface. */ +function resolveMethod( + methodRegistry: ReturnType, + typeName: string, + methodName: string +): HandlerMethod | null { + const lower = typeName.charAt(0).toLowerCase() + typeName.slice(1) + const candidates = [typeName, lower, `${typeName}Impl`, `${lower}Impl`, typeName.replace(/^I(?=[A-Z])/, "")] + for (const t of candidates) { + const m = methodRegistry.get(`${t}.${methodName}`) + if (m) return m + } + return null +} + +function receiverName(fn: SyntaxNode): string | null { + const decl = fn.childForFieldName("receiver")?.namedChildren.find((c) => c.type === "parameter_declaration") + return decl?.namedChildren.find((c) => c.type === "identifier")?.text ?? null +} + +/** The handler plus the methods it reaches through its receiver and struct fields, up to ISOLATION_MAX_DEPTH. */ +function methodsOnPath(handler: HandlerMethod, ctx: IsolationContext): HandlerMethod[] { + const out: HandlerMethod[] = [] + const seen = new Set() + let frontier: HandlerMethod[] = [handler] + for (let depth = 0; depth <= ISOLATION_MAX_DEPTH && frontier.length > 0; depth++) { + const next: HandlerMethod[] = [] + for (const m of frontier) { + if (seen.has(m.node)) continue + seen.add(m.node) + out.push(m) + const recvType = receiverTypeName(m.node) + const body = m.node.childForFieldName("body") + if (!recvType || !body) continue + const fields = ctx.fieldTypesOf(recvType) + const recvName = receiverName(m.node) + for (const call of findCalls(body)) { + const parts = callParts(call) + if (!parts?.receiver) continue + // `s.helper(...)` on the same receiver, or `s.repo.Find(...)` through a field + const target = parts.receiver.includes(".") + ? fields.get(parts.receiver.slice(parts.receiver.lastIndexOf(".") + 1)) + : (parts.receiver === recvName ? recvType : undefined) + if (!target) continue + const callee = resolveMethod(ctx.methodRegistry, target, parts.method) + if (callee && !seen.has(callee.node)) next.push(callee) + } + } + frontier = next + } + return out +} + +/** + * Tenant isolation nodes for a route, the Go counterpart of laravel-parser's + * addIsolationNodes. Emitted only when the route resolves a tenant — a tenant + * middleware on the route, or a tenant read from the Gin context or an accessor + * in the handler or a method it reaches — so single-tenant apps get no query + * nodes (ir:unscoped_query is a topology danger type; emitting it everywhere + * would turn every existing Gin baseline into drift). Each GORM query on the + * path becomes ir:scoped_query or ir:unscoped_query / ir:unscoped_write, and an + * unscoped one gets a missing_tenant_scope edge to the tenant node. + */ +function isolationGraphPart( + route: RouteInfo, + ctx: IsolationContext +): { nodes: ExecutionNode[]; edges: ExecutionEdge[] } { + const handler = resolveHandlerMethod(route, ctx.methodRegistry) + if (!handler) return { nodes: [], edges: [] } + const path = methodsOnPath(handler, ctx) + + let tenantNode: ExecutionNode | null = null + const tenantMiddleware = route.middleware.find((mw) => ctx.keyMatch(mw.shortName)) + if (tenantMiddleware) { + tenantNode = { + id: "tenant_ctx", type: IR_NODE_TYPES.TENANT_CONTEXT, symbol: `tenant context: ${tenantMiddleware.text}`, + file: tenantMiddleware.file, line: tenantMiddleware.line, role: "runtime", + } + } + for (const m of path) { + if (tenantNode) break + const read = findTenantContextRead(m, ctx.keyMatch) + if (read) { + tenantNode = { + id: "tenant_ctx", type: IR_NODE_TYPES.TENANT_CONTEXT, symbol: `tenant context: ${read.symbol}`, + file: read.file, line: read.line, role: "runtime", + } + } + } + if (!tenantNode) return { nodes: [], edges: [] } + + const ops: GormOperation[] = [] + for (const m of path) { + const recvType = receiverTypeName(m.node) + ops.push(...findGormOperations(m, recvType ? ctx.fieldTypesOf(recvType) : new Map(), ctx.signalMatch)) + } + + const nodes: ExecutionNode[] = [tenantNode] + const edges: ExecutionEdge[] = [] + let index = 0 + for (const op of ops) { + if (index >= ISOLATION_MAX_QUERIES) break + if (op.kind === "write" && op.scoped) continue // like Laravel: only unscoped writes become nodes + const type = op.scoped + ? IR_NODE_TYPES.SCOPED_QUERY + : op.kind === "write" ? IR_NODE_TYPES.UNSCOPED_WRITE : IR_NODE_TYPES.UNSCOPED_QUERY + const id = `iso_${index++}` + nodes.push({ id, type, symbol: `${op.model}::${op.operation}`, file: op.file, line: op.line, role: "data_access" }) + edges.push({ from: "handler", to: id, relation: "calls", traceability: "static" }) + if (!op.scoped) { + edges.push({ from: id, to: tenantNode.id, relation: "missing_tenant_scope", traceability: "semantic" }) + } + } + return { nodes, edges } +} + function routeToGraph( route: RouteInfo, skipListIndex: Map, constRegistry: Map, methodRegistry: ReturnType, parsed: ParsedFile[], - ownershipSources: ReadonlySet + ownershipSources: ReadonlySet, + isolation: IsolationContext ): IntermediateExecutionGraph { const nodes: ExecutionNode[] = [] const edges: ExecutionEdge[] = [] @@ -308,6 +448,11 @@ function routeToGraph( }) } + // Queries hang off the handler (like Laravel's isolation nodes), outside the chain. + const iso = isolationGraphPart(route, isolation) + nodes.push(...iso.nodes) + edges.push(...iso.edges) + return { entrypoint: `${route.method} ${route.path}`, method: route.method, @@ -326,8 +471,8 @@ function routeToGraph( * per route: routes + auth gate (honoring global-middleware skip-lists), * authz-check role resolution, validation-gate from DTO binding tags, and * transaction-boundary detection (GORM `.Transaction()` closures, one hop - * into a directly-called service method). Isolation (tenant scoping) is not - * implemented yet. + * into a directly-called service method), and tenant isolation (GORM queries + * with or without a tenant constraint, on routes that resolve a tenant). */ export function parseGinProject(files: GoSourceFile[], opts: ParseGinOptions = {}): IntermediateExecutionGraph[] { const routes = extractRoutes(files, opts) @@ -342,5 +487,24 @@ export function parseGinProject(files: GoSourceFile[], opts: ParseGinOptions = { const ownershipSources = new Set(opts.ownershipSources ?? []) - return routes.map((r) => routeToGraph(r, skipListIndex, constRegistry, methodRegistry, parsed, ownershipSources)) + const fieldTypeCache = new Map>() + const isolation: IsolationContext = { + methodRegistry, + fieldTypesOf: (typeName) => { + let fields = fieldTypeCache.get(typeName) + if (!fields) { + fields = new Map() + for (const file of parsed) { + const found = findStructFieldTypes(file.root, typeName) + if (found) { fields = found; break } + } + fieldTypeCache.set(typeName, fields) + } + return fields + }, + keyMatch: tokenMatcher(opts.isolation?.tenantContextKeys ?? DEFAULT_TENANT_CONTEXT_KEYS), + signalMatch: tokenMatcher(opts.isolation?.tenantSignals ?? DEFAULT_TENANT_SIGNALS), + } + + return routes.map((r) => routeToGraph(r, skipListIndex, constRegistry, methodRegistry, parsed, ownershipSources, isolation)) } diff --git a/packages/go-parser/src/isolation-parser.ts b/packages/go-parser/src/isolation-parser.ts new file mode 100644 index 0000000..b622100 --- /dev/null +++ b/packages/go-parser/src/isolation-parser.ts @@ -0,0 +1,242 @@ +import { walk, callParts, findCalls, functionParamTypes, type SyntaxNode } from "./ast.js" +import type { HandlerMethod } from "./handler-parser.js" + +/** + * Tenant isolation for Gin + GORM, the Go counterpart of laravel-parser's + * isolation-parser: where a request resolves its tenant, and whether each GORM + * query on its path is constrained by a tenant signal. + * + * Matching is by identifier/string token: a token matches a signal when, lowercased + * with `_` removed, it contains the signal (so "tenant" matches `tenant_id`, + * `TenantID`, `TenantScope`). Syntactic only: GORM global scopes, callbacks + * (`db.Callback()`), and a `Scopes(fn)` whose name carries no signal are not seen. + */ + +export interface IsolationOptions { + /** Tokens that mark a query as tenant-constrained. */ + tenantSignals?: string[] + /** Tokens that mark a Gin context key, middleware or accessor as the request's tenant. */ + tenantContextKeys?: string[] +} + +export const DEFAULT_TENANT_SIGNALS = ["tenant", "organization_id", "org_id"] +export const DEFAULT_TENANT_CONTEXT_KEYS = ["tenant", "organization", "org_id"] + +export type TokenMatcher = (text: string) => boolean + +export function tokenMatcher(words: string[]): TokenMatcher { + const needles = words.map((w) => w.toLowerCase().replace(/_/g, "")).filter(Boolean) + return (text) => { + const tokens = text.match(/[A-Za-z0-9_]+/g) ?? [] + return tokens.some((t) => { + const token = t.toLowerCase().replace(/_/g, "") + return needles.some((n) => token.includes(n)) + }) + } +} + +// --------------------------------------------------------------------------- +// Tenant context +// --------------------------------------------------------------------------- + +/** gin.Context / context.Context getters that read a value set earlier (by middleware). */ +const CONTEXT_GETTERS = new Set([ + "Get", "MustGet", "GetString", "GetInt", "GetInt64", "GetUint", "GetUint64", "GetStringMap", "Value", +]) + +/** Accessor helpers: GetTenantID(c), CurrentTenant(c), tenant.FromContext(ctx). */ +const ACCESSOR_NAME = /^(get|current|must|resolve|load)|from(context|ctx)$/i + +export interface TenantContextRead { + symbol: string + file: string + line: number +} + +/** The first place in `method` that reads the request's tenant, or null. */ +export function findTenantContextRead(method: HandlerMethod, keyMatch: TokenMatcher): TenantContextRead | null { + const body = method.node.childForFieldName("body") + if (!body) return null + const contextParams = new Set( + [...functionParamTypes(method.node)].filter(([, type]) => type === "Context").map(([name]) => name), + ) + + for (const node of findCalls(body)) { + const parts = callParts(node) + if (!parts) continue + const key = parts.args[0] + const isContextGetter = + CONTEXT_GETTERS.has(parts.method) && + !!parts.receiver && contextParams.has(parts.receiver) && + !!key && keyMatch(key.text) + const receiverTail = parts.receiver?.slice(parts.receiver.lastIndexOf(".") + 1) ?? "" + const isAccessor = + ACCESSOR_NAME.test(parts.method) && + (keyMatch(parts.method) || (!!receiverTail && keyMatch(receiverTail))) + if (isContextGetter || isAccessor) { + return { symbol: shorten(node.text), file: method.file, line: node.startPosition.row + 1 } + } + } + return null +} + +// --------------------------------------------------------------------------- +// GORM queries +// --------------------------------------------------------------------------- + +const READ_OPS = new Set(["First", "Find", "Take", "Last", "Scan", "Count", "Pluck", "FirstOrInit", "Raw"]) +const WRITE_OPS = new Set(["Create", "Save", "Update", "Updates", "UpdateColumn", "UpdateColumns", "Delete", "FirstOrCreate", "Exec"]) + +/** Chain methods that only a *gorm.DB has in practice. */ +const GORM_CHAIN = new Set([ + "Model", "Table", "Where", "Not", "Or", "Preload", "Joins", "InnerJoins", "Scopes", "Unscoped", "WithContext", + "Session", "Select", "Omit", "Order", "Limit", "Offset", "Group", "Having", "Debug", "Clauses", "Distinct", +]) + +/** Names a *gorm.DB variable or field usually goes by. */ +const DB_NAMES = new Set(["db", "DB", "tx", "gdb", "orm", "conn", "gormDB", "database"]) + +export interface GormOperation { + kind: "read" | "write" + operation: string + model: string + scoped: boolean + file: string + line: number +} + +/** + * GORM reads and writes in `method`'s body. `receiverFields` maps the method's + * receiver struct fields to their bare types, so `r.db` typed `*gorm.DB` counts. + */ +export function findGormOperations( + method: HandlerMethod, + receiverFields: ReadonlyMap, + signalMatch: TokenMatcher, +): GormOperation[] { + const body = method.node.childForFieldName("body") + if (!body) return [] + const paramTypes = functionParamTypes(method.node) + const out: GormOperation[] = [] + + for (const node of findCalls(body)) { + const parts = callParts(node) + if (!parts) continue + const kind = READ_OPS.has(parts.method) ? "read" : WRITE_OPS.has(parts.method) ? "write" : null + if (!kind) continue + + const { base, calls } = chainOf(node) + const baseAssignments = base?.type === "identifier" ? assignmentsTo(body, base.text) : [] + const chainIsGorm = calls.slice(1).some((c) => GORM_CHAIN.has(callParts(c)?.method ?? "")) + const baseIsGorm = + isDbExpression(base, paramTypes, receiverFields) || + baseAssignments.some((text) => /\.(db|DB|tx)\b|\.(Where|Model|Table|WithContext|Scopes)\(/.test(text)) + if (!chainIsGorm && !baseIsGorm) continue + + const texts = [node.text, ...baseAssignments] + if (kind === "write") texts.push(...statementsMentioning(body, destinationVar(parts.args[0]))) + + out.push({ + kind, + operation: parts.method, + model: modelOf(calls, parts.args[0], body) ?? "gorm", + scoped: texts.some(signalMatch), + file: method.file, + line: node.startPosition.row + 1, + }) + } + return out +} + +/** The receiver chain of a call: `r.db.Where(...).First(&x)` → base `r.db`, calls [First, Where]. */ +function chainOf(call: SyntaxNode): { base: SyntaxNode | null; calls: SyntaxNode[] } { + const calls = [call] + let operand = selectorOperand(call) + while (operand && operand.type === "call_expression") { + calls.push(operand) + operand = selectorOperand(operand) + } + return { base: operand, calls } +} + +function selectorOperand(call: SyntaxNode): SyntaxNode | null { + const fn = call.childForFieldName("function") + return fn?.type === "selector_expression" ? fn.childForFieldName("operand") : null +} + +function isDbExpression( + base: SyntaxNode | null, + paramTypes: ReadonlyMap, + receiverFields: ReadonlyMap, +): boolean { + if (!base) return false + if (base.type === "identifier") return paramTypes.get(base.text) === "DB" || DB_NAMES.has(base.text) + if (base.type === "selector_expression") { + const field = base.childForFieldName("field")?.text ?? "" + return receiverFields.get(field) === "DB" || DB_NAMES.has(field) + } + return false +} + +/** Texts of `name := ...` / `name = ...` / `var name = ...` statements in a body. */ +function assignmentsTo(body: SyntaxNode, name: string): string[] { + const out: string[] = [] + for (const n of walk(body)) { + if (n.type !== "short_var_declaration" && n.type !== "assignment_statement" && n.type !== "var_spec") continue + const left = n.childForFieldName("left") ?? n.childForFieldName("name") + if (left && (left.text.split(/\s*,\s*/).includes(name))) out.push(n.text) + } + return out +} + +/** `&order` / `order` → "order"; anything else → null. */ +function destinationVar(arg: SyntaxNode | undefined): string | null { + if (!arg) return null + const m = /^&?([A-Za-z_]\w*)$/.exec(arg.text) + return m ? m[1] : null +} + +/** Statements in a body that mention `name` as a whole word (its literal, its field writes). */ +function statementsMentioning(body: SyntaxNode, name: string | null): string[] { + if (!name) return [] + const word = new RegExp(`\\b${name}\\b`) + const out: string[] = [] + for (const n of walk(body)) { + if (!/(_statement|_declaration)$/.test(n.type) || n.type === "block") continue + if (n.type === "if_statement" || n.type === "for_statement" || n.type === "expression_switch_statement") continue + if (word.test(n.text)) out.push(n.text) + } + return out +} + +/** Model name from `Model(&T{})`, `Table("t")`, a composite-literal argument, or the destination variable's declaration. */ +function modelOf(calls: SyntaxNode[], firstArg: SyntaxNode | undefined, body: SyntaxNode): string | null { + for (const c of calls) { + const p = callParts(c) + if (p?.method === "Model" && p.args[0]) { + const t = compositeType(p.args[0].text) + if (t) return t + } + if (p?.method === "Table" && p.args[0]) return p.args[0].text.replace(/^["`]|["`]$/g, "") + } + if (!firstArg) return null + const literal = compositeType(firstArg.text) + if (literal) return literal + const name = destinationVar(firstArg) + if (!name) return null + const decl = + new RegExp(`\\bvar\\s+${name}\\s+(?:\\[\\])?\\*?(?:\\w+\\.)?(\\w+)`).exec(body.text) ?? + new RegExp(`\\b${name}\\s*:?=\\s*(?:&|new\\()?(?:\\[\\])?\\*?(?:\\w+\\.)?(\\w+)\\s*[{)]`).exec(body.text) + return decl ? decl[1] : null +} + +/** `&models.Order{}` / `Order{...}` / `[]Order{}` → "Order". */ +function compositeType(text: string): string | null { + const m = /^&?(?:\[\])?\*?(?:\w+\.)?([A-Z]\w*)\s*\{/.exec(text.trim()) + return m ? m[1] : null +} + +function shorten(text: string): string { + const firstLine = text.split("\n")[0] + return firstLine.length > 80 ? `${firstLine.slice(0, 77)}...` : firstLine +} diff --git a/packages/protocol/src/config.ts b/packages/protocol/src/config.ts index 6ae8cbc..3b17384 100644 --- a/packages/protocol/src/config.ts +++ b/packages/protocol/src/config.ts @@ -51,6 +51,16 @@ export interface ArchMindUserConfig { */ ownershipSources?: string[] } + /** + * Tenant isolation for multi-tenant apps. Go/Gin only for now (Laravel reads + * `conventions.tenantSignals` from .archmind.json). + */ + isolation?: { + /** Tokens that mark a query as tenant-constrained, e.g. ["tenant", "organization_id"]. */ + tenantSignals?: string[] + /** Tokens that mark a context key, middleware or accessor as the request's tenant. */ + tenantContextKeys?: string[] + } /** Finding types to drop from the report, e.g. ["missing_authorization"]. */ ignoreFindings?: string[] } From 56e574f0ece926a57745546102366ff64b45cd8b Mon Sep 17 00:00:00 2001 From: kidkender Date: Tue, 10 Nov 2026 17:14:11 +0700 Subject: [PATCH 05/25] fix(build): build workspaces in dependency order so a clean checkout builds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI on main has failed since at least 2026-10-15: `npm run build --workspaces` builds alphabetically, so on a fresh checkout `aql` is compiled before `protocol` has a dist/ and tsc cannot resolve it. - scripts/build-workspaces.mjs builds each workspace after the workspaces it depends on (dependencies/peerDependencies hard, devDependencies soft — dropped only to get past a cycle); the root `build` script runs it. - explainer: exclude src/__tests__ and src/benchmark from the tsc build. They are already left out of the published package, and compiling them made explainer need scorer (scorer -> llm-client -> prompt-builder -> explainer). - nestjs-parser: declare laravel-parser and springboot-parser as devDependencies; its cross-framework tests import them. - lsp: keep @kidkender/archmind-analysis external. Bundling it pulled in go-parser, whose tree-sitter-go native module esbuild cannot bundle and which needs tree-sitter 0.25 while lsp runs 0.21. - go-parser: findGoFiles returns `/`-separated paths on every OS (the scanner tests failed on Windows); the mcp-server cache test looks files up the same way. Verified on a clean worktree: npm ci, build (22 workspaces), npm test all pass. --- package-lock.json | 2 + package.json | 2 +- packages/explainer/tsconfig.json | 2 +- packages/go-parser/src/scanner.ts | 4 +- packages/lsp/build.mjs | 5 +- .../mcp-server/src/__tests__/cache.test.ts | 4 +- packages/nestjs-parser/package.json | 2 + scripts/build-workspaces.mjs | 65 +++++++++++++++++++ 8 files changed, 79 insertions(+), 7 deletions(-) create mode 100644 scripts/build-workspaces.mjs diff --git a/package-lock.json b/package-lock.json index cb74b89..342fe41 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6495,6 +6495,8 @@ "ts-morph": "^23.0.0" }, "devDependencies": { + "@kidkender/archmind-laravel-parser": "*", + "@kidkender/archmind-springboot-parser": "*", "@types/jest": "^29.5.0", "@types/js-yaml": "^4.0.9", "@types/node": "^20.0.0", diff --git a/package.json b/package.json index 32891ad..522c144 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "apps/*" ], "scripts": { - "build": "npm run build --workspaces --if-present", + "build": "node scripts/build-workspaces.mjs", "test": "npm run test --workspaces --if-present", "trace": "node apps/cli/dist/index.js trace" }, diff --git a/packages/explainer/tsconfig.json b/packages/explainer/tsconfig.json index fa59074..1819e6a 100644 --- a/packages/explainer/tsconfig.json +++ b/packages/explainer/tsconfig.json @@ -5,5 +5,5 @@ "outDir": "dist" }, "include": ["src"], - "exclude": ["dist", "node_modules"] + "exclude": ["dist", "node_modules", "src/__tests__", "src/benchmark"] } diff --git a/packages/go-parser/src/scanner.ts b/packages/go-parser/src/scanner.ts index 13005a5..468885c 100644 --- a/packages/go-parser/src/scanner.ts +++ b/packages/go-parser/src/scanner.ts @@ -34,7 +34,7 @@ export function isGinProject(root: string): boolean { /** * Walks the project for every `*.go` file (excluding `_test.go` — test * files aren't part of the routing surface and only add noise), skipping - * vendor/build/VCS directories. Returns paths relative to `root`. + * vendor/build/VCS directories. Returns paths relative to `root`, with `/` separators on every OS. */ export function findGoFiles(root: string, opts: ScanOptions = {}): string[] { const out: string[] = [] @@ -63,7 +63,7 @@ function walk(root: string, dir: string, out: string[], depth: number, includeTe if (isDir) { walk(root, abs, out, depth + 1, includeTests) } else if (entry.endsWith(".go") && (includeTests || !entry.endsWith("_test.go"))) { - out.push(relative(root, abs)) + out.push(relative(root, abs).replace(/\\/g, "/")) } } } diff --git a/packages/lsp/build.mjs b/packages/lsp/build.mjs index 02e235b..a670af1 100644 --- a/packages/lsp/build.mjs +++ b/packages/lsp/build.mjs @@ -10,7 +10,10 @@ await build({ platform: "node", format: "cjs", outfile: join(__dirname, "dist/lsp.cjs"), - external: ["tree-sitter", "tree-sitter-php", "tree-sitter-java", "ts-morph"], + // analysis is loaded at runtime from its own install: it pulls in go-parser, + // which needs tree-sitter 0.25 and tree-sitter-go (a native module esbuild + // cannot bundle), while lsp itself runs tree-sitter 0.21. + external: ["tree-sitter", "tree-sitter-php", "tree-sitter-java", "ts-morph", "@kidkender/archmind-analysis"], banner: { js: "#!/usr/bin/env node" }, minify: false, }) diff --git a/packages/mcp-server/src/__tests__/cache.test.ts b/packages/mcp-server/src/__tests__/cache.test.ts index bc0bdb2..17deda6 100644 --- a/packages/mcp-server/src/__tests__/cache.test.ts +++ b/packages/mcp-server/src/__tests__/cache.test.ts @@ -440,12 +440,12 @@ describe("getGraphs() Go/Gin (integration)", () => { test("re-parses after a tracked file's mtime changes", () => { const { tmp, mainFile } = makeGinTmp() getGraphs(tmp) - const before = _getGoTrackedFiles(tmp)!.get(join("cmd", "server", "main.go"))! + const before = _getGoTrackedFiles(tmp)!.get("cmd/server/main.go")! bumpMtime(mainFile) getGraphs(tmp) - const after = _getGoTrackedFiles(tmp)!.get(join("cmd", "server", "main.go"))! + const after = _getGoTrackedFiles(tmp)!.get("cmd/server/main.go")! expect(after).toBeGreaterThan(before) }) diff --git a/packages/nestjs-parser/package.json b/packages/nestjs-parser/package.json index f5a3753..2914065 100644 --- a/packages/nestjs-parser/package.json +++ b/packages/nestjs-parser/package.json @@ -41,6 +41,8 @@ "ts-morph": "^23.0.0" }, "devDependencies": { + "@kidkender/archmind-laravel-parser": "*", + "@kidkender/archmind-springboot-parser": "*", "@types/jest": "^29.5.0", "@types/js-yaml": "^4.0.9", "@types/node": "^20.0.0", diff --git a/scripts/build-workspaces.mjs b/scripts/build-workspaces.mjs new file mode 100644 index 0000000..69acaa6 --- /dev/null +++ b/scripts/build-workspaces.mjs @@ -0,0 +1,65 @@ +#!/usr/bin/env node +// Builds every workspace in dependency order. +// +// `npm run build --workspaces` builds in alphabetical order, so on a clean +// checkout (no dist/ yet) a package is compiled before the packages it imports +// — `aql` before `protocol` — and the build fails. This script orders the +// workspaces so each one is built after the workspaces it depends on. +// +// `dependencies` / `peerDependencies` are hard edges. `devDependencies` are soft: +// honored when possible, dropped only to get past a cycle (explainer's tests use +// scorer, and scorer → llm-client → prompt-builder → explainer). + +import { readFileSync, readdirSync, existsSync } from "fs" +import { join } from "path" +import { spawnSync } from "child_process" +import { fileURLToPath } from "url" + +const root = fileURLToPath(new URL("..", import.meta.url)) +const rootPkg = JSON.parse(readFileSync(join(root, "package.json"), "utf-8")) + +const workspaces = [] +for (const pattern of rootPkg.workspaces) { + const base = pattern.replace(/\/\*$/, "") + for (const name of readdirSync(join(root, base)).sort()) { + const dir = `${base}/${name}` + const pkgPath = join(root, dir, "package.json") + if (!existsSync(pkgPath)) continue + const pkg = JSON.parse(readFileSync(pkgPath, "utf-8")) + workspaces.push({ dir, pkg }) + } +} + +const byName = new Map(workspaces.map((w) => [w.pkg.name, w])) +const internal = (deps) => Object.keys(deps ?? {}).filter((d) => byName.has(d)) +for (const w of workspaces) { + w.hard = new Set([...internal(w.pkg.dependencies), ...internal(w.pkg.peerDependencies)]) + w.soft = new Set(internal(w.pkg.devDependencies).filter((d) => !w.hard.has(d))) +} + +const order = [] +const done = new Set() +while (order.length < workspaces.length) { + const pending = workspaces.filter((w) => !done.has(w.pkg.name)) + const ready = (w, useSoft) => + [...w.hard].every((d) => done.has(d)) && (!useSoft || [...w.soft].every((d) => done.has(d))) + const next = pending.find((w) => ready(w, true)) ?? pending.find((w) => ready(w, false)) + if (!next) { + console.error(`Dependency cycle among: ${pending.map((w) => w.pkg.name).join(", ")}`) + process.exit(1) + } + order.push(next) + done.add(next.pkg.name) +} + +const npm = process.platform === "win32" ? "npm.cmd" : "npm" +for (const w of order) { + if (!w.pkg.scripts?.build) continue + console.log(`\n▶ ${w.pkg.name} (${w.dir})`) + const result = spawnSync(npm, ["run", "build", "-w", w.dir], { cwd: root, stdio: "inherit", shell: process.platform === "win32" }) + if (result.status !== 0) { + console.error(`\n✘ build failed in ${w.dir}`) + process.exit(result.status ?? 1) + } +} +console.log(`\n✔ built ${order.filter((w) => w.pkg.scripts?.build).length} workspaces`) From 85d12b29fd32798456b0aa4bb7fd561a96d6a132 Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 11:43:01 +0700 Subject: [PATCH 06/25] feat(express-parser): add package skeleton for an Express.js parser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- package-lock.json | 23 ++++ packages/express-parser/jest.config.js | 16 +++ packages/express-parser/package.json | 49 ++++++++ .../src/__tests__/skeleton.test.ts | 105 ++++++++++++++++++ packages/express-parser/src/adapter.ts | 50 +++++++++ packages/express-parser/src/detect.ts | 65 +++++++++++ packages/express-parser/src/index.ts | 3 + packages/express-parser/src/project.ts | 35 ++++++ packages/express-parser/src/scanner.ts | 62 +++++++++++ packages/express-parser/tsconfig.json | 9 ++ 10 files changed, 417 insertions(+) create mode 100644 packages/express-parser/jest.config.js create mode 100644 packages/express-parser/package.json create mode 100644 packages/express-parser/src/__tests__/skeleton.test.ts create mode 100644 packages/express-parser/src/adapter.ts create mode 100644 packages/express-parser/src/detect.ts create mode 100644 packages/express-parser/src/index.ts create mode 100644 packages/express-parser/src/project.ts create mode 100644 packages/express-parser/src/scanner.ts create mode 100644 packages/express-parser/tsconfig.json diff --git a/package-lock.json b/package-lock.json index 342fe41..1f6c7ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1431,6 +1431,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 @@ -6289,6 +6293,25 @@ "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": { + "@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", 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..7c5de09 --- /dev/null +++ b/packages/express-parser/package.json @@ -0,0 +1,49 @@ +{ + "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": { + "@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__/skeleton.test.ts b/packages/express-parser/src/__tests__/skeleton.test.ts new file mode 100644 index 0000000..f557194 --- /dev/null +++ b/packages/express-parser/src/__tests__/skeleton.test.ts @@ -0,0 +1,105 @@ +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("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("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..494f4f6 --- /dev/null +++ b/packages/express-parser/src/adapter.ts @@ -0,0 +1,50 @@ +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" + +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. + * + * v0.1.0 skeleton: the project is loaded; route extraction lands next. + */ +export function parseExpressSources(sources: SourceFile[], _opts: ParseExpressOptions = {}): IntermediateExecutionGraph[] { + if (sources.length === 0) return [] + createExpressProject(sources) + return [] +} + +/** + * 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) + return parseExpressSources(readSourceFiles(appRoot), { + authGates: userConfig?.guards?.auth_gate, + authzChecks: userConfig?.guards?.authz_check, + ownershipSources: userConfig?.authorization?.ownershipSources, + ...opts, + }) +} + +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..736c95a --- /dev/null +++ b/packages/express-parser/src/detect.ts @@ -0,0 +1,65 @@ +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"]) + +/** 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 + + 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/index.ts b/packages/express-parser/src/index.ts new file mode 100644 index 0000000..4675b2d --- /dev/null +++ b/packages/express-parser/src/index.ts @@ -0,0 +1,3 @@ +export { parseExpressSources, parseExpressProjectAt, ExpressAdapter, type ParseExpressOptions } from "./adapter.js" +export { isExpressProject, findExpressRoot } from "./detect.js" +export { findSourceFiles, readSourceFiles, type SourceFile } from "./scanner.js" 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/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/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"] +} From 6114a8e9d183ee8f960a2a74ed2d84e4e145441f Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 11:56:06 +0700 Subject: [PATCH 07/25] feat(express-parser): extract routes, mounts and middleware chains - 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. --- .../src/__tests__/routes.test.ts | 379 ++++++++++++ packages/express-parser/src/adapter.ts | 7 +- packages/express-parser/src/evaluator.ts | 542 ++++++++++++++++++ packages/express-parser/src/graph.ts | 47 ++ packages/express-parser/src/index.ts | 2 + packages/express-parser/src/routes.ts | 372 ++++++++++++ packages/express-parser/src/scope.ts | 131 +++++ 7 files changed, 1477 insertions(+), 3 deletions(-) create mode 100644 packages/express-parser/src/__tests__/routes.test.ts create mode 100644 packages/express-parser/src/evaluator.ts create mode 100644 packages/express-parser/src/graph.ts create mode 100644 packages/express-parser/src/routes.ts create mode 100644 packages/express-parser/src/scope.ts 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..9d873cb --- /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.UNKNOWN_MIDDLEWARE, IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, 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/adapter.ts b/packages/express-parser/src/adapter.ts index 494f4f6..d94ac46 100644 --- a/packages/express-parser/src/adapter.ts +++ b/packages/express-parser/src/adapter.ts @@ -3,6 +3,8 @@ import type { IntermediateExecutionGraph, SemanticAdapter } from "@kidkender/arc import { findExpressRoot } from "./detect.js" import { readSourceFiles, type SourceFile } from "./scanner.js" import { createExpressProject } from "./project.js" +import { extractRoutes } from "./routes.js" +import { routeToGraph } from "./graph.js" export interface ParseExpressOptions { /** Middleware / function names classified as ir:auth_gate (archmind.json `guards.auth_gate`). */ @@ -18,12 +20,11 @@ export interface ParseExpressOptions { * route. Takes the file list directly so tests can use synthetic fixtures; * parseExpressProjectAt reads a project from disk. * - * v0.1.0 skeleton: the project is loaded; route extraction lands next. */ export function parseExpressSources(sources: SourceFile[], _opts: ParseExpressOptions = {}): IntermediateExecutionGraph[] { if (sources.length === 0) return [] - createExpressProject(sources) - return [] + const { routes } = extractRoutes(createExpressProject(sources)) + return routes.map(routeToGraph) } /** diff --git a/packages/express-parser/src/evaluator.ts b/packages/express-parser/src/evaluator.ts new file mode 100644 index 0000000..e7adbd3 --- /dev/null +++ b/packages/express-parser/src/evaluator.ts @@ -0,0 +1,542 @@ +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 } + | { 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.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 "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 }] + return this.evaluate(member.getInitializer()) + } + return [] + } + + // ------------------------------------------------------------------------- + // 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 (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 [] + } + 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 "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..1463898 --- /dev/null +++ b/packages/express-parser/src/graph.ts @@ -0,0 +1,47 @@ +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" + +const ADAPTER_VERSION = "0.1.0" + +/** + * One graph per route: its middleware in execution order, then the handler, + * linked by `precedes`. Middleware is ir:unknown_middleware until it is + * classified (auth, authorization, validation). + */ +export function routeToGraph(route: ExpressRoute): IntermediateExecutionGraph { + const nodes: ExecutionNode[] = route.middleware.map((mw, i) => ({ + id: `mw_${i}`, + type: IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, + symbol: mw.text, + file: mw.file, + line: mw.line, + ...(mw.args.length > 0 ? { args: mw.args } : {}), + role: "middleware", + })) + nodes.push({ + id: "handler", + type: IR_NODE_TYPES.BUSINESS_HANDLER, + symbol: route.handler.symbol, + file: route.handler.file, + line: route.handler.line, + role: "handler", + }) + + 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" }) + } + + 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, + } +} diff --git a/packages/express-parser/src/index.ts b/packages/express-parser/src/index.ts index 4675b2d..ea5236e 100644 --- a/packages/express-parser/src/index.ts +++ b/packages/express-parser/src/index.ts @@ -1,3 +1,5 @@ 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" diff --git a/packages/express-parser/src/routes.ts b/packages/express-parser/src/routes.ts new file mode 100644 index 0000000..8f01476 --- /dev/null +++ b/packages/express-parser/src/routes.ts @@ -0,0 +1,372 @@ +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): ExtractResult { + const ev = new Evaluator(ep) + 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()) + } + 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/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 +} From 6a16f2876cab98f9ad4cd93895f4946bcd0d09d7 Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 12:06:15 +0700 Subject: [PATCH 08/25] feat(express-parser): classify middleware into auth, authorization and validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../src/__tests__/middleware.test.ts | 192 ++++++++++++++++ .../src/__tests__/routes.test.ts | 2 +- packages/express-parser/src/adapter.ts | 5 +- packages/express-parser/src/evaluator.ts | 15 +- packages/express-parser/src/graph.ts | 49 +++- packages/express-parser/src/index.ts | 1 + packages/express-parser/src/middleware.ts | 217 ++++++++++++++++++ packages/express-parser/src/routes.ts | 6 + 8 files changed, 470 insertions(+), 17 deletions(-) create mode 100644 packages/express-parser/src/__tests__/middleware.test.ts create mode 100644 packages/express-parser/src/middleware.ts 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..8241912 --- /dev/null +++ b/packages/express-parser/src/__tests__/middleware.test.ts @@ -0,0 +1,192 @@ +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("(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 index 9d873cb..ec9c436 100644 --- a/packages/express-parser/src/__tests__/routes.test.ts +++ b/packages/express-parser/src/__tests__/routes.test.ts @@ -361,7 +361,7 @@ describe("parseExpressSources — graphs", () => { expect(g.entrypoint).toBe("POST /orders") expect(g.framework).toBe("express") expect(g.nodes.map((n) => n.type)).toEqual([ - IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, IR_NODE_TYPES.BUSINESS_HANDLER, + 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"]) diff --git a/packages/express-parser/src/adapter.ts b/packages/express-parser/src/adapter.ts index d94ac46..c7f627b 100644 --- a/packages/express-parser/src/adapter.ts +++ b/packages/express-parser/src/adapter.ts @@ -19,12 +19,11 @@ export interface ParseExpressOptions { * 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[] { +export function parseExpressSources(sources: SourceFile[], opts: ParseExpressOptions = {}): IntermediateExecutionGraph[] { if (sources.length === 0) return [] const { routes } = extractRoutes(createExpressProject(sources)) - return routes.map(routeToGraph) + return routes.map((r) => routeToGraph(r, { authGates: opts.authGates, authzChecks: opts.authzChecks })) } /** diff --git a/packages/express-parser/src/evaluator.ts b/packages/express-parser/src/evaluator.ts index e7adbd3..28a9e12 100644 --- a/packages/express-parser/src/evaluator.ts +++ b/packages/express-parser/src/evaluator.ts @@ -19,6 +19,13 @@ export type Value = | { 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 } @@ -159,6 +166,8 @@ export class Evaluator { 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": { @@ -234,6 +243,8 @@ export class Evaluator { } } 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) } @@ -245,8 +256,9 @@ export class Evaluator { 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 [] + 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 @@ -525,6 +537,7 @@ function valueKey(v: Value): string { 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}` diff --git a/packages/express-parser/src/graph.ts b/packages/express-parser/src/graph.ts index 1463898..e72eb31 100644 --- a/packages/express-parser/src/graph.ts +++ b/packages/express-parser/src/graph.ts @@ -1,24 +1,44 @@ 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" 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 ir:unknown_middleware until it is - * classified (auth, authorization, validation). + * linked by `precedes`. Middleware is classified (classifyMiddleware); + * infrastructure such as body parsers, logging and CORS is left out. */ -export function routeToGraph(route: ExpressRoute): IntermediateExecutionGraph { - const nodes: ExecutionNode[] = route.middleware.map((mw, i) => ({ - id: `mw_${i}`, - type: IR_NODE_TYPES.UNKNOWN_MIDDLEWARE, - symbol: mw.text, - file: mw.file, - line: mw.line, - ...(mw.args.length > 0 ? { args: mw.args } : {}), - role: "middleware", - })) +export function routeToGraph(route: ExpressRoute, opts: ClassifyOptions = {}): IntermediateExecutionGraph { + const nodes: ExecutionNode[] = [] + for (const mw of route.middleware) { + for (const kind of classifyMiddleware(mw, opts).kinds) { + const spec = NODE_FOR_KIND[kind] + if (!spec) continue + nodes.push({ + id: `mw_${nodes.length}`, + type: spec.type, + symbol: shorten(mw.text), + file: mw.file, + line: mw.line, + ...(mw.args.length > 0 ? { args: mw.args } : {}), + role: spec.role, + }) + } + } nodes.push({ id: "handler", type: IR_NODE_TYPES.BUSINESS_HANDLER, @@ -45,3 +65,8 @@ export function routeToGraph(route: ExpressRoute): IntermediateExecutionGraph { 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/index.ts b/packages/express-parser/src/index.ts index ea5236e..b18f0c5 100644 --- a/packages/express-parser/src/index.ts +++ b/packages/express-parser/src/index.ts @@ -3,3 +3,4 @@ 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..b2216aa --- /dev/null +++ b/packages/express-parser/src/middleware.ts @@ -0,0 +1,217 @@ +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"], +] + +function packageKind(values: Value[]): { kind: MiddlewareKind; pkg: string } | null { + for (const v of values) { + if (v.kind !== "external" && v.kind !== "externalCall") continue + // 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)", + "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)", + ].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*\\)", +].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/ +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]/ + +function bodyKinds(fn: Node): MiddlewareKind[] { + const text = fn.getText() + const kinds: MiddlewareKind[] = [] + if (BODY_AUTH.test(text)) 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/routes.ts b/packages/express-parser/src/routes.ts index 8f01476..c68a6cc 100644 --- a/packages/express-parser/src/routes.ts +++ b/packages/express-parser/src/routes.ts @@ -202,6 +202,12 @@ function chainEntry(node: Node, values: Value[], ev: Evaluator, env: Env): Chain 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() From 2d36c79a47b68fc3def12908ae6b906e0e2668db Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 13:00:10 +0700 Subject: [PATCH 09/25] feat(express-parser): service calls, transactions and ownership from handler bodies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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:", 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. --- .../src/__tests__/handler.test.ts | 179 ++++++++++++++++++ packages/express-parser/src/adapter.ts | 9 +- packages/express-parser/src/evaluator.ts | 56 +++++- packages/express-parser/src/graph.ts | 17 +- packages/express-parser/src/handler.ts | 149 +++++++++++++++ packages/express-parser/src/routes.ts | 3 +- 6 files changed, 406 insertions(+), 7 deletions(-) create mode 100644 packages/express-parser/src/__tests__/handler.test.ts create mode 100644 packages/express-parser/src/handler.ts 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..b0c89c4 --- /dev/null +++ b/packages/express-parser/src/__tests__/handler.test.ts @@ -0,0 +1,179 @@ +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("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/adapter.ts b/packages/express-parser/src/adapter.ts index c7f627b..6c2e739 100644 --- a/packages/express-parser/src/adapter.ts +++ b/packages/express-parser/src/adapter.ts @@ -4,6 +4,8 @@ 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 { @@ -22,8 +24,11 @@ export interface ParseExpressOptions { */ export function parseExpressSources(sources: SourceFile[], opts: ParseExpressOptions = {}): IntermediateExecutionGraph[] { if (sources.length === 0) return [] - const { routes } = extractRoutes(createExpressProject(sources)) - return routes.map((r) => routeToGraph(r, { authGates: opts.authGates, authzChecks: opts.authzChecks })) + 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 }))) } /** diff --git a/packages/express-parser/src/evaluator.ts b/packages/express-parser/src/evaluator.ts index 28a9e12..9e43942 100644 --- a/packages/express-parser/src/evaluator.ts +++ b/packages/express-parser/src/evaluator.ts @@ -97,6 +97,14 @@ export class Evaluator { 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) } @@ -208,9 +216,53 @@ export class Evaluator { 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 }] - return this.evaluate(member.getInitializer()) + const init = member.getInitializer() + if (init) return this.evaluate(init) + const typed = this.instanceOfType(member.getTypeNode()) + if (typed.length > 0) return typed } - return [] + 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 } // ------------------------------------------------------------------------- diff --git a/packages/express-parser/src/graph.ts b/packages/express-parser/src/graph.ts index e72eb31..f1e0be6 100644 --- a/packages/express-parser/src/graph.ts +++ b/packages/express-parser/src/graph.ts @@ -2,6 +2,7 @@ import { IR_NODE_TYPES, IR_EDGE_RELATIONS, IR_VERSION } from "@kidkender/archmin 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" @@ -22,7 +23,7 @@ const NODE_FOR_KIND: Partial() + + 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) || seenServices.has(fn)) continue + if (!isServiceTarget(callee, fn, handler)) continue + seenServices.add(fn) + serviceFns.push(fn) + if (facts.services.length < MAX_SERVICES) { + facts.services.push({ symbol: calleeSymbol(callee), file: relativePath(fn.getSourceFile()), line: fn.getStartLineNumber() }) + } + } + } + + // one hop: transactions and ownership inside the services the handler calls + for (const fn of serviceFns) { + 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): CodeRef | null { + const callee = call.getExpression() + if (!Node.isPropertyAccessExpression(callee)) return null + const method = callee.getName() + if (TXN_METHODS.has(method)) return ref(calleeSymbol(callee), call) + if (method !== "transaction") return null + const receiver = callee.getExpression() + const tail = receiver.getText().replace(/\s/g, "").split(".").pop() ?? "" + if (DB_RECEIVER.test(tail)) return ref(calleeSymbol(callee), call) + const fromOrm = ev.evaluate(receiver).some((v) => + (v.kind === "external" || v.kind === "externalCall") && + ORM_PACKAGES.some((pkg) => v.name === pkg || v.name.startsWith(`${pkg}.`))) + return fromOrm ? ref(calleeSymbol(callee), call) : null +} + +/** Where services live: a file or folder named for the layer. */ +const SERVICE_PATH = /(service|repositor|repo|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\./, "") +} + +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/routes.ts b/packages/express-parser/src/routes.ts index c68a6cc..0178962 100644 --- a/packages/express-parser/src/routes.ts +++ b/packages/express-parser/src/routes.ts @@ -72,8 +72,7 @@ type Registration = RouteRegistration | UseRegistration const MAX_MOUNT_DEPTH = 12 -export function extractRoutes(ep: ExpressProject): ExtractResult { - const ev = new Evaluator(ep) +export function extractRoutes(ep: ExpressProject, ev: Evaluator = new Evaluator(ep)): ExtractResult { const registrations: Registration[] = [] const unresolvedPaths: ExtractResult["unresolvedPaths"] = [] From 7ff5e6a594e1bde1bae6e4a2eb23863ef6597fc4 Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 13:22:07 +0700 Subject: [PATCH 10/25] feat: wire the Express parser into analysis, the CLI and the MCP server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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). --- apps/cli/build.mjs | 1 + apps/cli/package.json | 1 + apps/cli/src/utils/parse-project.ts | 11 ++++- package-lock.json | 3 ++ packages/analysis/build.mjs | 1 + packages/analysis/package.json | 1 + packages/analysis/src/analyze.ts | 28 +++++++++++- .../src/__tests__/handler.test.ts | 4 +- .../src/__tests__/skeleton.test.ts | 16 +++++++ packages/express-parser/src/adapter.ts | 10 ++++- packages/express-parser/src/detect.ts | 6 +++ packages/express-parser/src/graph.ts | 9 +++- packages/express-parser/src/handler.ts | 12 +++++- packages/mcp-server/build.mjs | 1 + packages/mcp-server/package.json | 1 + packages/mcp-server/src/cache.ts | 43 ++++++++++++++++++- packages/mcp-server/src/server.ts | 24 +++++------ 17 files changed, 150 insertions(+), 22 deletions(-) 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 1f6c7ef..c69385a 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": "*", @@ -6201,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": "*", @@ -6464,6 +6466,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/src/__tests__/handler.test.ts b/packages/express-parser/src/__tests__/handler.test.ts index b0c89c4..e06aa5d 100644 --- a/packages/express-parser/src/__tests__/handler.test.ts +++ b/packages/express-parser/src/__tests__/handler.test.ts @@ -51,7 +51,7 @@ describe("analyzeHandler — service calls", () => { 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.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 })) }) @@ -82,7 +82,7 @@ describe("analyzeHandler — service calls", () => { `, }), "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"]) + expect(symbolsOf(g, IR_NODE_TYPES.SERVICE_CALL)).toEqual(["users::findAll"]) }) }) diff --git a/packages/express-parser/src/__tests__/skeleton.test.ts b/packages/express-parser/src/__tests__/skeleton.test.ts index f557194..4242b06 100644 --- a/packages/express-parser/src/__tests__/skeleton.test.ts +++ b/packages/express-parser/src/__tests__/skeleton.test.ts @@ -53,6 +53,13 @@ describe("isExpressProject / findExpressRoot", () => { 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" }) @@ -97,6 +104,15 @@ describe("createExpressProject", () => { }) 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", "") diff --git a/packages/express-parser/src/adapter.ts b/packages/express-parser/src/adapter.ts index 6c2e739..097a840 100644 --- a/packages/express-parser/src/adapter.ts +++ b/packages/express-parser/src/adapter.ts @@ -1,3 +1,4 @@ +import { relative } from "path" import { loadUserConfig } from "@kidkender/archmind-protocol" import type { IntermediateExecutionGraph, SemanticAdapter } from "@kidkender/archmind-protocol" import { findExpressRoot } from "./detect.js" @@ -40,12 +41,19 @@ export function parseExpressProjectAt(root: string, opts: ParseExpressOptions = const appRoot = findExpressRoot(root) if (!appRoot) return [] const userConfig = loadUserConfig(root) - return parseExpressSources(readSourceFiles(appRoot), { + 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 { diff --git a/packages/express-parser/src/detect.ts b/packages/express-parser/src/detect.ts index 736c95a..7592aa2 100644 --- a/packages/express-parser/src/detect.ts +++ b/packages/express-parser/src/detect.ts @@ -4,6 +4,9 @@ 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"] @@ -39,6 +42,9 @@ export function findExpressRoot(root: string): string | null { 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 { diff --git a/packages/express-parser/src/graph.ts b/packages/express-parser/src/graph.ts index f1e0be6..869b52c 100644 --- a/packages/express-parser/src/graph.ts +++ b/packages/express-parser/src/graph.ts @@ -26,16 +26,21 @@ const NODE_FOR_KIND: Partial 0 && !(split && kind === "auth_gate") nodes.push({ id: `mw_${nodes.length}`, type: spec.type, symbol: shorten(mw.text), file: mw.file, line: mw.line, - ...(mw.args.length > 0 ? { args: mw.args } : {}), + ...(withArgs ? { args: mw.args } : {}), role: spec.role, }) } diff --git a/packages/express-parser/src/handler.ts b/packages/express-parser/src/handler.ts index 3653041..4590ba6 100644 --- a/packages/express-parser/src/handler.ts +++ b/packages/express-parser/src/handler.ts @@ -56,7 +56,7 @@ export function analyzeHandler(route: ExpressRoute, ev: Evaluator, opts: Handler seenServices.add(fn) serviceFns.push(fn) if (facts.services.length < MAX_SERVICES) { - facts.services.push({ symbol: calleeSymbol(callee), file: relativePath(fn.getSourceFile()), line: fn.getStartLineNumber() }) + facts.services.push({ symbol: serviceSymbol(callee), file: relativePath(fn.getSourceFile()), line: fn.getStartLineNumber() }) } } } @@ -125,6 +125,16 @@ 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() 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 }) => { From 29044d89fc50ae9247352c3da96dd56cd7e089b6 Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 13:31:46 +0700 Subject: [PATCH 11/25] test(express-parser): cross-framework conformance; writes inside transactions - 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). --- package-lock.json | 2 + packages/express-parser/package.json | 2 + .../src/__tests__/cross-framework.test.ts | 91 +++++++++++++ .../src/__tests__/handler.test.ts | 28 ++++ packages/express-parser/src/graph.ts | 8 +- packages/express-parser/src/handler.ts | 125 ++++++++++++++++-- .../cross-framework/auth-authz/express/app.js | 12 ++ .../auth-authz/express/auth.js | 15 +++ .../auth-authz/express/package.json | 5 + .../cross-framework/auth-only/express/app.js | 16 +++ .../cross-framework/auth-only/express/auth.js | 11 ++ .../auth-only/express/package.json | 5 + .../auth-service-call/express/app.js | 12 ++ .../auth-service-call/express/auth.js | 11 ++ .../auth-service-call/express/package.json | 5 + .../auth-service-call/express/task.service.js | 1 + .../auth-transaction/express/app.ts | 19 +++ .../auth-transaction/express/auth.ts | 11 ++ .../auth-transaction/express/data-source.ts | 3 + .../auth-transaction/express/order.entity.ts | 1 + .../auth-transaction/express/package.json | 5 + .../express/payment.entity.ts | 1 + .../auth-validation/express/app.js | 13 ++ .../auth-validation/express/auth.js | 11 ++ .../auth-validation/express/package.json | 5 + 25 files changed, 406 insertions(+), 12 deletions(-) create mode 100644 packages/express-parser/src/__tests__/cross-framework.test.ts create mode 100644 research/cross-framework/auth-authz/express/app.js create mode 100644 research/cross-framework/auth-authz/express/auth.js create mode 100644 research/cross-framework/auth-authz/express/package.json create mode 100644 research/cross-framework/auth-only/express/app.js create mode 100644 research/cross-framework/auth-only/express/auth.js create mode 100644 research/cross-framework/auth-only/express/package.json create mode 100644 research/cross-framework/auth-service-call/express/app.js create mode 100644 research/cross-framework/auth-service-call/express/auth.js create mode 100644 research/cross-framework/auth-service-call/express/package.json create mode 100644 research/cross-framework/auth-service-call/express/task.service.js create mode 100644 research/cross-framework/auth-transaction/express/app.ts create mode 100644 research/cross-framework/auth-transaction/express/auth.ts create mode 100644 research/cross-framework/auth-transaction/express/data-source.ts create mode 100644 research/cross-framework/auth-transaction/express/order.entity.ts create mode 100644 research/cross-framework/auth-transaction/express/package.json create mode 100644 research/cross-framework/auth-transaction/express/payment.entity.ts create mode 100644 research/cross-framework/auth-validation/express/app.js create mode 100644 research/cross-framework/auth-validation/express/auth.js create mode 100644 research/cross-framework/auth-validation/express/package.json diff --git a/package-lock.json b/package-lock.json index c69385a..22e72df 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6304,6 +6304,8 @@ "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", diff --git a/packages/express-parser/package.json b/packages/express-parser/package.json index 7c5de09..9a53c03 100644 --- a/packages/express-parser/package.json +++ b/packages/express-parser/package.json @@ -40,6 +40,8 @@ "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", 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 index e06aa5d..c860fb6 100644 --- a/packages/express-parser/src/__tests__/handler.test.ts +++ b/packages/express-parser/src/__tests__/handler.test.ts @@ -117,6 +117,34 @@ describe("analyzeHandler — transactions", () => { 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 on a handle from an ORM package counts whatever it is named", () => { const g = graph(graphs({ "app.ts": ` diff --git a/packages/express-parser/src/graph.ts b/packages/express-parser/src/graph.ts index 869b52c..d6d4d83 100644 --- a/packages/express-parser/src/graph.ts +++ b/packages/express-parser/src/graph.ts @@ -60,13 +60,19 @@ export function routeToGraph(route: ExpressRoute, opts: ClassifyOptions = {}, fa 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, ...txn, role: "transaction" }) + 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" }) diff --git a/packages/express-parser/src/handler.ts b/packages/express-parser/src/handler.ts index 4590ba6..0ef8ae6 100644 --- a/packages/express-parser/src/handler.ts +++ b/packages/express-parser/src/handler.ts @@ -9,11 +9,21 @@ export interface CodeRef { 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: CodeRef[] + transactions: TransactionRef[] /** The first call to a configured ownership source (archmind.json authorization.ownershipSources). */ ownership: CodeRef | null } @@ -78,23 +88,116 @@ function callsIn(fn: Node): CallExpression[] { return fn.getDescendantsOfKind(SyntaxKind.CallExpression) } -function transactionCall(call: CallExpression, ev: Evaluator): CodeRef | null { +function transactionCall(call: CallExpression, ev: Evaluator): TransactionRef | null { const callee = call.getExpression() if (!Node.isPropertyAccessExpression(callee)) return null const method = callee.getName() - if (TXN_METHODS.has(method)) return ref(calleeSymbol(callee), call) - if (method !== "transaction") return null + 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 tail = receiver.getText().replace(/\s/g, "").split(".").pop() ?? "" - if (DB_RECEIVER.test(tail)) return ref(calleeSymbol(callee), call) - const fromOrm = ev.evaluate(receiver).some((v) => - (v.kind === "external" || v.kind === "externalCall") && - ORM_PACKAGES.some((pkg) => v.name === pkg || v.name.startsWith(`${pkg}.`))) - return fromOrm ? ref(calleeSymbol(callee), call) : null + 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|dao|store|provider|manager|usecase|use-case|model|entit|domain|gateway|client)/i +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 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" } +} From 730823732d3e0dee7df21a1f8abed832b25bed38 Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 13:49:40 +0700 Subject: [PATCH 12/25] feat(express-parser): measure on unseen projects, sharpen classification, 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). --- CHANGELOG.md | 15 ++++ README.md | 15 +++- packages/express-parser/README.md | 80 +++++++++++++++++++ .../src/__tests__/handler.test.ts | 17 ++++ .../src/__tests__/middleware.test.ts | 55 +++++++++++++ packages/express-parser/src/handler.ts | 20 ++--- packages/express-parser/src/middleware.ts | 59 +++++++++++++- research/express-corpus/README.md | 60 ++++++++++++++ research/express-corpus/count-routes.mjs | 50 ++++++++++++ research/express-corpus/measure.mjs | 64 +++++++++++++++ 10 files changed, 422 insertions(+), 13 deletions(-) create mode 100644 packages/express-parser/README.md create mode 100644 research/express-corpus/README.md create mode 100644 research/express-corpus/count-routes.mjs create mode 100644 research/express-corpus/measure.mjs 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/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/src/__tests__/handler.test.ts b/packages/express-parser/src/__tests__/handler.test.ts index c860fb6..5702083 100644 --- a/packages/express-parser/src/__tests__/handler.test.ts +++ b/packages/express-parser/src/__tests__/handler.test.ts @@ -145,6 +145,23 @@ describe("analyzeHandler — transactions", () => { 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": ` diff --git a/packages/express-parser/src/__tests__/middleware.test.ts b/packages/express-parser/src/__tests__/middleware.test.ts index 8241912..04503d3 100644 --- a/packages/express-parser/src/__tests__/middleware.test.ts +++ b/packages/express-parser/src/__tests__/middleware.test.ts @@ -135,6 +135,61 @@ describe("classifyMiddleware — bodies of project middleware", () => { })).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": ` diff --git a/packages/express-parser/src/handler.ts b/packages/express-parser/src/handler.ts index 0ef8ae6..af9da8b 100644 --- a/packages/express-parser/src/handler.ts +++ b/packages/express-parser/src/handler.ts @@ -49,8 +49,11 @@ export function analyzeHandler(route: ExpressRoute, ev: Evaluator, opts: Handler const owners = new Set(opts.ownershipSources ?? []) const params = new Set(parameterNames(handler)) - const serviceFns: Node[] = [] - const seenServices = new Set() + // 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() @@ -61,18 +64,17 @@ export function analyzeHandler(route: ExpressRoute, ev: Evaluator, opts: Handler if (txn) facts.transactions.push(txn) for (const fn of projectFunctions(ev.evaluate(callee))) { - if (fn === handler || isWithin(fn, handler) || seenServices.has(fn)) continue - if (!isServiceTarget(callee, fn, handler)) continue - seenServices.add(fn) - serviceFns.push(fn) - if (facts.services.length < MAX_SERVICES) { + 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 services the handler calls - for (const fn of serviceFns) { + // 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) diff --git a/packages/express-parser/src/middleware.ts b/packages/express-parser/src/middleware.ts index b2216aa..5c53157 100644 --- a/packages/express-parser/src/middleware.ts +++ b/packages/express-parser/src/middleware.ts @@ -73,11 +73,22 @@ const PACKAGE_KINDS: [string, MiddlewareKind][] = [ ["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) { @@ -101,6 +112,8 @@ 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", @@ -112,6 +125,8 @@ const AUTH_NAME = new RegExp( "(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", ) @@ -138,20 +153,60 @@ const BODY_AUTH = new RegExp([ "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/ +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)) kinds.push("auth_gate") + 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"] 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(" ")}`) + } + } +} From 78e2026382368f29bd71e774ed7420cc731dfc1d Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 13:57:41 +0700 Subject: [PATCH 13/25] fix: trace script path, flaky tree-sitter test workers, silent graph-pass catches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - package.json: `npm run trace` pointed at apps/cli/dist/index.js; the CLI builds to index.cjs. - retrieval, nestjs-parser, mcp-server: maxWorkers 50 so each test file gets its own process. Their tests load the tree-sitter parsers (Laravel, Spring Boot, Go), whose module-level Parser fails intermittently when Jest reuses a worker across files — retrieval's cross-framework test failed 15 cases once and passed on rerun. Same fix laravel-parser already has. - laravel-parser graph-augmenter: the transaction, isolation, audit-log and nested service-call passes, and a queued job's handle(), no longer swallow errors silently. The parsers already turn unreadable files into empty results, so what reaches these catches is a bug; it is now reported on stderr with the pass and file, and the pass is skipped as before. --- package.json | 2 +- .../laravel-parser/src/graph-augmenter.ts | 22 ++++++++++++++----- packages/mcp-server/jest.config.js | 4 ++++ packages/nestjs-parser/jest.config.js | 4 ++++ packages/retrieval/jest.config.js | 4 ++++ 5 files changed, 30 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 32891ad..8eced82 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "scripts": { "build": "npm run build --workspaces --if-present", "test": "npm run test --workspaces --if-present", - "trace": "node apps/cli/dist/index.js trace" + "trace": "node apps/cli/dist/index.cjs trace" }, "overrides": { "js-yaml": "^4.2.0" diff --git a/packages/laravel-parser/src/graph-augmenter.ts b/packages/laravel-parser/src/graph-augmenter.ts index 40e9501..c1d064b 100644 --- a/packages/laravel-parser/src/graph-augmenter.ts +++ b/packages/laravel-parser/src/graph-augmenter.ts @@ -11,6 +11,17 @@ import { IR_NODE_TYPES, IR_EDGE_RELATIONS, IR_VERSION } from "@kidkender/archmin const ADAPTER_VERSION = "0.1.0" +/** + * A graph pass that threw is skipped so the rest of the route's graph still + * comes out, but it is reported: the parsers already turn unreadable files into + * empty results, so what reaches these catches is a bug, and a silent catch made + * it read as "nothing found here". + */ +function reportSkipped(pass: string, file: string | undefined, err: unknown): void { + const reason = err instanceof Error ? err.message : String(err) + console.warn(`[archmind] laravel-parser: ${pass} skipped for ${file ?? ""}: ${reason}`) +} + // ---- Cached parse-op wrappers -------------------------------------------- type CtrlL1 = ReturnType @@ -818,14 +829,14 @@ function expandServiceCalls( addTransactionNodes(nodes, edges, scNode.id, txnResult.blocks, l1?.serviceCalls ?? []) budget.remaining -= txnResult.blocks.length * 3 } - } catch { /* file unreadable or parse error — skip gracefully */ } + } catch (err) { reportSkipped("transaction pass", scNode.file, err) } // Isolation/query pass inside service method try { const isoResult = isoRes(cache, filePath, isoConv, methodName) addIsolationNodes(nodes, edges, scNode.id, isoResult) budget.remaining -= isoResult.modelQueries.length - } catch { /* skip */ } + } catch (err) { reportSkipped("isolation pass", scNode.file, err) } // Audit-log pass inside service method (IR v1.5 Phase 5) try { @@ -836,7 +847,7 @@ function expandServiceCalls( budget.remaining -= auditCalls.length } } - } catch { /* skip */ } + } catch (err) { reportSkipped("audit-log pass", scNode.file, err) } // Deeper service calls from this service method try { @@ -862,7 +873,7 @@ function expandServiceCalls( const guardNodes = addSelfGuardClauseNodes(nodes, edges, scNode.id, scNode.file, scClass ?? "", l1.selfGuardCalls, newSvcNodes) budget.remaining -= guardNodes.length } - } catch { /* skip */ } + } catch (err) { reportSkipped("nested service-call pass", scNode.file, err) } } expandServiceCalls(nodes, edges, nextServiceNodes, projectRoot, config, depth - 1, visited, budget, focus, cache) @@ -1254,7 +1265,8 @@ function expandJobBody( let l1: ReturnType try { l1 = parseControllerMethod(filePath, "handle") - } catch { + } catch (err) { + reportSkipped("queued job handle()", jobNode.file, err) return } if (!l1) return diff --git a/packages/mcp-server/jest.config.js b/packages/mcp-server/jest.config.js index c158c8b..cfeae98 100644 --- a/packages/mcp-server/jest.config.js +++ b/packages/mcp-server/jest.config.js @@ -2,6 +2,10 @@ export default { preset: "ts-jest/presets/default-esm", testEnvironment: "node", + // The server's caches load the Laravel and Go parsers, whose module-level + // tree-sitter Parser intermittently fails when Jest reuses one worker process + // across test files (see packages/laravel-parser/jest.config.js). + maxWorkers: 50, extensionsToTreatAsEsm: [".ts"], testPathIgnorePatterns: ["/node_modules/", "/dist/"], moduleNameMapper: { diff --git a/packages/nestjs-parser/jest.config.js b/packages/nestjs-parser/jest.config.js index 29918b5..ae35050 100644 --- a/packages/nestjs-parser/jest.config.js +++ b/packages/nestjs-parser/jest.config.js @@ -2,6 +2,10 @@ export default { preset: "ts-jest/presets/default-esm", testEnvironment: "node", + // The cross-framework tests load the Laravel and Spring Boot parsers, whose + // module-level tree-sitter Parser intermittently fails when Jest reuses one + // worker process across test files (see packages/laravel-parser/jest.config.js). + maxWorkers: 50, extensionsToTreatAsEsm: [".ts"], testPathIgnorePatterns: ["/node_modules/", "/dist/", "/fixtures/"], moduleNameMapper: { diff --git a/packages/retrieval/jest.config.js b/packages/retrieval/jest.config.js index c158c8b..04eb59f 100644 --- a/packages/retrieval/jest.config.js +++ b/packages/retrieval/jest.config.js @@ -2,6 +2,10 @@ export default { preset: "ts-jest/presets/default-esm", testEnvironment: "node", + // These tests load the Laravel / NestJS parsers, whose module-level tree-sitter + // Parser intermittently fails when Jest reuses one worker process across test + // files (see packages/laravel-parser/jest.config.js). One process per file. + maxWorkers: 50, extensionsToTreatAsEsm: [".ts"], testPathIgnorePatterns: ["/node_modules/", "/dist/"], moduleNameMapper: { From ac67aed0416b3387353dca2c4bca589bb9d286ae Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 14:38:39 +0700 Subject: [PATCH 14/25] test(laravel-parser): a graph pass that throws inside a service is reported and skipped The isolation parser is made to throw for the service file only; the test checks the stderr warning names the pass, the file and the error, that the rest of the graph (the service's calls, the transaction) is still built, and that later passes of the same service (its guard clause) still run. --- .../graph-augmenter-skipped-pass.test.ts | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 packages/laravel-parser/src/__tests__/graph-augmenter-skipped-pass.test.ts diff --git a/packages/laravel-parser/src/__tests__/graph-augmenter-skipped-pass.test.ts b/packages/laravel-parser/src/__tests__/graph-augmenter-skipped-pass.test.ts new file mode 100644 index 0000000..3393594 --- /dev/null +++ b/packages/laravel-parser/src/__tests__/graph-augmenter-skipped-pass.test.ts @@ -0,0 +1,60 @@ +import { describe, test, expect, jest, beforeAll, afterAll } from "@jest/globals" +import { join, dirname } from "path" +import { fileURLToPath } from "url" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" + +// A graph pass inside a service method that throws is skipped and reported on +// stderr; the rest of the route's graph — earlier passes, later passes of the +// same service — still comes out. The isolation parser is made to throw for the +// service file only, so the controller-level passes run normally. + +jest.unstable_mockModule("../isolation-parser.js", () => ({ + parseIsolation: (filePath: string) => { + if (filePath.replace(/\\/g, "/").includes("app/Services/UserRepo.php")) throw new Error("boom in isolation") + return { modelQueries: [], modelWrites: [], readsTenantFromContainer: false } + }, +})) + +const { augmentGraph } = await import("../graph-augmenter.js") + +const FIXTURES = join(dirname(fileURLToPath(import.meta.url)), "fixtures") + +const SKELETON: IntermediateExecutionGraph = { + entrypoint: "DELETE /users/{user}", + method: "DELETE", path: "/users/{user}", + nodes: [{ + id: "ctrl_usercontroller_destroy", type: "ir:business_handler", + symbol: "UserController::destroy", role: "handler", + file: "app/Http/Controllers/UserController.php", + }], + edges: [], + annotations: [], +} + +describe("augmentGraph — a pass that throws inside a service", () => { + let warn: ReturnType + let graph: IntermediateExecutionGraph + + beforeAll(() => { + warn = jest.spyOn(console, "warn").mockImplementation(() => {}) + graph = augmentGraph(SKELETON, { projectRoot: FIXTURES }) + }) + + afterAll(() => warn.mockRestore()) + + test("is reported with the pass, the file and the error", () => { + const messages = warn.mock.calls.map((c: unknown[]) => String(c[0])) + expect(messages).toContainEqual( + "[archmind] laravel-parser: isolation pass skipped for app/Services/UserRepo.php: boom in isolation", + ) + }) + + test("does not stop the rest of the graph: the service's calls and the transaction are still there", () => { + expect(graph.nodes.some((n) => n.type === "ir:service_call" && n.symbol === "User::apiTokens()->delete")).toBe(true) + expect(graph.nodes.some((n) => n.type === "ir:txn_boundary" && n.symbol === "DB::transaction")).toBe(true) + }) + + test("does not stop the later passes of the same service: its guard clause is still found", () => { + expect(graph.nodes.find((n) => n.symbol === "UserRepo::ensureDeletable")?.type).toBe("ir:guard_clause") + }) +}) From 16bc3d54fa120957146041463f34a3f3be635b03 Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 15:09:13 +0700 Subject: [PATCH 15/25] fix(nestjs-parser): link transaction writes with ir:wraps, not "within_transaction" "within_transaction" is neither an IR relation nor a tracked legacy one, so validateGraph reported it as unknown. None of the conformance fixtures opened a transaction, which is how it went unnoticed. Writes now hang off the transaction by ir:wraps, as in Laravel and Express graphs (nothing reads the old relation). New conformance suite on the auth-transaction fixture; it fails on the old emitter. --- .../src/__tests__/ir-conformance.test.ts | 33 +++++++++++++++++++ .../nestjs-parser/src/emitters/ir-emitter.ts | 5 +-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/packages/nestjs-parser/src/__tests__/ir-conformance.test.ts b/packages/nestjs-parser/src/__tests__/ir-conformance.test.ts index 72318ce..94b1676 100644 --- a/packages/nestjs-parser/src/__tests__/ir-conformance.test.ts +++ b/packages/nestjs-parser/src/__tests__/ir-conformance.test.ts @@ -121,3 +121,36 @@ describe("IR conformance — NestJS global-guard fixture", () => { expect(unknown).toHaveLength(0) }) }) + +// --------------------------------------------------------------------------- +// Suite 4: Transaction fixture (txn boundary + writes) +// None of the fixtures above opens a transaction, which is how a non-IR edge +// relation between a transaction and its writes went unnoticed. +// --------------------------------------------------------------------------- + +describe("IR conformance — NestJS transaction fixture", () => { + let graphs: IntermediateExecutionGraph[] + + beforeAll(() => { + graphs = parseNestJSProject(join(process.cwd(), "../../research/cross-framework/auth-transaction/nestjs")) + }) + + test("the fixture opens a transaction with writes", () => { + const types = graphs.flatMap((g) => g.nodes.map((n) => n.type)) + expect(types).toContain("ir:txn_boundary") + expect(types).toContain("ir:txn_write") + }) + + test("no unknown node types or edge relations", () => { + expect(unknownOnly(allGraphViolations(graphs))).toEqual([]) + }) + + test("writes hang off the transaction by ir:wraps", () => { + const [g] = graphs + const txn = g.nodes.find((n) => n.type === "ir:txn_boundary")! + const writes = g.nodes.filter((n) => n.type === "ir:txn_write") + for (const w of writes) { + expect(g.edges).toContainEqual(expect.objectContaining({ from: txn.id, to: w.id, relation: "ir:wraps" })) + } + }) +}) diff --git a/packages/nestjs-parser/src/emitters/ir-emitter.ts b/packages/nestjs-parser/src/emitters/ir-emitter.ts index 0ba9f7b..f036e27 100644 --- a/packages/nestjs-parser/src/emitters/ir-emitter.ts +++ b/packages/nestjs-parser/src/emitters/ir-emitter.ts @@ -1,5 +1,5 @@ import type { IntermediateExecutionGraph, ExecutionNode, ExecutionEdge, DTOSchema, EntrypointDescriptor } from "@kidkender/archmind-protocol" -import { IR_VERSION, IR_NODE_TYPES } from "@kidkender/archmind-protocol" +import { IR_VERSION, IR_NODE_TYPES, IR_EDGE_RELATIONS } from "@kidkender/archmind-protocol" import type { NestJSSemanticRoute } from "../types.js" const ADAPTER_VERSION = "0.2.0" @@ -156,10 +156,11 @@ function emitGraph( symbol: `${w.entity}::${w.operation}`, role: "persistence", }) + // ir:wraps, as Laravel and Express emit it ("within_transaction" is not an IR relation) edges.push({ from: txnId, to: writeId, - relation: "within_transaction", + relation: IR_EDGE_RELATIONS.WRAPS, traceability: "static", }) } From b3093374d7207259b9315602fad847675ee26181 Mon Sep 17 00:00:00 2001 From: kidkender Date: Wed, 11 Nov 2026 15:09:13 +0700 Subject: [PATCH 16/25] fix(explainer): only a Laravel FormRequest counts as an authorization layer over_authorized_route counted every ir:validation_gate as a third authorization layer ("FormRequest::authorize"), and delegated_validation reported validators as delegating authorization. Both are about Laravel's FormRequest::authorize(); a NestJS ValidationPipe, Spring @Valid, Gin binding or Express celebrate / express-validator only checks the input. They fired on ordinary authenticated, role-checked, validated routes outside Laravel (on one Express project: 5 over_authorized_route, 12 delegated_validation). The FormRequest meaning now applies when graph.framework is "laravel" or unset (legacy and hand-built graphs keep their behaviour). Outside Laravel a route has at most two authorization layers, so over_authorized_route does not fire there. The NestJS detector test that asserted the old behaviour is updated. --- .../src/__tests__/nestjs-detectors.test.ts | 13 ++--- .../__tests__/validation-framework.test.ts | 47 +++++++++++++++++++ .../pattern-detectors/delegated-validation.ts | 5 ++ .../src/pattern-detectors/framework.ts | 12 +++++ .../over-authorized-route.ts | 4 +- 5 files changed, 72 insertions(+), 9 deletions(-) create mode 100644 packages/explainer/src/__tests__/validation-framework.test.ts create mode 100644 packages/explainer/src/pattern-detectors/framework.ts diff --git a/packages/explainer/src/__tests__/nestjs-detectors.test.ts b/packages/explainer/src/__tests__/nestjs-detectors.test.ts index cda0d02..eaa4a9e 100644 --- a/packages/explainer/src/__tests__/nestjs-detectors.test.ts +++ b/packages/explainer/src/__tests__/nestjs-detectors.test.ts @@ -198,11 +198,10 @@ describe("NestJS: detectSynchronousMail", () => { // ── over_authorized_route ───────────────────────────────────────────────────── describe("NestJS: detectOverAuthorizedRoute", () => { - it("fires when all 3 distinct layer types present (auth_gate + authz_check + validation_gate)", () => { - // Detector counts distinct LAYER TYPES, not node count: - // 1. ir:auth_gate → "auth middleware" - // 2. ir:authz_check → "policy/Gate check" - // 3. ir:validation_gate → "FormRequest::authorize" (DTO validation in NestJS) + it("does not count DTO validation as an authorization layer (auth_gate + authz_check + validation_gate)", () => { + // Only a Laravel FormRequest can authorize (FormRequest::authorize). A NestJS + // DTO / ValidationPipe checks the input, so this route has two authorization + // layers (guard + roles), below the detector's threshold of three. const graph = nestjsGraph({ method: "DELETE", path: "/admin/resources/:id", @@ -218,9 +217,7 @@ describe("NestJS: detectOverAuthorizedRoute", () => { { from: "ctrl", to: "mw_2", relation: "validates", traceability: "static" }, ], }) - const findings = detectOverAuthorizedRoute(graph) - expect(findings).toHaveLength(1) - expect(findings[0].type).toBe("over_authorized_route") + expect(detectOverAuthorizedRoute(graph)).toEqual([]) }) }) diff --git a/packages/explainer/src/__tests__/validation-framework.test.ts b/packages/explainer/src/__tests__/validation-framework.test.ts new file mode 100644 index 0000000..0e95da6 --- /dev/null +++ b/packages/explainer/src/__tests__/validation-framework.test.ts @@ -0,0 +1,47 @@ +import { describe, test, expect } from "@jest/globals" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" +import { explain } from "../index.js" +import { FINDING_TYPES } from "../findings/types.js" + +// A validation gate carries authorization only in Laravel (FormRequest::authorize). +// The same route — authenticated, role-checked, input-validated — must not be +// reported as over-authorized, or as delegating authorization from its +// validator, when the validator is a NestJS pipe, a Spring @Valid, a Gin +// binding or an Express celebrate / express-validator. + +function route(framework: string | undefined): IntermediateExecutionGraph { + return { + entrypoint: "POST /orders", + method: "POST", + path: "/orders", + annotations: [], + ...(framework ? { framework } : {}), + nodes: [ + { id: "auth", type: "ir:auth_gate", symbol: "auth:sanctum" }, + { id: "authz", type: "ir:authz_check", symbol: "OrderPolicy::create", args: ["create"] }, + { id: "valid", type: "ir:validation_gate", symbol: "StoreOrderRequest" }, + { id: "handler", type: "ir:business_handler", symbol: "OrderController::store" }, + ], + edges: [ + { from: "auth", to: "authz", relation: "ir:precedes", traceability: "static" }, + { from: "authz", to: "valid", relation: "ir:precedes", traceability: "static" }, + { from: "valid", to: "handler", relation: "ir:precedes", traceability: "static" }, + ], + } +} + +const types = (g: IntermediateExecutionGraph) => explain(g).map((f) => f.type) + +describe("validation gates as authorization layers", () => { + test.each([["laravel"], [undefined]])("framework %s: a FormRequest counts as an authorization layer", (framework) => { + const found = types(route(framework)) + expect(found).toContain(FINDING_TYPES.OVER_AUTHORIZED_ROUTE) + expect(found).toContain(FINDING_TYPES.DELEGATED_VALIDATION) + }) + + test.each([["express"], ["nestjs"], ["springboot"], ["gin"]])("framework %s: input validation is not an authorization layer", (framework) => { + const found = types(route(framework)) + expect(found).not.toContain(FINDING_TYPES.OVER_AUTHORIZED_ROUTE) + expect(found).not.toContain(FINDING_TYPES.DELEGATED_VALIDATION) + }) +}) diff --git a/packages/explainer/src/pattern-detectors/delegated-validation.ts b/packages/explainer/src/pattern-detectors/delegated-validation.ts index 7fd587d..af3d198 100644 --- a/packages/explainer/src/pattern-detectors/delegated-validation.ts +++ b/packages/explainer/src/pattern-detectors/delegated-validation.ts @@ -4,6 +4,7 @@ import type { Finding, ReasoningStep, Evidence, UncertaintyReason } from "../fin import { FINDING_TYPES } from "../findings/types.js" import { stableHash } from "../findings/stable-hash.js" import { checkMissingNodes } from "../findings/uncertainty.js" +import { validationCanAuthorize } from "./framework.js" function edgesAmong(graph: IntermediateExecutionGraph, nodeIds: string[]): string[] { const idSet = new Set(nodeIds) @@ -17,6 +18,10 @@ export function detectDelegatedValidation( authNodeIds: string[], graph: IntermediateExecutionGraph ): Finding[] { + // "delegates authorization" is about FormRequest::authorize() returning true; + // a validation gate that cannot authorize has nothing to delegate + if (!validationCanAuthorize(graph)) return [] + const gateFacts = facts.filter( (f): f is ValidationGateFact => f.kind === "validation_gate" && f.delegatesAuthorization diff --git a/packages/explainer/src/pattern-detectors/framework.ts b/packages/explainer/src/pattern-detectors/framework.ts new file mode 100644 index 0000000..1a2b11e --- /dev/null +++ b/packages/explainer/src/pattern-detectors/framework.ts @@ -0,0 +1,12 @@ +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" + +/** + * Whether a validation gate can carry authorization, as Laravel's + * FormRequest::authorize() does. Elsewhere — NestJS ValidationPipe, Spring + * @Valid, Gin binding tags, Express celebrate / express-validator — a + * validation gate only checks the input. A graph without a framework tag is a + * legacy or hand-built Laravel graph and keeps the Laravel meaning. + */ +export function validationCanAuthorize(graph: IntermediateExecutionGraph): boolean { + return !graph.framework || graph.framework === "laravel" +} diff --git a/packages/explainer/src/pattern-detectors/over-authorized-route.ts b/packages/explainer/src/pattern-detectors/over-authorized-route.ts index 4d55947..4d45f87 100644 --- a/packages/explainer/src/pattern-detectors/over-authorized-route.ts +++ b/packages/explainer/src/pattern-detectors/over-authorized-route.ts @@ -4,6 +4,7 @@ import { query } from "@kidkender/archmind-graph-query" import type { Finding } from "../findings/types.js" import { FINDING_TYPES } from "../findings/types.js" import { stableHash } from "../findings/stable-hash.js" +import { validationCanAuthorize } from "./framework.js" // 3+ separate auth enforcement points signals over-engineering or // authorization logic spread across too many layers. @@ -26,7 +27,8 @@ export function detectOverAuthorizedRoute( const authGates = q.security().authenticationGates().toArray() const authzChecks = q.security().authorizationChecks().toArray() - const validationGates = q.nodes().ofType(IR_NODE_TYPES.VALIDATION_GATE).toArray() + // a validation gate is an authorization layer only where it can authorize (FormRequest::authorize) + const validationGates = validationCanAuthorize(graph) ? q.nodes().ofType(IR_NODE_TYPES.VALIDATION_GATE).toArray() : [] // Count distinct auth layers const layers: Array<{ label: string; nodes: typeof authGates }> = [] From 16227d068e4b18cfd86537a34b0295e00d0f5ad3 Mon Sep 17 00:00:00 2001 From: kidkender Date: Thu, 12 Nov 2026 10:49:21 +0700 Subject: [PATCH 17/25] docs: changelog for the fix/minor-issues fixes --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b23f1f7..64eed4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## [Unreleased] + +### Fixed +- **`@kidkender/archmind-explainer`: input validation outside Laravel is no longer counted as an authorization layer.** `over_authorized_route` counted every `ir:validation_gate` as a third authorization layer ("FormRequest::authorize") and `delegated_validation` reported validators as delegating authorization. Both describe Laravel's `FormRequest::authorize()`; a NestJS `ValidationPipe`, Spring `@Valid`, Gin binding or Express celebrate / express-validator only checks the input, so ordinary authenticated, role-checked, validated routes on those frameworks got these findings. The FormRequest meaning now applies when the graph's framework is `laravel` or unset. Outside Laravel a route has at most two authorization layers, so `over_authorized_route` does not fire there. +- `@kidkender/archmind-nestjs-parser`: writes inside a transaction were linked to it by `within_transaction`, which is not an IR relation, so `validateGraph` reported it as unknown. They are now linked by `ir:wraps`, as in Laravel graphs. New conformance suite on a transaction fixture. +- `@kidkender/archmind-laravel-parser`: the transaction, isolation, audit-log and nested service-call passes inside a service method, and a queued job's `handle()`, swallowed any error silently. The parsers already turn unreadable files into empty results, so what reached these catches was a bug that read as "nothing found". It is now reported on stderr (`[archmind] laravel-parser: skipped for : `) and the pass is skipped as before. +- Flaky tests in `retrieval`, `nestjs-parser` and `mcp-server`: their tests load the tree-sitter parsers, whose module-level parser fails intermittently when Jest reuses one worker process across test files. Each test file now gets its own process (`maxWorkers`), as `laravel-parser` already did. Measured: `retrieval` with every file in one process failed 5 of 5 runs; with the fix it passed 10 of 10, as did `nestjs-parser`. +- `npm run trace` at the repository root pointed at `apps/cli/dist/index.js`; the CLI builds to `index.cjs`. + ## [0.9.1] - 2026-10-28 ### Added From 671c629e6ccd8b6d5c3dc888dffeb7fb181d913d Mon Sep 17 00:00:00 2001 From: kidkender Date: Thu, 12 Nov 2026 10:55:11 +0700 Subject: [PATCH 18/25] test: one Jest process per test file where tests load tree-sitter parsers retrieval, nestjs-parser and mcp-server load the tree-sitter parsers, whose module-level parser fails when Jest reuses a worker process across test files. On the GitHub runner Jest has few workers, so retrieval's regression and cross-framework suites failed every run once the build itself was fixed. maxWorkers 50 gives each file its own process, as laravel-parser already does. Same change as in fix/minor-issues, so both merge cleanly. --- packages/mcp-server/jest.config.js | 4 ++++ packages/nestjs-parser/jest.config.js | 4 ++++ packages/retrieval/jest.config.js | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/packages/mcp-server/jest.config.js b/packages/mcp-server/jest.config.js index c158c8b..cfeae98 100644 --- a/packages/mcp-server/jest.config.js +++ b/packages/mcp-server/jest.config.js @@ -2,6 +2,10 @@ export default { preset: "ts-jest/presets/default-esm", testEnvironment: "node", + // The server's caches load the Laravel and Go parsers, whose module-level + // tree-sitter Parser intermittently fails when Jest reuses one worker process + // across test files (see packages/laravel-parser/jest.config.js). + maxWorkers: 50, extensionsToTreatAsEsm: [".ts"], testPathIgnorePatterns: ["/node_modules/", "/dist/"], moduleNameMapper: { diff --git a/packages/nestjs-parser/jest.config.js b/packages/nestjs-parser/jest.config.js index 29918b5..ae35050 100644 --- a/packages/nestjs-parser/jest.config.js +++ b/packages/nestjs-parser/jest.config.js @@ -2,6 +2,10 @@ export default { preset: "ts-jest/presets/default-esm", testEnvironment: "node", + // The cross-framework tests load the Laravel and Spring Boot parsers, whose + // module-level tree-sitter Parser intermittently fails when Jest reuses one + // worker process across test files (see packages/laravel-parser/jest.config.js). + maxWorkers: 50, extensionsToTreatAsEsm: [".ts"], testPathIgnorePatterns: ["/node_modules/", "/dist/", "/fixtures/"], moduleNameMapper: { diff --git a/packages/retrieval/jest.config.js b/packages/retrieval/jest.config.js index c158c8b..04eb59f 100644 --- a/packages/retrieval/jest.config.js +++ b/packages/retrieval/jest.config.js @@ -2,6 +2,10 @@ export default { preset: "ts-jest/presets/default-esm", testEnvironment: "node", + // These tests load the Laravel / NestJS parsers, whose module-level tree-sitter + // Parser intermittently fails when Jest reuses one worker process across test + // files (see packages/laravel-parser/jest.config.js). One process per file. + maxWorkers: 50, extensionsToTreatAsEsm: [".ts"], testPathIgnorePatterns: ["/node_modules/", "/dist/"], moduleNameMapper: { From de354470216dcc202f0711dde292a8c46ccfcdfc Mon Sep 17 00:00:00 2001 From: kidkender Date: Thu, 12 Nov 2026 15:14:31 +0700 Subject: [PATCH 19/25] perf(laravel-parser): parse each file once per run and stop walking whole trees per lookup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Parsing files over 32 KiB (previous commit) exposed a cost that small files hid: every module (controller, transaction, isolation, guard clause, audit log) re-parsed the controller or service for every route, and each method lookup walked the whole tree through `.children`, which builds a JS array at every node. On invoiceninja the CLI ran for over 10 minutes and the machine ran out of memory; 19 routes of InvoiceController alone took 6.2 s and 517 MB. - php-source: parsed files are reused while their content is unchanged (up to 32 files, least recently used dropped; an edited file is parsed again). - findMethod is shared by the five modules (their identical private copies are removed) and uses descendantsOfType, with a per-tree name index. - extractUseMap is computed once per tree (callers get a copy). InvoiceController's 19 routes: 261 parses → 20, 6.2 s → 0.8 s, 517 MB → 20 MB, same 196 nodes. Full invoiceninja: completes in 36 s (139 s before the 32 KiB fix, when its large files were skipped). monica and akaunting graphs are identical before and after. --- .../src/__tests__/php-source.test.ts | 40 +++++++++++++- .../laravel-parser/src/audit-log-parser.ts | 20 +------ .../laravel-parser/src/controller-parser.ts | 30 ++++------- .../laravel-parser/src/guard-clause-parser.ts | 20 +------ .../laravel-parser/src/isolation-parser.ts | 20 +------ packages/laravel-parser/src/php-source.ts | 54 ++++++++++++++++++- .../laravel-parser/src/transaction-parser.ts | 20 +------ 7 files changed, 104 insertions(+), 100 deletions(-) diff --git a/packages/laravel-parser/src/__tests__/php-source.test.ts b/packages/laravel-parser/src/__tests__/php-source.test.ts index 29ea882..287a932 100644 --- a/packages/laravel-parser/src/__tests__/php-source.test.ts +++ b/packages/laravel-parser/src/__tests__/php-source.test.ts @@ -2,8 +2,10 @@ import { describe, test, expect, jest, beforeEach, afterEach } from "@jest/globa import { mkdtempSync, writeFileSync, rmSync } from "fs" import { tmpdir } from "os" import { join } from "path" -import type Parser from "tree-sitter" -import { parseOptionsFor, parseSource, parsePhpFile } from "../php-source.js" +import Parser from "tree-sitter" +// @ts-ignore — tree-sitter-php lacks ambient declarations in this workspace +import PHP from "tree-sitter-php" +import { parseOptionsFor, parseSource, parsePhpFile, findMethod } from "../php-source.js" import { parseTransactions } from "../transaction-parser.js" // A controller well past tree-sitter 0.21's default 32 KiB parse buffer: the @@ -77,4 +79,38 @@ describe("php-source", () => { expect(message).toContain("/app/Http/Controllers/X.php") expect(message).toContain("Invalid argument") }) + + test("a file is parsed once while its content is unchanged, and again after it changes", () => { + const real = new Parser() + real.setLanguage((PHP as { php?: unknown }).php ?? PHP) + let parses = 0 + const counting = { parse: (...args: unknown[]) => { parses++; return (real.parse as (...a: unknown[]) => Parser.Tree)(...args) } } as unknown as Parser + const file = join(dir, "Cached.php") + + writeFileSync(file, " { + const file = join(dir, "Methods.php") + writeFileSync(file, `>() + export function extractUseMap(root: Parser.SyntaxNode): Map { + const isRoot = !root.parent + const cached = isRoot ? useMaps.get(root.tree) : undefined + if (cached) return new Map(cached) const map = new Map() gatherUseDecls(root, map) - return map + if (isRoot) useMaps.set(root.tree, map) + return new Map(map) } function registerUseClause(clause: Parser.SyntaxNode, prefix: string, map: Map): void { @@ -310,26 +317,7 @@ function lastSegment(fqcn: string): string { // ---- Method finder ---------------------------------------------------- -function findMethod(root: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - for (const child of root.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} -function findMethodIn(node: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - if (node.type === "method_declaration") { - const nameNode = node.childForFieldName("name") - if (nameNode?.text === name) return node - } - - for (const child of node.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} // ---- FormRequest extraction ------------------------------------------- diff --git a/packages/laravel-parser/src/guard-clause-parser.ts b/packages/laravel-parser/src/guard-clause-parser.ts index caac970..6b1b278 100644 --- a/packages/laravel-parser/src/guard-clause-parser.ts +++ b/packages/laravel-parser/src/guard-clause-parser.ts @@ -1,7 +1,7 @@ import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" -import { parsePhpFile } from "./php-source.js" +import { parsePhpFile, findMethod } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -127,22 +127,4 @@ function isGuardIfStatement(stmt: Parser.SyntaxNode): boolean { // ---- Method finder ------------------------------------------------------ -function findMethod(root: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - for (const child of root.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} -function findMethodIn(node: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - if (node.type === "method_declaration") { - const nameNode = node.childForFieldName("name") - if (nameNode?.text === name) return node - } - for (const child of node.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} diff --git a/packages/laravel-parser/src/isolation-parser.ts b/packages/laravel-parser/src/isolation-parser.ts index e4958da..beabe4d 100644 --- a/packages/laravel-parser/src/isolation-parser.ts +++ b/packages/laravel-parser/src/isolation-parser.ts @@ -1,7 +1,7 @@ import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" -import { parsePhpFile } from "./php-source.js" +import { parsePhpFile, findMethod } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -83,25 +83,7 @@ export function parseIsolation(filePath: string, opts: IsolationOptions = {}, me // ---- Method finder ------------------------------------------------------ -function findMethod(root: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - for (const child of root.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} -function findMethodIn(node: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - if (node.type === "method_declaration") { - const nameNode = node.childForFieldName("name") - if (nameNode?.text === name) return node - } - for (const child of node.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} // ---- Container read detection ----------------------------------------- diff --git a/packages/laravel-parser/src/php-source.ts b/packages/laravel-parser/src/php-source.ts index 1e4351a..a9d5a88 100644 --- a/packages/laravel-parser/src/php-source.ts +++ b/packages/laravel-parser/src/php-source.ts @@ -35,11 +35,63 @@ export function readSource(filePath: string): string | null { } } +/** + * Parsed files, most recently used last. A route is analysed by several modules + * (controller, transaction, isolation, guard clauses, audit log), each of which + * used to re-parse the same controller or service for every route — hundreds of + * parses of one large file per project. An entry is reused only while the file's + * content is unchanged, so an edited file is parsed again. Trees are only read, + * never edited, so sharing one between modules is safe. + */ +const parsed = new Map() +/** Files kept parsed at once; enough for a route's controller and the services it reaches. */ +const PARSE_CACHE_SIZE = 32 + /** Reads and parses a PHP file; null when it cannot be read or parsed (see parseSource). */ export function parsePhpFile(parser: Parser, filePath: string): { source: string; tree: Parser.Tree } | null { const source = readSource(filePath) if (source === null) return null + const hit = parsed.get(filePath) + if (hit && hit.source === source) { + parsed.delete(filePath) + parsed.set(filePath, hit) + return hit + } const tree = parseSource(parser, source, filePath) if (!tree) return null - return { source, tree } + const entry = { source, tree } + parsed.delete(filePath) + parsed.set(filePath, entry) + if (parsed.size > PARSE_CACHE_SIZE) parsed.delete(parsed.keys().next().value as string) + return entry } + +/** + * The first method named `name` in document order (as the old recursive walks + * found it). `descendantsOfType` walks the tree natively and only wraps the + * matches; walking `.children` recursively built a JS array at every node of + * every method body, which made each lookup on a large file cost a full-tree + * allocation. + */ +export function findMethod(root: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { + // from a tree's root, look the method up in that tree's index (built once per tree) + if (!root.parent) { + let index = methodIndex.get(root.tree) + if (!index) { + index = new Map() + for (const method of root.descendantsOfType("method_declaration")) { + const methodName = method.childForFieldName("name")?.text + if (methodName && !index.has(methodName)) index.set(methodName, method) // first in document order + } + methodIndex.set(root.tree, index) + } + return index.get(name) ?? null + } + for (const method of root.descendantsOfType("method_declaration")) { + if (method.childForFieldName("name")?.text === name) return method + } + return null +} + +/** Method name → first method_declaration with that name, per tree. */ +const methodIndex = new WeakMap>() diff --git a/packages/laravel-parser/src/transaction-parser.ts b/packages/laravel-parser/src/transaction-parser.ts index 60c7f15..e743ac8 100644 --- a/packages/laravel-parser/src/transaction-parser.ts +++ b/packages/laravel-parser/src/transaction-parser.ts @@ -1,7 +1,7 @@ import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" -import { parsePhpFile } from "./php-source.js" +import { parsePhpFile, findMethod } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -84,25 +84,7 @@ export function parseTransactions(filePath: string, methodName?: string): Transa // ---- Method finder ------------------------------------------------------ -function findMethod(root: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - for (const child of root.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} -function findMethodIn(node: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - if (node.type === "method_declaration") { - const nameNode = node.childForFieldName("name") - if (nameNode?.text === name) return node - } - for (const child of node.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} // ---- Tree traversal --------------------------------------------------- From 1af2ba9881c3357f1137f531bff1b473fcebf39e Mon Sep 17 00:00:00 2001 From: kidkender Date: Thu, 12 Nov 2026 16:03:18 +0700 Subject: [PATCH 20/25] fix(cli): detect a Gin project whose go.mod is one directory down MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CLI only treated a project as Go when go.mod sat at the root, then asked isGinProject; analysis and the MCP server already rely on isGinProject alone, which also finds a go.mod one directory down (api/, server/) and returns false for a root that has composer.json. Such a project fell through to the Laravel default and showed no routes. On zgiai/zgi (go.mod in api/): Laravel, 0 routes → Go, 226 routes. ginfast (go.mod at the root) unchanged; isGinProject is false for the Laravel, Spring Boot, NestJS and Express projects checked. --- apps/cli/src/utils/parse-project.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/cli/src/utils/parse-project.ts b/apps/cli/src/utils/parse-project.ts index 2392940..1fc1761 100644 --- a/apps/cli/src/utils/parse-project.ts +++ b/apps/cli/src/utils/parse-project.ts @@ -96,8 +96,9 @@ export function detectFramework(projectRoot: string): Framework { // go.mod is a strong, cheap-to-check signal unique to Go — checked before // the fallback heuristics below so a Gin project never falls through to - // the Laravel default. - if (existsSync(join(projectRoot, "go.mod")) && isGinProject(projectRoot)) return "go" + // the Laravel default. isGinProject also finds a go.mod one directory down + // (api/, server/), as analysis and the MCP server do. + if (isGinProject(projectRoot)) return "go" // Fallback heuristics if (existsSync(join(projectRoot, "artisan"))) return "laravel" From ff7a102eb2f08f676c47a55fb4a576957da76edc Mon Sep 17 00:00:00 2001 From: kidkender Date: Thu, 12 Nov 2026 16:42:49 +0700 Subject: [PATCH 21/25] fix(laravel-parser): compare tree-sitter nodes by position, not identity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit gatherServiceCalls folds a mutating call into the relationship accessor it is chained on ($user->apiTokens()->delete() → one "User::apiTokens()->delete") and skips the accessor when recursing with `child !== objNode`. tree-sitter 0.21 does not always return the same JS object for the same node — it depends on its node cache and on garbage collection — so in some runs the accessor was visited again and emitted as a duplicate service call. That made output vary between identical runs (koel: 1943 / 1946 / 1943 nodes; one koel method gave two different results in 6 of 50 calls) and, with the parse cache of the previous commit, made BookStack consistently wrong (3922 instead of 3917). Nodes are now compared by start/end index and type. Same build, three runs: koel 1933 and BookStack 3917 every time. New test repeats the koel pattern 60 times; it fails on the old comparison. --- .../__tests__/service-call-folding.test.ts | 63 +++++++++++++++++++ .../laravel-parser/src/controller-parser.ts | 10 ++- 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 packages/laravel-parser/src/__tests__/service-call-folding.test.ts diff --git a/packages/laravel-parser/src/__tests__/service-call-folding.test.ts b/packages/laravel-parser/src/__tests__/service-call-folding.test.ts new file mode 100644 index 0000000..1586add --- /dev/null +++ b/packages/laravel-parser/src/__tests__/service-call-folding.test.ts @@ -0,0 +1,63 @@ +import { describe, test, expect, beforeAll, afterAll } from "@jest/globals" +import { mkdtempSync, writeFileSync, rmSync } from "fs" +import { tmpdir } from "os" +import { join } from "path" +import { parseControllerMethod } from "../controller-parser.js" + +// A mutating call chained onto a relationship accessor ($folder->playlists()->detach()) +// is folded into one service call; the accessor alone must not be emitted again. +// The skip used to compare tree-sitter nodes with `!==`, and tree-sitter does not +// always hand back the same JS object for the same node, so some runs emitted a +// duplicate "PlaylistFolder::playlists" (seen on koel: 6 of 50 runs). + +const SERVICE = `each(static function (string $playlistId) use ($folder): void { + PlaylistFolder::query() + ->whereHas('playlists', static fn ($q) => $q->whereKey($playlistId)) + ->get() + ->each(static fn (PlaylistFolder $folder) => $folder->playlists()->detach($playlistId)); + }); + $folder->playlists()->attach($playlistIds); + }); + } +} +` + +describe("parseControllerMethod — folded relationship mutations", () => { + let dir: string + let file: string + + beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), "archmind-folding-")) + file = join(dir, "PlaylistFolderService.php") + writeFileSync(file, SERVICE) + }) + + afterAll(() => rmSync(dir, { recursive: true, force: true })) + + test("the accessor is folded into its mutation and not emitted on its own", () => { + const calls = parseControllerMethod(file, "addPlaylistsToFolder")!.serviceCalls.map((s) => `${s.serviceClass}::${s.method}`) + expect(calls).toContain("PlaylistFolder::playlists()->attach") + expect(calls).toContain("PlaylistFolder::playlists()->detach") + expect(calls).not.toContain("PlaylistFolder::playlists") + }) + + test("repeated runs give the same result", () => { + const seen = new Set() + for (let i = 0; i < 60; i++) { + const calls = parseControllerMethod(file, "addPlaylistsToFolder")!.serviceCalls.map((s) => `${s.serviceClass}::${s.method}`) + seen.add(JSON.stringify(calls)) + } + expect(seen.size).toBe(1) + }) +}) diff --git a/packages/laravel-parser/src/controller-parser.ts b/packages/laravel-parser/src/controller-parser.ts index 6291779..625d234 100644 --- a/packages/laravel-parser/src/controller-parser.ts +++ b/packages/laravel-parser/src/controller-parser.ts @@ -869,6 +869,11 @@ function tryExtractBaseServiceCall( return null } +/** Whether two tree-sitter nodes are the same node of the same tree (wrapper objects may differ). */ +function sameNode(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean { + return a.startIndex === b.startIndex && a.endIndex === b.endIndex && a.type === b.type +} + function gatherServiceCalls( node: Parser.SyntaxNode, injections: Map, @@ -893,8 +898,11 @@ function gatherServiceCalls( }) // objNode is fully consumed by the combined node above — recurse // into the rest of the chain but skip re-visiting it standalone. + // Compared by position, not `!==`: tree-sitter does not guarantee + // one JS object per node (it depends on its node cache and on GC), + // so identity made the base accessor show up again in some runs. for (const child of node.children as Parser.SyntaxNode[]) { - if (child !== objNode) gatherServiceCalls(child, injections, results, requestParamVars) + if (!sameNode(child, objNode)) gatherServiceCalls(child, injections, results, requestParamVars) } return } From c7bb79ba5523aa55346038d8255cc14d08afcec2 Mon Sep 17 00:00:00 2001 From: kidkender Date: Fri, 13 Nov 2026 09:14:47 +0700 Subject: [PATCH 22/25] feat(go-parser): follow tenant isolation through registries, DAOs and model wrappers Real multi-tenant Gin apps rarely query GORM straight from a struct field, so the first version found no queries on them. Isolation now: - resolves handlers and callees through package-level registries, embedded structs, typed locals and constructor return types (api.Controllers.BoardApi.X, service.GroupApp.Board.X, NewSysRoleList()); - reads the tenant from tenant-named fields (claims.TenantID) and tenant-named functions handed the Gin context (TenantScope(c)); - treats read/write calls on DAO, repository and model wrappers as queries, judged at the call site when the wrapper takes its conditions as variadic arguments, and judges Scopes(funcs...) by the caller's arguments; - counts operations covered by a tenant-setting GORM callback as scoped; - skips models declared without a tenant field (shared tables), ignores Preload("Tenant"), and follows conditions built in variables (subqueries). Measured on two real apps: thingspanel goes from 1 to 129 routes with a tenant context and 15 distinct unscoped sites; ginfast from 0 to 40, with 8 distinct unscoped sites. --- packages/go-parser/README.md | 7 +- .../src/__tests__/isolation-wrappers.test.ts | 438 ++++++++++++++++++ packages/go-parser/src/code-index.ts | 247 ++++++++++ packages/go-parser/src/graph-builder.ts | 123 ++++- packages/go-parser/src/isolation-parser.ts | 236 ++++++++-- 5 files changed, 997 insertions(+), 54 deletions(-) create mode 100644 packages/go-parser/src/__tests__/isolation-wrappers.test.ts create mode 100644 packages/go-parser/src/code-index.ts diff --git a/packages/go-parser/README.md b/packages/go-parser/README.md index 477b2fc..00a42c4 100644 --- a/packages/go-parser/README.md +++ b/packages/go-parser/README.md @@ -36,7 +36,10 @@ Most of ArchMind uses it through `@kidkender/archmind-analysis`, the CLI (`archm - **Authorization checks**: role/policy middleware, and **ownership** checks. A handler that calls one of the functions named in `archmind.json` → `authorization.ownershipSources` (for example `["currentCharacter"]`) is treated as authorizing by ownership. - **Validation gates**: `ShouldBindJSON`, `ShouldBindQuery` and `ShouldBindUri` resolved to the DTO struct and its `binding` tags. - **Transaction boundaries**: GORM `.Transaction(func...)` closures, followed one hop into a directly called service method. -- **Tenant isolation**: on a route that resolves a tenant (a middleware whose name carries a tenant key, a `c.Get("tenant_id")`-style read from the Gin context, or an accessor such as `GetTenantID(c)` / `tenant.FromContext(ctx)`), an `ir:tenant_context` node, and every GORM query in the handler and up to two calls below it (handler → service → repository) as `ir:scoped_query` or `ir:unscoped_query` / `ir:unscoped_write`. An unscoped query gets a `missing_tenant_scope` edge, which the explainer reports as a `missing_tenant_scope` finding. Routes that resolve no tenant get none of these nodes. +- **Tenant isolation**: on a route that resolves a tenant (a middleware whose name carries a tenant key, a `c.Get("tenant_id")`-style read from the Gin context, an accessor such as `GetTenantID(c)` / `tenant.FromContext(ctx)`, a tenant-named function handed the context such as `TenantScope(c)`, or a tenant field read such as `claims.TenantID`), an `ir:tenant_context` node, and every query in the handler and up to two calls below it (handler → service → repository) as `ir:scoped_query` or `ir:unscoped_query` / `ir:unscoped_write`. An unscoped query gets a `missing_tenant_scope` edge, which the explainer reports as a `missing_tenant_scope` finding. Routes that resolve no tenant get none of these nodes. + - Calls are followed through struct fields, typed locals (`db := dal.BoardQuery{}`, `list := models.NewSysRoleList()`), package-level registries and embedded structs (`service.GroupApp.Board.X`); route handlers registered that way (`api.Controllers.BoardApi.X`) are resolved too. + - Besides GORM chains, a read/write-named call on a DAO, repository or model wrapper (a type declared under `dal/`, `dao/`, `repo*/`, `store/`, `query/`, `model*/`, ... or named `*Query` / `*Repo` / `*Dao` / ...) counts as a query. When the wrapper takes its conditions as variadic arguments (`First(ctx, conds ...gen.Condition)`, `Find(c, scopes ...func(*gorm.DB) *gorm.DB)`), it is judged at the call site by those arguments; otherwise it is followed. A `Scopes(funcs...)` fed by a parameter is judged by the arguments of the call that reached it. + - A create, update, delete or query whose GORM callback (`db.Callback().Create()...Register(name, fn)`) mentions the tenant counts as scoped. A query on a model declared in the project without a tenant field (directly or in an embedded struct) is shared data and is not reported. `Preload("Tenant")` does not scope a query. - A handler wired up as a local variable (`h := handler.NewXxx(...)`) is resolved to its type. Nodes carry the `file` and `line` where the parser found them. @@ -62,7 +65,7 @@ The tree-sitter helpers other packages build on: `parseGo`, `walk`, `receiverTyp ## Limits - Scoped to the Gin + GORM + `internal/{handler,service,middleware,model,dto}` layout it was built against, and checked on other public Gin repositories. Some architectures still return no routes (an engine held in a struct field and mutated by a method, a custom wrapper type with its own `.GET()`, deeply functional-options setups, Wire-style injection). -- Tenant isolation is syntactic: a GORM global scope, a callback (`db.Callback()`), a plugin, or a `Scopes(fn)` whose name carries no tenant signal is not seen, so a query constrained that way reads as unscoped. Queries more than two calls below the handler, or behind an interface whose implementation is not named `T`, `t`, `TImpl` or `tImpl`, are not found. At most 25 query nodes per route. +- Tenant isolation is syntactic: a GORM plugin, a global scope applied outside a registered callback, or a `Scopes(fn)` whose name and arguments carry no tenant signal is not seen, so a query constrained that way reads as unscoped. Queries that are global by design (login, uniqueness checks, super-admin setup) are reported too. Types are matched by bare name across packages. Queries more than two calls below the handler, or behind an interface whose implementation is not named `T`, `t`, `TImpl` or `tImpl`, are not found. At most 25 query nodes per route. ## License diff --git a/packages/go-parser/src/__tests__/isolation-wrappers.test.ts b/packages/go-parser/src/__tests__/isolation-wrappers.test.ts new file mode 100644 index 0000000..2aa0d1f --- /dev/null +++ b/packages/go-parser/src/__tests__/isolation-wrappers.test.ts @@ -0,0 +1,438 @@ +import { describe, test, expect } from "@jest/globals" +import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" +import { parseGinProject } from "../graph-builder.js" +import type { GoSourceFile } from "../route-parser.js" + +// Layouts seen in real multi-tenant Gin apps, where the request reaches the +// query through package-level registries, typed locals and DAO / model wrappers +// rather than struct fields: +// - "registry": handlers and services hung off package vars of structs that +// embed them (api.Controllers.BoardApi.X, service.GroupApp.Board.X), the +// tenant read off JWT claims, gorm-gen DAOs taking conditions as arguments. +// - "model wrappers": controllers built by constructors, models as named +// slices with Find(c, scopes...) and the tenant scope passed in by the caller. + +function graphFor(graphs: IntermediateExecutionGraph[], route: string): IntermediateExecutionGraph { + const [method, path] = route.split(" ") + const g = graphs.find((x) => x.method === method && x.path === path) + if (!g) throw new Error(`no graph for ${route}; have ${graphs.map((x) => `${x.method} ${x.path}`).join(", ")}`) + return g +} + +function typesOf(g: IntermediateExecutionGraph): string[] { + return g.nodes.map((n) => n.type) +} + +// --- registry layout -------------------------------------------------------- + +const REGISTRY_APP: GoSourceFile[] = [ + { + path: "cmd/main.go", + content: ` +package main + +func main() { + r := gin.Default() + api := r.Group("/api") + apps.InitBoard(api) +} +`, + }, + { + path: "router/apps/board.go", + content: ` +package apps + +func InitBoard(Router *gin.RouterGroup) { + url := Router.Group("/board") + url.POST("", api.Controllers.BoardApi.CreateBoard) + url.POST("/raw", api.Controllers.BoardApi.CreateBoardRaw) + url.GET("/:id", api.Controllers.BoardApi.GetBoard) + url.GET("/:id/raw", api.Controllers.BoardApi.GetBoardRaw) +} +`, + }, + { + path: "internal/api/enter.go", + content: ` +package api + +type Controller struct { + BoardApi // boards +} + +var ( + Controllers = new(Controller) +) +`, + }, + { + path: "internal/api/board.go", + content: ` +package api + +type BoardApi struct{} + +func (*BoardApi) CreateBoard(c *gin.Context) { + var req model.CreateBoardReq + userClaims := c.MustGet("claims").(*utils.UserClaims) + req.TenantID = userClaims.TenantID + service.GroupApp.Board.CreateBoard(c, &req) +} + +func (*BoardApi) CreateBoardRaw(c *gin.Context) { + var req model.CreateBoardReq + userClaims := c.MustGet("claims").(*utils.UserClaims) + log.Println(userClaims.TenantID) + service.GroupApp.Board.CreateBoardRaw(c, &req) +} + +func (*BoardApi) GetBoard(c *gin.Context) { + userClaims := c.MustGet("claims").(*utils.UserClaims) + service.GroupApp.Board.GetBoard(c, c.Param("id"), userClaims.TenantID) +} + +func (*BoardApi) GetBoardRaw(c *gin.Context) { + userClaims := c.MustGet("claims").(*utils.UserClaims) + log.Println(userClaims.TenantID) + service.GroupApp.Board.GetBoardRaw(c, c.Param("id")) +} +`, + }, + { + path: "internal/service/enter.go", + content: ` +package service + +type ServiceGroup struct { + Board +} + +var GroupApp = new(ServiceGroup) +`, + }, + { + path: "internal/service/board.go", + content: ` +package service + +type Board struct{} + +func (*Board) CreateBoard(ctx context.Context, req *model.CreateBoardReq) error { + db := dal.BoardQuery{} + var board model.Board + board.TenantID = req.TenantID + board.Name = req.Name + return db.Create(ctx, &board) +} + +func (*Board) CreateBoardRaw(ctx context.Context, req *model.CreateBoardReq) error { + db := dal.BoardQuery{} + var board model.Board + board.Name = req.Name + return db.Create(ctx, &board) +} + +func (*Board) GetBoard(ctx context.Context, id string, tenantID string) (*model.Board, error) { + db := dal.BoardQuery{} + return db.First(ctx, query.Board.ID.Eq(id), query.Board.TenantID.Eq(tenantID)) +} + +func (*Board) GetBoardRaw(ctx context.Context, id string) (*model.Board, error) { + db := dal.BoardQuery{} + return db.First(ctx, query.Board.ID.Eq(id)) +} +`, + }, + { + path: "internal/dal/board.go", + content: ` +package dal + +type BoardQuery struct{} + +func (BoardQuery) First(ctx context.Context, option ...gen.Condition) (*model.Board, error) { + return query.Board.WithContext(ctx).Where(option...).First() +} + +func (BoardQuery) Create(ctx context.Context, b *model.Board) error { + return query.Board.WithContext(ctx).Create(b) +} +`, + }, + { + path: "internal/model/board.go", + content: ` +package model + +type Board struct { + ID string + TenantID string + Name string +} +`, + }, +] + +const TENANT_HOOK: GoSourceFile = { + path: "initialize/gorm.go", + content: ` +package initialize + +func RegisterHooks(db *gorm.DB) { + db.Callback().Create().Before("gorm:create").Register("tenant:create", SetTenantOnCreate) +} + +func SetTenantOnCreate(db *gorm.DB) { + db.Statement.SetColumn("TenantID", tenantFrom(db.Statement.Context)) +} +`, +} + +describe("parseGinProject — tenant isolation through registries and DAOs", () => { + test("a handler reached through a package var of embedded structs is read; a tenant field off JWT claims marks the tenant", () => { + const g = graphFor(parseGinProject(REGISTRY_APP), "GET /api/board/:id") + const ctx = g.nodes.find((n) => n.type === IR_NODE_TYPES.TENANT_CONTEXT) + expect(ctx?.symbol).toContain("userClaims.TenantID") + expect(ctx?.file).toBe("internal/api/board.go") + }) + + test("a DAO call given a tenant condition is ir:scoped_query", () => { + const g = graphFor(parseGinProject(REGISTRY_APP), "GET /api/board/:id") + const scoped = g.nodes.filter((n) => n.type === IR_NODE_TYPES.SCOPED_QUERY) + expect(scoped.map((n) => n.symbol)).toEqual(["BoardQuery::First"]) + expect(scoped[0]!.file).toBe("internal/service/board.go") + expect(typesOf(g)).not.toContain(IR_NODE_TYPES.UNSCOPED_QUERY) + }) + + test("a DAO call by id alone is ir:unscoped_query, judged at the call site", () => { + const g = graphFor(parseGinProject(REGISTRY_APP), "GET /api/board/:id/raw") + const unscoped = g.nodes.filter((n) => n.type === IR_NODE_TYPES.UNSCOPED_QUERY) + expect(unscoped.map((n) => n.symbol)).toEqual(["BoardQuery::First"]) + expect(unscoped[0]!.file).toBe("internal/service/board.go") // not the generic DAO body + const ctx = g.nodes.find((n) => n.type === IR_NODE_TYPES.TENANT_CONTEXT)! + expect(g.edges).toContainEqual(expect.objectContaining({ + from: unscoped[0]!.id, to: ctx.id, relation: "missing_tenant_scope", + })) + }) + + test("a DAO create of a record tied to the tenant gets no node", () => { + const g = graphFor(parseGinProject(REGISTRY_APP), "POST /api/board") + expect(typesOf(g)).toContain(IR_NODE_TYPES.TENANT_CONTEXT) + expect(typesOf(g)).not.toContain(IR_NODE_TYPES.UNSCOPED_WRITE) + }) + + test("a create without the tenant is ir:unscoped_write, unless a GORM create hook sets it", () => { + const without = graphFor(parseGinProject(REGISTRY_APP), "POST /api/board/raw") + const write = without.nodes.find((n) => n.type === IR_NODE_TYPES.UNSCOPED_WRITE) + expect(write?.symbol).toBe("Board::Create") + + const withHook = graphFor(parseGinProject([...REGISTRY_APP, TENANT_HOOK]), "POST /api/board/raw") + expect(typesOf(withHook)).not.toContain(IR_NODE_TYPES.UNSCOPED_WRITE) + }) +}) + +// --- model-wrapper layout --------------------------------------------------- + +const MODEL_APP: GoSourceFile[] = [ + { + path: "main.go", + content: ` +package main + +func main() { + r := gin.Default() + routes.InitRoutes(r) +} +`, + }, + { + path: "app/routes/routes.go", + content: ` +package routes + +func InitRoutes(r *gin.Engine) { + roles := controllers.NewSysRoleController() + menus := controllers.NewSysMenuController() + api := r.Group("/api") + api.GET("/roles", roles.List) + api.GET("/roles/all", roles.All) + api.GET("/roles/total", roles.Total) + api.GET("/roles/total-all", roles.TotalAll) + api.GET("/roles/:id", roles.Get) + api.GET("/menus", menus.List) +} +`, + }, + { + path: "app/controllers/sysrole.go", + content: ` +package controllers + +type SysRoleController struct{} + +func NewSysRoleController() *SysRoleController { + return &SysRoleController{} +} + +func (rc *SysRoleController) List(c *gin.Context) { + list := models.NewSysRoleList() + list.Find(c, tenanthelper.TenantScope(c)) +} + +func (rc *SysRoleController) All(c *gin.Context) { + _ = tenanthelper.GetTenantID(c) + list := models.NewSysRoleList() + list.Find(c, func(db *gorm.DB) *gorm.DB { return db }) +} + +func (rc *SysRoleController) Total(c *gin.Context) { + list := models.NewSysRoleList() + list.Total(c, tenanthelper.TenantScope(c)) +} + +func (rc *SysRoleController) TotalAll(c *gin.Context) { + _ = tenanthelper.GetTenantID(c) + list := models.NewSysRoleList() + list.Total(c) +} + +func (rc *SysRoleController) Get(c *gin.Context) { + _ = tenanthelper.GetTenantID(c) + role := models.NewSysRole() + role.FindByID(c, c.Param("id")) +} +`, + }, + { + path: "app/controllers/sysmenu.go", + content: ` +package controllers + +type SysMenuController struct{} + +func NewSysMenuController() *SysMenuController { + return &SysMenuController{} +} + +func (mc *SysMenuController) List(c *gin.Context) { + _ = tenanthelper.GetTenantID(c) + list := models.NewSysMenuList() + list.Find(c) +} +`, + }, + { + path: "app/models/sysrole.go", + content: ` +package models + +type SysRole struct { + BaseModel + Name string +} + +type SysRoleList []SysRole + +func NewSysRoleList() SysRoleList { + return SysRoleList{} +} + +func NewSysRole() *SysRole { + return &SysRole{} +} + +func (l *SysRoleList) Find(c context.Context, funcs ...func(*gorm.DB) *gorm.DB) error { + return app.DB().WithContext(c).Scopes(funcs...).Find(l).Error +} + +func (l *SysRoleList) Total(c context.Context, funcs ...func(*gorm.DB) *gorm.DB) (total int64, err error) { + err = app.DB().WithContext(c).Model(&SysRole{}).Scopes(funcs...).Count(&total).Error + return +} + +func (r *SysRole) FindByID(c context.Context, id string) error { + return app.DB().WithContext(c).Preload("Tenant").Where("id = ?", id).First(r).Error +} +`, + }, + { + path: "app/models/base.go", + content: ` +package models + +type BaseModel struct { + ID uint + TenantID uint +} +`, + }, + { + path: "app/models/sysmenu.go", + content: ` +package models + +type SysMenu struct { + ID uint + Title string +} + +type SysMenuList []SysMenu + +func NewSysMenuList() SysMenuList { + return SysMenuList{} +} + +func (l *SysMenuList) Find(c context.Context, funcs ...func(*gorm.DB) *gorm.DB) error { + return app.DB().WithContext(c).Scopes(funcs...).Find(l).Error +} +`, + }, +] + +describe("parseGinProject — tenant isolation through model wrappers", () => { + test("a handler on a controller built by a constructor is read; a tenant-named function of the context marks the tenant", () => { + const g = graphFor(parseGinProject(MODEL_APP), "GET /api/roles") + const ctx = g.nodes.find((n) => n.type === IR_NODE_TYPES.TENANT_CONTEXT) + expect(ctx?.symbol).toContain("TenantScope(c)") + expect(ctx?.file).toBe("app/controllers/sysrole.go") + }) + + test("a wrapper call given the tenant scope is scoped; one without it is not", () => { + const graphs = parseGinProject(MODEL_APP) + + const scoped = graphFor(graphs, "GET /api/roles") + expect(scoped.nodes.filter((n) => n.type === IR_NODE_TYPES.SCOPED_QUERY).map((n) => n.symbol)) + .toEqual(["SysRoleList::Find"]) + expect(typesOf(scoped)).not.toContain(IR_NODE_TYPES.UNSCOPED_QUERY) + + const all = graphFor(graphs, "GET /api/roles/all") + expect(all.nodes.filter((n) => n.type === IR_NODE_TYPES.UNSCOPED_QUERY).map((n) => n.symbol)) + .toEqual(["SysRoleList::Find"]) + }) + + test("Scopes(funcs...) inside a followed method is judged by the caller's arguments", () => { + const graphs = parseGinProject(MODEL_APP) + + const total = graphFor(graphs, "GET /api/roles/total") + expect(total.nodes.filter((n) => n.type === IR_NODE_TYPES.SCOPED_QUERY).map((n) => n.symbol)) + .toEqual(["SysRole::Count"]) + + const totalAll = graphFor(graphs, "GET /api/roles/total-all") + expect(totalAll.nodes.filter((n) => n.type === IR_NODE_TYPES.UNSCOPED_QUERY).map((n) => n.symbol)) + .toEqual(["SysRole::Count"]) + }) + + test("Preload(\"Tenant\") loads a relation and does not scope the query", () => { + const g = graphFor(parseGinProject(MODEL_APP), "GET /api/roles/:id") + expect(g.nodes.filter((n) => n.type === IR_NODE_TYPES.UNSCOPED_QUERY).map((n) => n.symbol)) + .toEqual(["SysRole::First"]) + }) + + test("a query on a shared table (a model without a tenant field) is not reported", () => { + const g = graphFor(parseGinProject(MODEL_APP), "GET /api/menus") + expect(typesOf(g)).toContain(IR_NODE_TYPES.TENANT_CONTEXT) + expect(typesOf(g)).not.toContain(IR_NODE_TYPES.UNSCOPED_QUERY) + }) +}) diff --git a/packages/go-parser/src/code-index.ts b/packages/go-parser/src/code-index.ts new file mode 100644 index 0000000..155a34f --- /dev/null +++ b/packages/go-parser/src/code-index.ts @@ -0,0 +1,247 @@ +import { walk, bareTypeName, callParts, functionParamTypes, receiverTypeName, type SyntaxNode } from "./ast.js" +import type { HandlerMethod } from "./handler-parser.js" + +/** + * Project-wide facts tenant isolation needs to follow a request past the + * handler: the type of a package-level variable (`var GroupApp = new(ServiceGroup)`), + * the type a constructor returns (`func NewSysRoleList() SysRoleList`), which + * file declares a struct (to tell a DAO or model from a service), and the GORM + * callbacks a project registers (`db.Callback().Create().Before(...).Register(name, fn)`). + */ +export interface CodeIndex { + /** Package-level variable → bare type name. */ + packageVars: Map + /** Function name → bare type of its (first) result. */ + returnTypes: Map + /** Struct / named type → path of the file that declares it. */ + typeFiles: Map + /** Function declarations by name, for callbacks registered by name. */ + functions: Map + /** GORM callbacks by operation ("create" | "update" | "delete" | "query") → registered function names. */ + callbacks: Map + /** A named slice or pointer type → its element type: `type SysRoleList []SysRole` → SysRole. */ + elementTypes: Map + /** A struct → the types it embeds: `type User struct { BaseModel; ... }` → [BaseModel]. */ + embeddedTypes: Map + /** + * A struct name → the named fields of every struct declared with that name + * (packages reuse names: service.Board and model.Board). + */ + structFields: Map +} + +export function buildCodeIndex(files: { path: string; root: SyntaxNode }[]): CodeIndex { + const index: CodeIndex = { + packageVars: new Map(), returnTypes: new Map(), typeFiles: new Map(), functions: new Map(), callbacks: new Map(), + elementTypes: new Map(), embeddedTypes: new Map(), structFields: new Map(), + } + for (const file of files) { + for (const top of file.root.namedChildren) { + if (top.type === "var_declaration") { + for (const spec of top.descendantsOfType("var_spec")) { + const type = varSpecType(spec, index) + if (!type) continue + for (const name of spec.childrenForFieldName("name")) { + if (name.type === "identifier" && !index.packageVars.has(name.text)) index.packageVars.set(name.text, type) + } + } + } else if (top.type === "type_declaration") { + for (const spec of top.descendantsOfType("type_spec")) { + const name = spec.childForFieldName("name")?.text + if (name && !index.typeFiles.has(name)) index.typeFiles.set(name, file.path) + const typeNode = spec.childForFieldName("type") + if (name && typeNode?.type === "slice_type") { + const element = typeNode.childForFieldName("element") + const bare = element ? bareTypeName(element) : null + if (bare) index.elementTypes.set(name, bare) + } + if (name && typeNode?.type === "struct_type") { + const embedded: string[] = [] + const named: string[] = [] + // only this struct's own fields (not those of a nested anonymous struct) + const list = typeNode.namedChildren.find((c) => c.type === "field_declaration_list") + for (const field of list?.namedChildren ?? []) { + if (field.type !== "field_declaration") continue + const names = field.childrenForFieldName("name") + if (names.length > 0) { named.push(...names.map((n) => n.text)); continue } + const t = field.childForFieldName("type") + const bare = t ? bareTypeName(t) : null + if (bare) embedded.push(bare) + } + if (embedded.length) index.embeddedTypes.set(name, [...(index.embeddedTypes.get(name) ?? []), ...embedded]) + index.structFields.set(name, [...(index.structFields.get(name) ?? []), ...named]) + } + } + } else if (top.type === "function_declaration") { + const name = top.childForFieldName("name")?.text + if (!name) continue + if (!index.functions.has(name)) index.functions.set(name, top) + const result = top.childForFieldName("result") + const type = result ? resultType(result) : null + if (type && !index.returnTypes.has(name)) index.returnTypes.set(name, type) + } + } + // db.Callback().Create().Before("gorm:create").Register("name", CreateHook) + for (const node of walk(file.root)) { + const parts = callParts(node) + if (!parts || parts.method !== "Register" || !parts.receiver?.includes("Callback()")) continue + const op = /Callback\(\)\.(Create|Update|Delete|Query)\(\)/.exec(parts.receiver)?.[1]?.toLowerCase() + const fn = parts.args[1]?.text.split(".").pop() + if (op && fn) index.callbacks.set(op, [...(index.callbacks.get(op) ?? []), fn]) + } + } + return index +} + +/** The type a `var x T` / `var x = new(T)` / `var x = &T{}` / `var x = NewT()` declares. */ +function varSpecType(spec: SyntaxNode, index: CodeIndex): string | null { + const typeNode = spec.childForFieldName("type") + if (typeNode) return bareTypeName(typeNode) + const value = spec.childForFieldName("value")?.namedChildren[0] + return value ? typeOfValueText(value.text, index) : null +} + +function resultType(result: SyntaxNode): string | null { + if (result.type === "parameter_list") { + const first = result.namedChildren.find((c) => c.type === "parameter_declaration") + const t = first?.childForFieldName("type") + return t ? bareTypeName(t) : null + } + return bareTypeName(result) +} + +/** `&dal.BoardQuery{}` / `models.SysRole{}` / `new(Board)` / `models.NewSysRoleList()` → the bare type. */ +export function typeOfValueText(text: string, index: CodeIndex): string | null { + const t = text.trim() + const literal = /^&?(?:\w+\.)?([A-Z]\w*)\s*\{/.exec(t) + if (literal) return literal[1] + const made = /^new\(\s*\*?(?:\w+\.)?(\w+)\s*\)$/.exec(t) + if (made) return made[1] + const call = /^(?:\w+\.)?(\w+)\s*\(/.exec(t) + if (call) return index.returnTypes.get(call[1]) ?? null + return null +} + +/** Paths and type names that hold data access rather than business logic. */ +const DATA_PATH = /(^|\/)(dal|dao|daos|repositor\w*|repo|repos|store|stores|query|queries|models?|entit\w*|persistence|db)(\/|\.go$)/i +const DATA_TYPE = /(Query|Repo|Repository|Dao|DAO|Store|Model|Mapper)$/ + +/** + * Whether rows of a model carry a tenant: its struct (or, for a named slice + * like `type SysRoleList []SysRole`, its element's struct) has a field named for + * the tenant. A table without one (menus, the tenants table itself) is shared, + * so a query on it has no tenant to miss. A model whose struct is not in the + * project (or "gorm" when no model is named) → true: it is still reported. + */ +export function modelHasTenantField( + model: string, + index: CodeIndex, + signalMatch: (text: string) => boolean, +): boolean { + // a DAO is judged by the entity it serves: UserQuery / UserRepository → User + const entity = model.replace(/(Query|Repo|Repository|Dao|DAO|Store|Mapper)$/, "") + if (entity !== model) model = entity + const element = index.elementTypes.get(model) + const candidates = [model, element].filter((t): t is string => !!t) + if (!candidates.some((t) => index.typeFiles.has(t))) return true + // one level of embedded structs: type User struct { BaseModel; ... } with TenantID in BaseModel + for (const t of [...candidates]) candidates.push(...(index.embeddedTypes.get(t) ?? [])) + return candidates.some((t) => (index.structFields.get(t) ?? []).some((field) => signalMatch(field))) +} + +export function isDataType(typeName: string, index: CodeIndex): boolean { + const file = index.typeFiles.get(typeName) + return (!!file && DATA_PATH.test(file)) || DATA_TYPE.test(typeName) +} + +/** + * The bare type of a receiver expression as written at a call site in `method`: + * the method's receiver (`s`), a field chain (`s.repo`), a parameter or local + * (`db := dal.BoardQuery{}`, `list := models.NewSysRoleList()`), or a + * package-level variable, possibly behind an import alias (`service.GroupApp.Board`). + * Null when any step does not resolve (or the expression contains a call). + */ +export function resolveReceiverType( + method: HandlerMethod, + receiver: string, + fieldTypesOf: (typeName: string) => Map, + index: CodeIndex, +): string | null { + if (receiver.includes("(") || receiver.includes("[")) return null + const segments = receiver.split(".") + let type: string | null = null + let rest = segments + + const recvName = receiverNameOf(method.node) + if (segments[0] === recvName) { + type = receiverTypeName(method.node) + rest = segments.slice(1) + } else { + const local = localType(method.node, segments[0], index) + if (local) { + type = local + rest = segments.slice(1) + } else if (index.packageVars.has(segments[0])) { + type = index.packageVars.get(segments[0])! + rest = segments.slice(1) + } else if (segments.length > 1 && index.packageVars.has(segments[1])) { + type = index.packageVars.get(segments[1])! // pkg.Var + rest = segments.slice(2) + } + } + for (const field of rest) { + if (!type) return null + type = fieldType(type, field, fieldTypesOf, index) + } + return type +} + +/** + * The type of `field` on a struct: a named field, an embedded struct (its field + * name is its type name: `type Controller struct { BoardApi }`), or a field + * promoted from an embedded struct, one level deep. + */ +function fieldType( + typeName: string, + field: string, + fieldTypesOf: (typeName: string) => Map, + index: CodeIndex, +): string | null { + const named = fieldTypesOf(typeName).get(field) + if (named) return named + const embedded = index.embeddedTypes.get(typeName) ?? [] + if (embedded.includes(field)) return field + for (const e of embedded) { + const promoted = fieldTypesOf(e).get(field) ?? ((index.embeddedTypes.get(e) ?? []).includes(field) ? field : undefined) + if (promoted) return promoted + } + return null +} + +function receiverNameOf(fn: SyntaxNode): string | null { + const decl = fn.childForFieldName("receiver")?.namedChildren.find((c) => c.type === "parameter_declaration") + return decl?.namedChildren.find((c) => c.type === "identifier")?.text ?? null +} + +/** The type of a parameter or a local declared in a function body. */ +function localType(fn: SyntaxNode, name: string, index: CodeIndex): string | null { + const param = functionParamTypes(fn).get(name) + if (param) return param + const body = fn.childForFieldName("body") + if (!body) return null + for (const n of walk(body)) { + if (n.type === "var_spec") { + if (!n.childrenForFieldName("name").some((id) => id.text === name)) continue + const t = varSpecType(n, index) + if (t) return t + } else if (n.type === "short_var_declaration" || n.type === "assignment_statement") { + const left = n.childForFieldName("left")?.namedChildren ?? [] + const right = n.childForFieldName("right")?.namedChildren ?? [] + const i = left.findIndex((l) => l.text === name) + if (i < 0 || !right[i]) continue + const t = typeOfValueText(right[i].text, index) + if (t) return t + } + } + return null +} diff --git a/packages/go-parser/src/graph-builder.ts b/packages/go-parser/src/graph-builder.ts index 01a3486..ffd31a2 100644 --- a/packages/go-parser/src/graph-builder.ts +++ b/packages/go-parser/src/graph-builder.ts @@ -8,8 +8,9 @@ import { buildConstRegistry, resolveConstExpr } from "./const-resolver.js" import { buildMethodRegistry, findBindCalls, resolveVarDtoType, type HandlerMethod } from "./handler-parser.js" import { resolveDtoBinding, findStructFieldTypes } from "./dto-binding-parser.js" import { findTransactionBoundaries } from "./transaction-parser.js" +import { buildCodeIndex, resolveReceiverType, isDataType, modelHasTenantField, type CodeIndex } from "./code-index.js" import { - findTenantContextRead, findGormOperations, tokenMatcher, + findTenantContextRead, findGormOperations, tokenMatcher, daoCall, variadicParamNames, type DataAccessContext, DEFAULT_TENANT_SIGNALS, DEFAULT_TENANT_CONTEXT_KEYS, type IsolationOptions, type TokenMatcher, type GormOperation, } from "./isolation-parser.js" @@ -267,6 +268,15 @@ interface IsolationContext { fieldTypesOf: (typeName: string) => Map keyMatch: TokenMatcher signalMatch: TokenMatcher + codeIndex: CodeIndex + /** GORM callbacks registered by the project whose function sets or filters the tenant. */ + tenantHooks: ReadonlySet<"create" | "update" | "delete" | "query"> +} + +/** A method on a request's path, with the argument text of the call that reached it. */ +interface PathEntry { + method: HandlerMethod + callerArgs: string } /** How far below the handler queries are looked for: handler → service → repository. */ @@ -294,32 +304,48 @@ function receiverName(fn: SyntaxNode): string | null { return decl?.namedChildren.find((c) => c.type === "identifier")?.text ?? null } -/** The handler plus the methods it reaches through its receiver and struct fields, up to ISOLATION_MAX_DEPTH. */ -function methodsOnPath(handler: HandlerMethod, ctx: IsolationContext): HandlerMethod[] { - const out: HandlerMethod[] = [] +function dataAccessContext(m: HandlerMethod, callerArgs: string, ctx: IsolationContext): DataAccessContext { + return { + resolveType: (receiver) => resolveReceiverType(m, receiver, ctx.fieldTypesOf, ctx.codeIndex), + isDataType: (t) => isDataType(t, ctx.codeIndex), + calleeOf: (t, name) => resolveMethod(ctx.methodRegistry, t, name), + passedParams: variadicParamNames(m.node), + callerArgs, + tenantHooks: ctx.tenantHooks, + } +} + +/** + * The handler plus the methods it reaches, up to ISOLATION_MAX_DEPTH: through + * its receiver and struct fields (`s.repo.Find`), locals and parameters of a + * known type (`db := dal.BoardQuery{}`), and package-level variables + * (`service.GroupApp.Board.CreateBoard`). A read/write call on a DAO or model + * wrapper is recorded where it is made (its arguments carry the scope), so the + * generic wrapper behind it is not followed. + */ +function methodsOnPath(handler: HandlerMethod, ctx: IsolationContext): PathEntry[] { + const out: PathEntry[] = [] const seen = new Set() - let frontier: HandlerMethod[] = [handler] + let frontier: PathEntry[] = [{ method: handler, callerArgs: "" }] for (let depth = 0; depth <= ISOLATION_MAX_DEPTH && frontier.length > 0; depth++) { - const next: HandlerMethod[] = [] - for (const m of frontier) { + const next: PathEntry[] = [] + for (const entry of frontier) { + const m = entry.method if (seen.has(m.node)) continue seen.add(m.node) - out.push(m) - const recvType = receiverTypeName(m.node) + out.push(entry) const body = m.node.childForFieldName("body") - if (!recvType || !body) continue - const fields = ctx.fieldTypesOf(recvType) - const recvName = receiverName(m.node) + if (!body) continue + const data = dataAccessContext(m, "", ctx) for (const call of findCalls(body)) { const parts = callParts(call) if (!parts?.receiver) continue - // `s.helper(...)` on the same receiver, or `s.repo.Find(...)` through a field - const target = parts.receiver.includes(".") - ? fields.get(parts.receiver.slice(parts.receiver.lastIndexOf(".") + 1)) - : (parts.receiver === recvName ? recvType : undefined) - if (!target) continue + const target = resolveReceiverType(m, parts.receiver, ctx.fieldTypesOf, ctx.codeIndex) + if (!target || daoCall(call, body, data, ctx.signalMatch)?.leaf) continue const callee = resolveMethod(ctx.methodRegistry, target, parts.method) - if (callee && !seen.has(callee.node)) next.push(callee) + if (callee && !seen.has(callee.node)) { + next.push({ method: callee, callerArgs: parts.args.map((a) => a.text).join(", ") }) + } } } frontier = next @@ -353,7 +379,7 @@ function isolationGraphPart( file: tenantMiddleware.file, line: tenantMiddleware.line, role: "runtime", } } - for (const m of path) { + for (const { method: m } of path) { if (tenantNode) break const read = findTenantContextRead(m, ctx.keyMatch) if (read) { @@ -366,9 +392,9 @@ function isolationGraphPart( if (!tenantNode) return { nodes: [], edges: [] } const ops: GormOperation[] = [] - for (const m of path) { + for (const { method: m, callerArgs } of path) { const recvType = receiverTypeName(m.node) - ops.push(...findGormOperations(m, recvType ? ctx.fieldTypesOf(recvType) : new Map(), ctx.signalMatch)) + ops.push(...findGormOperations(m, recvType ? ctx.fieldTypesOf(recvType) : new Map(), ctx.signalMatch, dataAccessContext(m, callerArgs, ctx))) } const nodes: ExecutionNode[] = [tenantNode] @@ -377,6 +403,9 @@ function isolationGraphPart( for (const op of ops) { if (index >= ISOLATION_MAX_QUERIES) break if (op.kind === "write" && op.scoped) continue // like Laravel: only unscoped writes become nodes + // an unscoped query only misses a tenant on a model whose rows carry one; + // shared tables declared in the project without a tenant field (menus, the tenants table) are not reported + if (!op.scoped && !modelHasTenantField(op.model, ctx.codeIndex, ctx.signalMatch)) continue const type = op.scoped ? IR_NODE_TYPES.SCOPED_QUERY : op.kind === "write" ? IR_NODE_TYPES.UNSCOPED_WRITE : IR_NODE_TYPES.UNSCOPED_QUERY @@ -487,6 +516,16 @@ export function parseGinProject(files: GoSourceFile[], opts: ParseGinOptions = { const ownershipSources = new Set(opts.ownershipSources ?? []) + const signalMatch = tokenMatcher(opts.isolation?.tenantSignals ?? DEFAULT_TENANT_SIGNALS) + const codeIndex = buildCodeIndex(parsed) + // a GORM callback whose function mentions the tenant (sets TenantID on create, filters by it on query) + const tenantHooks = new Set<"create" | "update" | "delete" | "query">() + for (const [op, names] of codeIndex.callbacks) { + if (names.some((n) => { const fn = codeIndex.functions.get(n); return !!fn && signalMatch(fn.text) })) { + tenantHooks.add(op as "create" | "update" | "delete" | "query") + } + } + const fieldTypeCache = new Map>() const isolation: IsolationContext = { methodRegistry, @@ -503,8 +542,46 @@ export function parseGinProject(files: GoSourceFile[], opts: ParseGinOptions = { return fields }, keyMatch: tokenMatcher(opts.isolation?.tenantContextKeys ?? DEFAULT_TENANT_CONTEXT_KEYS), - signalMatch: tokenMatcher(opts.isolation?.tenantSignals ?? DEFAULT_TENANT_SIGNALS), + signalMatch, + codeIndex, + tenantHooks, } - return routes.map((r) => routeToGraph(r, skipListIndex, constRegistry, methodRegistry, parsed, ownershipSources, isolation)) + const resolved = routes.map((r) => withHandlerReceiver(r, parsed, isolation)) + return resolved.map((r) => routeToGraph(r, skipListIndex, constRegistry, methodRegistry, parsed, ownershipSources, isolation)) +} + +/** + * Fills in a route's handler receiver type when route extraction could not: + * a handler reached through a package-level variable (`api.Controllers.BoardApi.CreateBoard`) + * or through a local of the registering function (`roles := controllers.NewSysRoleController()` + * then `roles.List`). Resolved from the function that registers the route, so the + * validation, transaction, ownership and isolation passes can read the handler. + */ +function withHandlerReceiver(route: RouteInfo, parsed: ParsedFile[], ctx: IsolationContext): RouteInfo { + if (route.handlerReceiverType) return route + const dot = route.handlerText.lastIndexOf(".") + if (dot <= 0 || /[\s(){}]/.test(route.handlerText)) return route + const receiver = route.handlerText.slice(0, dot) + const methodName = route.handlerText.slice(dot + 1) + const file = parsed.find((f) => f.path === route.file) + const enclosing = file ? enclosingFunction(file.root, route.line) : null + const site: HandlerMethod = enclosing + ? { node: enclosing, file: route.file, line: enclosing.startPosition.row + 1 } + : { node: file?.root ?? parsed[0].root, file: route.file, line: route.line } + const type = resolveReceiverType(site, receiver, ctx.fieldTypesOf, ctx.codeIndex) + const handler = type ? resolveMethod(ctx.methodRegistry, type, methodName) : null + const receiverType = handler ? receiverTypeName(handler.node) : null + return receiverType ? { ...route, handlerReceiverType: receiverType } : route +} + +/** The innermost function or method declaration spanning a 1-based line. */ +function enclosingFunction(root: SyntaxNode, line: number): SyntaxNode | null { + let best: SyntaxNode | null = null + for (const fn of findFunctionDecls(root)) { + const start = fn.startPosition.row + 1 + const end = fn.endPosition.row + 1 + if (start <= line && line <= end && (!best || fn.startPosition.row >= best.startPosition.row)) best = fn + } + return best } diff --git a/packages/go-parser/src/isolation-parser.ts b/packages/go-parser/src/isolation-parser.ts index b622100..aa023b5 100644 --- a/packages/go-parser/src/isolation-parser.ts +++ b/packages/go-parser/src/isolation-parser.ts @@ -53,13 +53,21 @@ export interface TenantContextRead { line: number } -/** The first place in `method` that reads the request's tenant, or null. */ +/** + * The first place in `method` that reads the request's tenant, or null: + * - a getter on the request context with a tenant key: `c.GetString("tenant_id")`; + * - an accessor named for the tenant: `GetTenantID(c)`, `tenant.FromContext(ctx)`; + * - a function named for the tenant handed the request context: `tenanthelper.TenantScope(c)`; + * - a field named for the tenant read off a value: `claims.TenantID` (JWT claims put + * in the context by middleware). + */ export function findTenantContextRead(method: HandlerMethod, keyMatch: TokenMatcher): TenantContextRead | null { const body = method.node.childForFieldName("body") if (!body) return null const contextParams = new Set( [...functionParamTypes(method.node)].filter(([, type]) => type === "Context").map(([name]) => name), ) + const at = (node: SyntaxNode): TenantContextRead => ({ symbol: shorten(node.text), file: method.file, line: node.startPosition.row + 1 }) for (const node of findCalls(body)) { const parts = callParts(node) @@ -73,9 +81,15 @@ export function findTenantContextRead(method: HandlerMethod, keyMatch: TokenMatc const isAccessor = ACCESSOR_NAME.test(parts.method) && (keyMatch(parts.method) || (!!receiverTail && keyMatch(receiverTail))) - if (isContextGetter || isAccessor) { - return { symbol: shorten(node.text), file: method.file, line: node.startPosition.row + 1 } - } + const isTenantFunctionOfContext = + keyMatch(parts.method) && parts.args.some((a) => contextParams.has(a.text)) + if (isContextGetter || isAccessor || isTenantFunctionOfContext) return at(node) + } + for (const node of walk(body)) { + if (node.type !== "selector_expression") continue + const operand = node.childForFieldName("operand") + const field = node.childForFieldName("field") + if (operand?.type === "identifier" && field && keyMatch(field.text)) return at(node) } return null } @@ -105,14 +119,110 @@ export interface GormOperation { line: number } +/** Methods a DAO / repository / model wrapper exposes for reads and writes, beyond GORM's own. */ +const DAO_READ_OPS = new Set([...READ_OPS, "Get", "GetByID", "GetById", "FindByID", "FindById", "FindOne", "List", "Page", "Query", "Exists"]) +const DAO_WRITE_OPS = new Set([...WRITE_OPS, "Insert", "Remove", "Upsert", "BatchCreate", "CreateInBatches"]) + +/** Which GORM callback chain an operation goes through. */ +function callbackOf(operation: string, kind: "read" | "write"): "create" | "update" | "delete" | "query" { + if (kind === "read") return "query" + if (/^(Delete|Remove)$/.test(operation)) return "delete" + if (/^(Update|Updates|UpdateColumn|UpdateColumns)$/.test(operation)) return "update" + return "create" +} + +/** What findGormOperations needs to see past plain GORM chains. */ +export interface DataAccessContext { + /** Type of a receiver expression at a call site in the method (`db`, `s.repo`, `service.GroupApp.Board`). */ + resolveType: (receiver: string) => string | null + /** Whether a type is a DAO / repository / model (declared under dal/, models/, ... or named so). */ + isDataType: (typeName: string) => boolean + /** Argument text at the call site that reached this method, for scopes passed in (`Scopes(funcs...)`). */ + callerArgs: string + /** GORM callbacks that add the tenant on their own (a create hook that sets TenantID). */ + tenantHooks: ReadonlySet<"create" | "update" | "delete" | "query"> + /** The project method a call resolves to, if any. */ + calleeOf: (typeName: string, method: string) => HandlerMethod | null + /** The method's variadic parameters (`scopes ...func(*gorm.DB) *gorm.DB`): conditions its caller hands in. */ + passedParams: ReadonlySet +} + +/** `Preload("Tenant")` loads a relation, it does not filter rows: drop it before looking for a tenant signal. */ +function withoutPreloads(text: string): string { + return text.replace(/\.Preload\(\s*("[^"]*"|`[^`]*`)[^)]*\)/g, "") +} + +/** Whether any text forwards one of the method's variadic parameters (`scopes...`). */ +function forwardsPassedParam(texts: string[], params: ReadonlySet): boolean { + return [...params].some((p) => texts.some((t) => new RegExp(`\\b${p}\\s*\\.\\.\\.`).test(t))) +} + +/** The names of a function's variadic parameters. */ +export function variadicParamNames(fn: SyntaxNode): Set { + const out = new Set() + for (const p of fn.childForFieldName("parameters")?.namedChildren ?? []) { + if (p.type !== "variadic_parameter_declaration") continue + const name = p.childForFieldName("name")?.text + if (name) out.add(name) + } + return out +} + +export interface DaoCall { + kind: "read" | "write" + type: string + scoped: boolean + /** + * Whether the call is judged where it is made instead of inside the callee: + * the callee takes its conditions from the caller (`First(ctx, option ...gen.Condition)`, + * `Find(c, funcs ...func(*gorm.DB) *gorm.DB)`) or is not in the project, or it is + * a write whose record the caller has already tied to the tenant. + */ + leaf: boolean +} + +/** A read/write-named call on a DAO, repository or model wrapper, or null. */ +export function daoCall(call: SyntaxNode, body: SyntaxNode, data: DataAccessContext, signalMatch: TokenMatcher): DaoCall | null { + const parts = callParts(call) + if (!parts?.receiver) return null + const kind = DAO_READ_OPS.has(parts.method) ? "read" : DAO_WRITE_OPS.has(parts.method) ? "write" : null + if (!kind) return null + const type = data.resolveType(parts.receiver) + if (!type || !data.isDataType(type)) return null + + const texts = [call.text] + for (const a of parts.args) { + const name = /^([A-Za-z_]\w*)(\.\.\.)?$/.exec(a.text)?.[1] + if (name) texts.push(...assignmentsTo(body, name)) // queryScopes := append(..., scopes...) + } + if (kind === "write") for (const a of parts.args) texts.push(...statementsMentioning(body, destinationVar(a))) + const scoped = texts.some((t) => signalMatch(withoutPreloads(t))) || + (forwardsPassedParam(texts, data.passedParams) && signalMatch(data.callerArgs)) || + data.tenantHooks.has(callbackOf(parts.method, kind)) + + const callee = data.calleeOf(type, parts.method) + const takesConditions = !callee || hasVariadicParameter(callee.node) + return { kind, type, scoped, leaf: takesConditions || (kind === "write" && scoped) } +} + +function hasVariadicParameter(fn: SyntaxNode): boolean { + return fn.childForFieldName("parameters")?.namedChildren.some((p) => p.type === "variadic_parameter_declaration") ?? false +} + /** * GORM reads and writes in `method`'s body. `receiverFields` maps the method's * receiver struct fields to their bare types, so `r.db` typed `*gorm.DB` counts. + * With `data`, a read/write-named call on a DAO or model wrapper + * (`db.First(ctx, query.Board.TenantID.Eq(t))`, `list.Find(c, TenantScope(c))`) + * counts too, scoped by its arguments; a scope a wrapper receives as a parameter + * (`Scopes(funcs...)`) is judged by the arguments at the call site that reached it; + * and an operation whose GORM callback adds the tenant counts as scoped. */ export function findGormOperations( method: HandlerMethod, receiverFields: ReadonlyMap, signalMatch: TokenMatcher, + data?: DataAccessContext, ): GormOperation[] { const body = method.node.childForFieldName("body") if (!body) return [] @@ -122,32 +232,79 @@ export function findGormOperations( for (const node of findCalls(body)) { const parts = callParts(node) if (!parts) continue - const kind = READ_OPS.has(parts.method) ? "read" : WRITE_OPS.has(parts.method) ? "write" : null - if (!kind) continue + + // a DAO / repository / model wrapper call, checked first so a wrapper held in a + // variable named `db` (db := dal.UserQuery{}) is not taken for *gorm.DB. + // Judged here when it is a leaf (db.First(ctx, query.Board.TenantID.Eq(t)), + // list.Find(c, scopes...)); otherwise followed into the callee (see methodsOnPath). + const dao = data ? daoCall(node, body, data, signalMatch) : null + if (dao) { + if (dao.leaf) { + out.push({ + kind: dao.kind, operation: parts.method, model: dao.type, scoped: dao.scoped, + file: method.file, line: node.startPosition.row + 1, + }) + } + continue + } const { base, calls } = chainOf(node) + const kind = READ_OPS.has(parts.method) ? "read" : WRITE_OPS.has(parts.method) ? "write" : null const baseAssignments = base?.type === "identifier" ? assignmentsTo(body, base.text) : [] - const chainIsGorm = calls.slice(1).some((c) => GORM_CHAIN.has(callParts(c)?.method ?? "")) - const baseIsGorm = + const chainIsGorm = !!kind && calls.slice(1).some((c) => GORM_CHAIN.has(callParts(c)?.method ?? "")) + const baseIsGorm = !!kind && ( isDbExpression(base, paramTypes, receiverFields) || - baseAssignments.some((text) => /\.(db|DB|tx)\b|\.(Where|Model|Table|WithContext|Scopes)\(/.test(text)) - if (!chainIsGorm && !baseIsGorm) continue - - const texts = [node.text, ...baseAssignments] - if (kind === "write") texts.push(...statementsMentioning(body, destinationVar(parts.args[0]))) - - out.push({ - kind, - operation: parts.method, - model: modelOf(calls, parts.args[0], body) ?? "gorm", - scoped: texts.some(signalMatch), - file: method.file, - line: node.startPosition.row + 1, - }) + baseAssignments.some((text) => /\.(db|DB|tx)\b|\.(Where|Model|Table|WithContext|Scopes)\(/.test(text))) + + if (chainIsGorm || baseIsGorm) { + const texts = [node.text, ...baseAssignments] + // a subquery or condition built in a variable: Where("device_id IN (?)", devices) + for (const c of calls) { + for (const a of callParts(c)?.args ?? []) { + if (a.type === "identifier" && a.text !== base?.text) texts.push(...assignmentsTo(body, a.text)) + } + } + if (kind === "write") texts.push(...statementsMentioning(body, destinationVar(parts.args[0]))) + // a scope handed in by the caller: Scopes(funcs...) with funcs a parameter + const passedScope = calls.some((c) => { + const p = callParts(c) + return p?.method === "Scopes" && p.args.some((a) => paramTypes.has(a.text.replace(/\.\.\.$/, "")) || /\.\.\.$/.test(a.text)) + }) + const scoped = texts.some((t) => signalMatch(withoutPreloads(t))) || + (passedScope && !!data && signalMatch(data.callerArgs)) || + (!!data && data.tenantHooks.has(callbackOf(parts.method, kind!))) + out.push({ + kind: kind!, + operation: parts.method, + model: modelOf(calls, parts.args[0], body) ?? valueModel(parts.args[0], data) ?? + genModel(base, baseAssignments) ?? "gorm", + scoped, + file: method.file, + line: node.startPosition.row + 1, + }) + } } return out } +/** First(t) on the receiver or a typed local: the model is that value's type, when it is a project model. */ +function valueModel(arg: SyntaxNode | undefined, data: DataAccessContext | undefined): string | null { + const name = destinationVar(arg) + if (!name || !data) return null + const type = data.resolveType(name) + return type && data.isDataType(type) ? type : null +} + +/** gorm-gen: `query.Device.WithContext(ctx)...First()` or `users := query.User; users.Where(...)` → the model name. */ +function genModel(base: SyntaxNode | null, baseAssignments: string[]): string | null { + const texts = [base?.text ?? "", ...baseAssignments.map((a) => a.split(/:?=/).pop()!.trim())] + for (const t of texts) { + const m = /^\w+\.([A-Z]\w*)$/.exec(t) + if (m) return m[1] + } + return null +} + /** The receiver chain of a call: `r.db.Where(...).First(&x)` → base `r.db`, calls [First, Where]. */ function chainOf(call: SyntaxNode): { base: SyntaxNode | null; calls: SyntaxNode[] } { const calls = [call] @@ -179,14 +336,35 @@ function isDbExpression( } /** Texts of `name := ...` / `name = ...` / `var name = ...` statements in a body. */ -function assignmentsTo(body: SyntaxNode, name: string): string[] { - const out: string[] = [] - for (const n of walk(body)) { - if (n.type !== "short_var_declaration" && n.type !== "assignment_statement" && n.type !== "var_spec") continue - const left = n.childForFieldName("left") ?? n.childForFieldName("name") - if (left && (left.text.split(/\s*,\s*/).includes(name))) out.push(n.text) +/** + * Assignments in a body, by assigned name. Built once per body (one walk) and + * kept per tree, keyed by the body's span: tree-sitter does not guarantee one + * JS object per node, so nodes are not used as keys. + */ +const assignmentIndex = new WeakMap>>() + +function assignmentsIn(body: SyntaxNode): Map { + let perTree = assignmentIndex.get(body.tree) + if (!perTree) { perTree = new Map(); assignmentIndex.set(body.tree, perTree) } + const key = `${body.startIndex}:${body.endIndex}` + let byName = perTree.get(key) + if (!byName) { + byName = new Map() + for (const n of walk(body)) { + if (n.type !== "short_var_declaration" && n.type !== "assignment_statement" && n.type !== "var_spec") continue + const left = n.childForFieldName("left") ?? n.childForFieldName("name") + if (!left) continue + for (const name of new Set(left.text.split(/\s*,\s*/))) { + byName.set(name, [...(byName.get(name) ?? []), n.text]) + } + } + perTree.set(key, byName) } - return out + return byName +} + +function assignmentsTo(body: SyntaxNode, name: string): string[] { + return assignmentsIn(body).get(name) ?? [] } /** `&order` / `order` → "order"; anything else → null. */ From da8515c8dde76047169ce16ca148961bc179c04b Mon Sep 17 00:00:00 2001 From: kidkender Date: Fri, 13 Nov 2026 09:44:46 +0700 Subject: [PATCH 23/25] fix(go-parser): join group prefixes and route paths the way Gin does Route paths were the plain concatenation of every Group() prefix and the route path, so groups written without slashes (Group("api").Group("v1") .POST("device")) came out as "apiv1device" instead of /api/v1/device, and "/api/" + "/users" as "/api//users". Gin joins them with path.Join, keeping a trailing slash on the relative path; joinPaths does the same. thingspanel-backend-community: 233 of 267 routes had a malformed path, now 0. ginfast: 2 of 122, now 0. Route counts unchanged. --- .../src/__tests__/route-path-join.test.ts | 59 +++++++++++++++++++ packages/go-parser/src/route-parser.ts | 17 +++++- 2 files changed, 73 insertions(+), 3 deletions(-) create mode 100644 packages/go-parser/src/__tests__/route-path-join.test.ts diff --git a/packages/go-parser/src/__tests__/route-path-join.test.ts b/packages/go-parser/src/__tests__/route-path-join.test.ts new file mode 100644 index 0000000..0895af2 --- /dev/null +++ b/packages/go-parser/src/__tests__/route-path-join.test.ts @@ -0,0 +1,59 @@ +import { describe, test, expect } from "@jest/globals" +import { extractRoutes, joinPaths, type GoSourceFile } from "../route-parser.js" + +// Gin joins a group's prefix and a route's path with path.Join, so slashes are +// optional on either side: Group("api").Group("v1").POST("device") serves +// /api/v1/device. Plain concatenation produced "apiv1device". + +const file = (content: string): GoSourceFile => ({ path: "main.go", content }) +const paths = (content: string) => extractRoutes([file(content)]).map((r) => `${r.method} ${r.path}`) + +describe("joinPaths", () => { + test.each([ + ["", "", ""], + ["", "/", "/"], + ["", "api", "/api"], + ["/api", "v1", "/api/v1"], + ["/api/", "/v1", "/api/v1"], + ["/api", "", "/api"], + ["/api", "/", "/api/"], + ["/api", "users/", "/api/users/"], + ["/api", "//users", "/api/users"], + ["/api", ":id", "/api/:id"], + ["/files", "*filepath", "/files/*filepath"], + ])("joinPaths(%j, %j) = %j", (base, relative, expected) => { + expect(joinPaths(base, relative)).toBe(expected) + }) +}) + +describe("route paths built from groups without slashes", () => { + test("groups and routes written without leading slashes", () => { + expect(paths(`package main +func main() { + r := gin.Default() + api := r.Group("api") + v1 := api.Group("v1") + device := v1.Group("device") + device.POST("", create) + device.GET(":id", get) + device.GET("detail/:id", detail) +}`)).toEqual(["POST /api/v1/device", "GET /api/v1/device/:id", "GET /api/v1/device/detail/:id"]) + }) + + test("a trailing slash on the group does not double up", () => { + expect(paths(`package main +func main() { + r := gin.Default() + api := r.Group("/api/") + api.GET("/users", list) +}`)).toEqual(["GET /api/users"]) + }) + + test("a route on the engine with an empty path is /", () => { + expect(paths(`package main +func main() { + r := gin.Default() + r.GET("", home) +}`)).toEqual(["GET /"]) + }) +}) diff --git a/packages/go-parser/src/route-parser.ts b/packages/go-parser/src/route-parser.ts index 7a7c525..d7abdf9 100644 --- a/packages/go-parser/src/route-parser.ts +++ b/packages/go-parser/src/route-parser.ts @@ -21,7 +21,7 @@ export interface MiddlewareRef { export interface RouteInfo { method: string - /** Fully resolved path — concatenation of every enclosing Group() prefix. */ + /** Fully resolved path — every enclosing Group() prefix joined the way Gin joins them. */ path: string /** Raw text of the final (handler) argument, e.g. "handler.CreateOrder". */ handlerText: string @@ -170,7 +170,18 @@ function groupOf(expr: SyntaxNode, file: string, groups: Map const refs = (nodes: SyntaxNode[]): MiddlewareRef[] => nodes.map((a) => toMiddlewareRef(a, file)).filter((m): m is MiddlewareRef => !!m) if (method === "Use") return { ...base, middleware: [...base.middleware, ...refs(args)] } const [pathArg, ...mwArgs] = args - return { prefix: base.prefix + (pathArg ? stringLiteralValue(pathArg) ?? "" : ""), middleware: [...base.middleware, ...refs(mwArgs)] } + return { prefix: joinPaths(base.prefix, pathArg ? stringLiteralValue(pathArg) ?? "" : ""), middleware: [...base.middleware, ...refs(mwArgs)] } +} + +/** + * Gin's joinPaths: `path.Join(base, relative)`, keeping a trailing slash the + * relative path has. `Group("api").Group("v1").POST("device")` is /api/v1/device, + * and `Group("/api/").GET("/x")` is /api/x — not a plain concatenation. + */ +export function joinPaths(base: string, relative: string): string { + if (relative === "") return base + const joined = "/" + [...base.split("/"), ...relative.split("/")].filter((s) => s !== "" && s !== ".").join("/") + return relative.endsWith("/") && !joined.endsWith("/") ? `${joined}/` : joined } /** @@ -313,7 +324,7 @@ function handleStatement( routes.push({ method: parts.method, - path: state.prefix + suffix, + path: joinPaths(state.prefix, suffix) || "/", handlerText: handlerArg.text, handlerReceiverType: handlerReceiverType(handlerArg, paramTypes), middleware: [...state.middleware, ...inlineMw], From c4c14bf85a07b7bbd5d0c02150cd352c779e214b Mon Sep 17 00:00:00 2001 From: kidkender Date: Fri, 13 Nov 2026 10:41:16 +0700 Subject: [PATCH 24/25] chore: release v0.10.0 --- CHANGELOG.md | 15 +++++++++- apps/cli/package.json | 2 +- package-lock.json | 38 ++++++++++++------------- packages/analysis/package.json | 2 +- packages/explainer/package.json | 4 +-- packages/express-parser/package.json | 2 +- packages/go-parser/package.json | 4 +-- packages/laravel-parser/package.json | 4 +-- packages/lens/package.json | 6 ++-- packages/lsp/package.json | 2 +- packages/mcp-server/package.json | 2 +- packages/nestjs-parser/package.json | 4 +-- packages/protocol/package.json | 2 +- packages/springboot-parser/package.json | 4 +-- 14 files changed, 52 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ee104d3..35ebfe9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,10 @@ # Changelog -## [Unreleased] +## [0.10.0] - 2026-11-13 ### Added +- **`@kidkender/archmind-go-parser` 0.4.0: tenant isolation for Gin + GORM.** On a route that resolves a tenant (a tenant middleware, `c.Get("tenant_id")`, an accessor such as `GetTenantID(c)`, a tenant-named function handed the context such as `TenantScope(c)`, or a field such as `claims.TenantID`), an `ir:tenant_context` node and every query in the handler and two calls below it as `ir:scoped_query` or `ir:unscoped_query` / `ir:unscoped_write`; the explainer reports unscoped ones as `missing_tenant_scope`. Calls are followed through struct fields, typed locals, package-level registries and embedded structs; DAO / repository / model wrappers count as queries, judged at the call site when they take their conditions as arguments; GORM callbacks that set the tenant, shared tables without a tenant field and `Preload("Tenant")` are taken into account. Routes that resolve no tenant get none of these nodes. `archmind.json` `isolation.tenantSignals` / `isolation.tenantContextKeys` (`protocol` 0.6.0). +- **`@kidkender/archmind-springboot-parser` 0.5.0: `archmind.json` `guards`.** Annotation names under `guards.auth_gate` emit `ir:auth_gate`, under `guards.authz_check` `ir:auth_gate` → `ir:authz_check`, ahead of the built-in rules (a listed Shiro `@RequiresRoles` is no longer `ir:unknown_middleware`). - **`@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. @@ -10,6 +12,7 @@ ### 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`. +- `@kidkender/archmind-laravel-parser`: each file is parsed once per run and method lookups no longer walk whole trees. On invoiceninja the CLI ran for over 10 minutes and ran out of memory once files over 32 KiB were parsed; it now takes 22 s. ### 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. @@ -21,6 +24,16 @@ - `@kidkender/archmind-laravel-parser`: the transaction, isolation, audit-log and nested service-call passes inside a service method, and a queued job's `handle()`, swallowed any error silently. The parsers already turn unreadable files into empty results, so what reached these catches was a bug that read as "nothing found". It is now reported on stderr (`[archmind] laravel-parser: skipped for : `) and the pass is skipped as before. - Flaky tests in `retrieval`, `nestjs-parser` and `mcp-server`: their tests load the tree-sitter parsers, whose module-level parser fails intermittently when Jest reuses one worker process across test files. Each test file now gets its own process (`maxWorkers`), as `laravel-parser` already did. Measured: `retrieval` with every file in one process failed 5 of 5 runs; with the fix it passed 10 of 10, as did `nestjs-parser`. - `npm run trace` at the repository root pointed at `apps/cli/dist/index.js`; the CLI builds to `index.cjs`. +- **`laravel-parser` and `springboot-parser`: controllers and services over 32 KiB produced no auth, transaction, isolation or guard nodes.** tree-sitter 0.21 rejects input past its default buffer and only route parsing sized it; every read and parse now sizes the buffer to the source. A parse failure is printed on stderr with the file path instead of reading as an empty file. +- `laravel-parser`: output could differ between identical runs (koel 1943 / 1946 / 1943 nodes) because tree-sitter nodes were compared by object identity; they are compared by position now. +- `@kidkender/archmind-go-parser`: route paths were the plain concatenation of the group prefixes, so `Group("api").Group("v1").POST("device")` came out as `apiv1device`. Paths are joined the way Gin joins them (233 of 267 routes on one project were malformed, now none). +- The CLI did not detect a Gin project whose `go.mod` is one directory down (analysis and the MCP server already did). +- `archmind visualize` ignored `archmind.json` `ignoreFindings`. +- A clean checkout did not build: `npm run build` built the workspaces in alphabetical order, before the packages they depend on. It builds them in dependency order now, and CI passes on a fresh clone. + +### Release notes +- Versions: CLI 0.10.0, `express-parser` 0.1.0 (new), `go-parser` 0.4.0, `springboot-parser` 0.5.0, `protocol` 0.6.0, `analysis` 0.3.0, `mcp-server` 0.8.0, `explainer` 0.3.4, `laravel-parser` 0.5.3, `nestjs-parser` 0.7.2, `lsp` 0.1.4, `lens` 0.2.1 (needs `go-parser` ^0.4.0). Packages that depended on `protocol` ^0.5 now need ^0.6.0. +- Publish order: `protocol`, `laravel-parser`, `springboot-parser`, `nestjs-parser`, `go-parser`, `express-parser`, `explainer`, `lens`, `analysis`, `lsp`, `mcp-server`, CLI. ## [0.9.1] - 2026-10-28 diff --git a/apps/cli/package.json b/apps/cli/package.json index a63d061..fa10d3d 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind", - "version": "0.9.1", + "version": "0.10.0", "description": "Execution topology intelligence for Laravel, NestJS, and Go/Gin — trace routes, detect regressions, find security gaps. No LLM required.", "type": "module", "bin": { diff --git a/package-lock.json b/package-lock.json index 67dc6d3..15448b8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,7 @@ }, "apps/cli": { "name": "@kidkender/archmind", - "version": "0.9.1", + "version": "0.10.0", "license": "MIT", "dependencies": { "@kidkender/archmind-explainer": "*", @@ -6199,7 +6199,7 @@ }, "packages/analysis": { "name": "@kidkender/archmind-analysis", - "version": "0.2.3", + "version": "0.3.0", "license": "MIT", "dependencies": { "@kidkender/archmind-express-parser": "*", @@ -6276,11 +6276,11 @@ }, "packages/explainer": { "name": "@kidkender/archmind-explainer", - "version": "0.3.3", + "version": "0.3.4", "license": "MIT", "dependencies": { "@kidkender/archmind-graph-query": "*", - "@kidkender/archmind-protocol": "^0.5.0" + "@kidkender/archmind-protocol": "^0.6.0" }, "devDependencies": { "@kidkender/archmind-laravel-parser": "*", @@ -6300,7 +6300,7 @@ "version": "0.1.0", "license": "MIT", "dependencies": { - "@kidkender/archmind-protocol": "^0.5.1", + "@kidkender/archmind-protocol": "^0.6.0", "ts-morph": "^23.0.0" }, "devDependencies": { @@ -6318,10 +6318,10 @@ }, "packages/go-parser": { "name": "@kidkender/archmind-go-parser", - "version": "0.3.0", + "version": "0.4.0", "license": "MIT", "dependencies": { - "@kidkender/archmind-protocol": "^0.5.1", + "@kidkender/archmind-protocol": "^0.6.0", "tree-sitter": "^0.25.0", "tree-sitter-go": "^0.25.0" }, @@ -6380,10 +6380,10 @@ }, "packages/laravel-parser": { "name": "@kidkender/archmind-laravel-parser", - "version": "0.5.2", + "version": "0.5.3", "license": "MIT", "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.6.0", "tree-sitter": "^0.21.0", "tree-sitter-php": "^0.23.0" }, @@ -6400,11 +6400,11 @@ }, "packages/lens": { "name": "@kidkender/archmind-lens", - "version": "0.2.0", + "version": "0.2.1", "license": "MIT", "dependencies": { - "@kidkender/archmind-go-parser": "^0.3.0", - "@kidkender/archmind-protocol": "^0.5.1" + "@kidkender/archmind-go-parser": "^0.4.0", + "@kidkender/archmind-protocol": "^0.6.0" }, "devDependencies": { "@types/jest": "^29.5.0", @@ -6436,7 +6436,7 @@ }, "packages/lsp": { "name": "@kidkender/archmind-lsp", - "version": "0.1.3", + "version": "0.1.4", "license": "MIT", "dependencies": { "tree-sitter": "^0.21.0", @@ -6464,7 +6464,7 @@ }, "packages/mcp-server": { "name": "@kidkender/archmind-mcp", - "version": "0.7.1", + "version": "0.8.0", "license": "MIT", "dependencies": { "@kidkender/archmind-explainer": "*", @@ -6515,10 +6515,10 @@ }, "packages/nestjs-parser": { "name": "@kidkender/archmind-nestjs-parser", - "version": "0.7.1", + "version": "0.7.2", "license": "MIT", "dependencies": { - "@kidkender/archmind-protocol": "^0.5.1", + "@kidkender/archmind-protocol": "^0.6.0", "js-yaml": "^4.3.2", "ts-morph": "^23.0.0" }, @@ -6575,7 +6575,7 @@ }, "packages/protocol": { "name": "@kidkender/archmind-protocol", - "version": "0.5.1", + "version": "0.6.0", "license": "MIT", "devDependencies": { "typescript": "^5.4.0" @@ -6659,10 +6659,10 @@ }, "packages/springboot-parser": { "name": "@kidkender/archmind-springboot-parser", - "version": "0.4.0", + "version": "0.5.0", "license": "MIT", "dependencies": { - "@kidkender/archmind-protocol": "^0.5.1", + "@kidkender/archmind-protocol": "^0.6.0", "tree-sitter": "^0.21.0", "tree-sitter-java": "^0.23.5" }, diff --git a/packages/analysis/package.json b/packages/analysis/package.json index 76a4b25..c0c7ec6 100644 --- a/packages/analysis/package.json +++ b/packages/analysis/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind-analysis", - "version": "0.2.3", + "version": "0.3.0", "description": "Canonical analysis pipeline for ArchMind — parse project → RouteInfo[] with findings", "type": "module", "main": "./dist/analysis.cjs", diff --git a/packages/explainer/package.json b/packages/explainer/package.json index 30dffb6..70aed33 100644 --- a/packages/explainer/package.json +++ b/packages/explainer/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind-explainer", - "version": "0.3.3", + "version": "0.3.4", "description": "Explanation engine for ArchMind — fact extraction, pattern detection, evidence packaging, and finding ranking for Laravel/NestJS execution graphs.", "type": "module", "main": "dist/index.js", @@ -17,7 +17,7 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.6.0", "@kidkender/archmind-graph-query": "*" }, "devDependencies": { diff --git a/packages/express-parser/package.json b/packages/express-parser/package.json index 9a53c03..c7ba01d 100644 --- a/packages/express-parser/package.json +++ b/packages/express-parser/package.json @@ -36,7 +36,7 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-protocol": "^0.5.1", + "@kidkender/archmind-protocol": "^0.6.0", "ts-morph": "^23.0.0" }, "devDependencies": { diff --git a/packages/go-parser/package.json b/packages/go-parser/package.json index e3548b0..6bdf21d 100644 --- a/packages/go-parser/package.json +++ b/packages/go-parser/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind-go-parser", - "version": "0.3.0", + "version": "0.4.0", "description": "Static analysis parser for Go/Gin projects — extracts routes, middleware chains (including runtime skip-lists), and auth patterns into ArchMind IR graphs.", "type": "module", "main": "dist/index.js", @@ -35,7 +35,7 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-protocol": "^0.5.1", + "@kidkender/archmind-protocol": "^0.6.0", "tree-sitter": "^0.25.0", "tree-sitter-go": "^0.25.0" }, diff --git a/packages/laravel-parser/package.json b/packages/laravel-parser/package.json index a99be3a..222c316 100644 --- a/packages/laravel-parser/package.json +++ b/packages/laravel-parser/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind-laravel-parser", - "version": "0.5.2", + "version": "0.5.3", "description": "Static analysis parser for Laravel projects — extracts routes, middleware chains, FormRequest validation rules, and auth patterns into ArchMind IR graphs.", "type": "module", "main": "dist/index.js", @@ -36,7 +36,7 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.6.0", "tree-sitter": "^0.21.0", "tree-sitter-php": "^0.23.0" }, diff --git a/packages/lens/package.json b/packages/lens/package.json index ece123b..3032e8e 100644 --- a/packages/lens/package.json +++ b/packages/lens/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind-lens", - "version": "0.2.0", + "version": "0.2.1", "description": "Symbol-first context for Go services: from any function, find the HTTP routes, background loops, callbacks and startup code that reach it, and whether the call runs inside a database transaction.", "type": "module", "main": "dist/index.js", @@ -34,8 +34,8 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-go-parser": "^0.3.0", - "@kidkender/archmind-protocol": "^0.5.1" + "@kidkender/archmind-go-parser": "^0.4.0", + "@kidkender/archmind-protocol": "^0.6.0" }, "devDependencies": { "@types/jest": "^29.5.0", diff --git a/packages/lsp/package.json b/packages/lsp/package.json index ebc30bd..8d47d4b 100644 --- a/packages/lsp/package.json +++ b/packages/lsp/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind-lsp", - "version": "0.1.3", + "version": "0.1.4", "description": "ArchMind Language Server — inlay hints and diagnostics for Laravel and NestJS in any LSP-compatible editor", "type": "module", "bin": { diff --git a/packages/mcp-server/package.json b/packages/mcp-server/package.json index 8182132..e929cdf 100644 --- a/packages/mcp-server/package.json +++ b/packages/mcp-server/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind-mcp", - "version": "0.7.1", + "version": "0.8.0", "description": "ArchMind MCP server — semantic execution graph intelligence for Laravel, NestJS, and Go/Gin projects, wired into Claude Code and any MCP-compatible AI client.", "type": "module", "bin": { diff --git a/packages/nestjs-parser/package.json b/packages/nestjs-parser/package.json index 49feb10..f1a4e17 100644 --- a/packages/nestjs-parser/package.json +++ b/packages/nestjs-parser/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind-nestjs-parser", - "version": "0.7.1", + "version": "0.7.2", "description": "Static analysis parser for NestJS projects — extracts routes, auth guards, DTOs, and class-validator field rules into ArchMind IR graphs.", "type": "module", "main": "dist/index.js", @@ -36,7 +36,7 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-protocol": "^0.5.1", + "@kidkender/archmind-protocol": "^0.6.0", "js-yaml": "^4.3.2", "ts-morph": "^23.0.0" }, diff --git a/packages/protocol/package.json b/packages/protocol/package.json index ed6a8dc..60614d3 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind-protocol", - "version": "0.5.1", + "version": "0.6.0", "description": "Shared type vocabulary for the ArchMind ecosystem — IR graph types, validation contracts, runtime correlation types.", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/springboot-parser/package.json b/packages/springboot-parser/package.json index bfe0a4f..3503fb1 100644 --- a/packages/springboot-parser/package.json +++ b/packages/springboot-parser/package.json @@ -1,6 +1,6 @@ { "name": "@kidkender/archmind-springboot-parser", - "version": "0.4.0", + "version": "0.5.0", "description": "Static analysis parser for Spring Boot projects — extracts REST controllers, security annotations, @Transactional boundaries, and service call graphs into ArchMind IR.", "type": "module", "main": "dist/index.js", @@ -22,7 +22,7 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-protocol": "^0.5.1", + "@kidkender/archmind-protocol": "^0.6.0", "tree-sitter": "^0.21.0", "tree-sitter-java": "^0.23.5" }, From 38b8350f77111835a5ae3d600853cd81e9cc5bd8 Mon Sep 17 00:00:00 2001 From: kidkender Date: Fri, 13 Nov 2026 11:06:58 +0700 Subject: [PATCH 25/25] fix(lsp): declare analysis as a runtime dependency lsp's build keeps @kidkender/archmind-analysis external (it pulls in go-parser's native tree-sitter-go, which esbuild cannot bundle), but the package listed it only under devDependencies, so an installed lsp 0.1.4 would fail with MODULE_NOT_FOUND on start. It is now a dependency (^0.3.0). --- CHANGELOG.md | 1 + package-lock.json | 2 +- packages/lsp/package.json | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35ebfe9..2d651a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ ### Release notes - Versions: CLI 0.10.0, `express-parser` 0.1.0 (new), `go-parser` 0.4.0, `springboot-parser` 0.5.0, `protocol` 0.6.0, `analysis` 0.3.0, `mcp-server` 0.8.0, `explainer` 0.3.4, `laravel-parser` 0.5.3, `nestjs-parser` 0.7.2, `lsp` 0.1.4, `lens` 0.2.1 (needs `go-parser` ^0.4.0). Packages that depended on `protocol` ^0.5 now need ^0.6.0. +- `lsp` 0.1.4 loads `analysis` from its own install instead of bundling it (`analysis` pulls in `go-parser`'s native tree-sitter-go, which cannot be bundled), so `analysis` ^0.3.0 is now a dependency of `lsp`. - Publish order: `protocol`, `laravel-parser`, `springboot-parser`, `nestjs-parser`, `go-parser`, `express-parser`, `explainer`, `lens`, `analysis`, `lsp`, `mcp-server`, CLI. ## [0.9.1] - 2026-10-28 diff --git a/package-lock.json b/package-lock.json index 15448b8..60357bd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6439,6 +6439,7 @@ "version": "0.1.4", "license": "MIT", "dependencies": { + "@kidkender/archmind-analysis": "^0.3.0", "tree-sitter": "^0.21.0", "tree-sitter-java": "^0.23.0", "tree-sitter-php": "^0.23.0", @@ -6448,7 +6449,6 @@ "archmind-lsp": "dist/lsp.cjs" }, "devDependencies": { - "@kidkender/archmind-analysis": "*", "@kidkender/archmind-laravel-parser": "*", "@kidkender/archmind-nestjs-parser": "*", "@kidkender/archmind-protocol": "*", diff --git a/packages/lsp/package.json b/packages/lsp/package.json index 8d47d4b..09333b5 100644 --- a/packages/lsp/package.json +++ b/packages/lsp/package.json @@ -11,6 +11,7 @@ "dev": "node --loader ts-node/esm src/server.ts" }, "dependencies": { + "@kidkender/archmind-analysis": "^0.3.0", "tree-sitter": "^0.21.0", "tree-sitter-php": "^0.23.0", "tree-sitter-java": "^0.23.0", @@ -20,7 +21,6 @@ "@kidkender/archmind-laravel-parser": "*", "@kidkender/archmind-nestjs-parser": "*", "@kidkender/archmind-protocol": "*", - "@kidkender/archmind-analysis": "*", "@types/node": "^20.0.0", "esbuild": "^0.28.0", "typescript": "^5.4.0",