@yagyeshvyas/vibeguard 1.3.0 → 1.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.vibeguard-mcp.example.json +51 -0
- package/CHANGELOG.md +604 -216
- package/MCP-FIREWALL.md +296 -0
- package/README.md +355 -31
- package/bin/cli.js +355 -27
- package/bin/cmd-agent-monitor.js +45 -0
- package/bin/cmd-agent-risk.js +64 -0
- package/bin/cmd-gif.js +62 -0
- package/bin/cmd-git-scan.js +74 -0
- package/bin/cmd-llm-proxy.js +164 -0
- package/bin/cmd-mcp-firewall.js +191 -0
- package/bin/cmd-pentest.js +103 -0
- package/bin/cmd-platform.js +137 -0
- package/bin/cmd-pr-scan.js +135 -0
- package/bin/cmd-sbom-diff.js +38 -0
- package/bin/cmd-skill-scan.js +35 -0
- package/docs/AISVS.md +25 -0
- package/docs/ARCHITECTURE.md +81 -0
- package/docs/INSTALLATION.md +139 -0
- package/docs/WINDOWS.md +74 -0
- package/docs/security-policy.strict.example.json +134 -0
- package/docs/security-policy.strict.example.pub.pem +3 -0
- package/package.json +45 -7
- package/src/.vibeguard/cache/file-hashes.json +60 -0
- package/src/.vibeguard/latest-snapshot.json +36 -0
- package/src/.vibeguard/mcp-pins.json +1 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +279 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +151 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +299 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +65 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +2051 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +168 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +362 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +150 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +1611 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +164 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +292 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +144 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +220 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +299 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +37 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +2055 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +168 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +362 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +220 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +279 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +151 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +299 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +65 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +2055 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +168 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +362 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +150 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +1611 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +164 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +292 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +144 -0
- package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +220 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +279 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +151 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +299 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +65 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +2054 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +168 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +362 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +150 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +1611 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +164 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +292 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +144 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +220 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +299 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +37 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +2055 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +168 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +362 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +220 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +428 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +344 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +297 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +33 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +2055 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +1611 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +292 -0
- package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +220 -0
- package/src/.vibeguard-baseline.json +5226 -0
- package/src/action-guard.js +84 -6
- package/src/agent-monitor.js +262 -0
- package/src/agent-policy.js +642 -0
- package/src/agent-risk.js +271 -0
- package/src/agentic.js +1513 -0
- package/src/ast.js +165 -7
- package/src/audit-trail.js +212 -67
- package/src/auto.js +427 -427
- package/src/autofix.js +11 -4
- package/src/bundles.js +198 -0
- package/src/daemon.js +343 -343
- package/src/dashboard.js +278 -278
- package/src/engine.js +3 -0
- package/src/entropy.js +187 -0
- package/src/firewall.js +19 -3
- package/src/gif.js +134 -0
- package/src/gitscan.js +282 -0
- package/src/hook.js +151 -151
- package/src/injection-decode.js +136 -0
- package/src/install.js +298 -280
- package/src/integrity.js +16 -1
- package/src/integrity.json +43 -13
- package/src/interceptor.js +12 -9
- package/src/llm-proxy.js +986 -0
- package/src/mcp-audit.js +61 -5
- package/src/mcp-firewall.js +971 -0
- package/src/mcp-server.js +2500 -2047
- package/src/obfuscation.js +315 -0
- package/src/owasp-agentic.js +314 -0
- package/src/pentest.js +589 -0
- package/src/pii.js +4 -0
- package/src/platform/aisvs.js +38 -0
- package/src/platform/approval.js +187 -0
- package/src/platform/canonical.js +73 -0
- package/src/platform/contracts.js +158 -0
- package/src/platform/delegation.js +73 -0
- package/src/platform/http-gateway.js +177 -0
- package/src/platform/identity.js +253 -0
- package/src/platform/jwt.js +86 -0
- package/src/platform/mcp-http-bridge.js +199 -0
- package/src/platform/memory-guard.js +64 -0
- package/src/platform/os-sandbox.js +144 -0
- package/src/platform/policy.js +332 -0
- package/src/platform/sandbox-manager.js +92 -0
- package/src/platform/signed-audit.js +357 -0
- package/src/platform/ssrf.js +129 -0
- package/src/plugin.js +182 -168
- package/src/pre-deploy.js +170 -55
- package/src/privacy-audit.js +272 -272
- package/src/repl.js +150 -150
- package/src/report.js +7 -1
- package/src/routes.js +1210 -0
- package/src/rules-2026.js +1407 -0
- package/src/rules-pack.js +3068 -3019
- package/src/rules.js +376 -60
- package/src/sandbox.js +200 -10
- package/src/sbom.js +193 -164
- package/src/scanner.js +189 -33
- package/src/shell-guard.js +11 -0
- package/src/skill-scan.js +477 -0
- package/src/slopsquat.js +144 -144
- package/src/surface.js +408 -0
- package/src/taint-ast.js +204 -37
- package/src/taint.js +15 -3
- package/src/tokenlean.js +579 -0
- package/src/trace.js +220 -220
package/src/routes.js
ADDED
|
@@ -0,0 +1,1210 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Framework-aware entrypoint extraction.
|
|
5
|
+
*
|
|
6
|
+
* A scanner that only greps for sinks cannot tell an attacker-reachable bug from
|
|
7
|
+
* dead code, and cannot answer the only question that matters at review time:
|
|
8
|
+
* "which HTTP endpoint / RPC / server action can be abused, and is it guarded?"
|
|
9
|
+
*
|
|
10
|
+
* This module turns a project into a list of ENTRYPOINTS (every place an
|
|
11
|
+
* untrusted caller can enter the program) with the facts needed to grade it:
|
|
12
|
+
* - the handler's extent in the file (line window, derived by brace matching)
|
|
13
|
+
* - the auth guards actually executed in that window (or inherited from a
|
|
14
|
+
* router mount / decorator / middleware chain)
|
|
15
|
+
* - whether it mutates state, reads an object id, and whether it filters by an
|
|
16
|
+
* owner/tenant column (the IDOR signal)
|
|
17
|
+
*
|
|
18
|
+
* Zero dependencies, text-based: runs even when acorn is unavailable. The AST
|
|
19
|
+
* pass is precision on top, not a prerequisite. Frameworks are detected by file
|
|
20
|
+
* convention first (Next.js, Supabase edge, pages/api), then by call shape
|
|
21
|
+
* (Express, Fastify, Hono, tRPC, FastAPI/Flask, Gin/Echo, Rails).
|
|
22
|
+
*
|
|
23
|
+
* Output is consumed by src/surface.js (risk merge with scanner findings) and by
|
|
24
|
+
* `vibeguard attack-surface`.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const path = require('path');
|
|
28
|
+
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Guard vocabulary — calls that prove an identity check ran inside the handler.
|
|
31
|
+
// Deliberately narrow: a guard must be CALLED, not imported, in the body window.
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
const GUARD_RE = new RegExp(
|
|
34
|
+
[
|
|
35
|
+
'\\bauth\\s*\\(', // NextAuth / Auth.js
|
|
36
|
+
'\\bgetServerSession\\s*\\(',
|
|
37
|
+
'\\bgetSession\\s*\\(',
|
|
38
|
+
'\\bgetUser\\s*\\(', // supabase.auth.getUser()
|
|
39
|
+
'\\brequireUser\\b', '\\brequireAuth\\b', '\\brequireLogin\\b',
|
|
40
|
+
'\\brequireSession\\b', '\\brequireRole\\b', '\\brequirePermission\\b',
|
|
41
|
+
'\\bwithAuth\\b', '\\bwithApiAuthRequired\\b', '\\bwithPageAuthRequired\\b',
|
|
42
|
+
'\\bcurrentUser\\s*\\(', '\\bclerkMiddleware\\b', '\\bprotect\\s*\\(',
|
|
43
|
+
'\\bensureAuth\\b', '\\bensureAuthenticated\\b', '\\bassertAuth\\b',
|
|
44
|
+
'\\bassertAuthenticated\\b', '\\bcheckAuth\\b', '\\bcheckPermission\\b',
|
|
45
|
+
'\\bisAuthenticated\\b', '\\bisLoggedIn\\b', '\\bisLoggedInMiddleware\\b',
|
|
46
|
+
'\\bensureLoggedIn\\b', '\\brequireLoggedIn\\b', '\\bisAdmin\\b',
|
|
47
|
+
'\\bisAdminUserMiddleware\\b', '\\bcheckSession\\b', '\\bhasPermission\\b',
|
|
48
|
+
'\\bauthenticate\\b', '\\bauthorize\\b',
|
|
49
|
+
'\\bverifyToken\\b', '\\bverifyJwt\\b', '\\bverifyJWT\\b', '\\bjwt\\.verify\\b',
|
|
50
|
+
'\\bgetToken\\b', '\\bgetAuth\\s*\\(', '\\bvalidateSession\\b',
|
|
51
|
+
'\\bverifySession\\b', '\\bgetCurrentUser\\b', '\\bgetLoggedInUser\\b',
|
|
52
|
+
'\\bhasRole\\b', '\\bcan\\s*\\(', '\\bability\\.can\\b',
|
|
53
|
+
'\\bisAuthorized\\b', '\\bdenyAll\\b', '\\bisAdminUser\\b',
|
|
54
|
+
'\\bblockUnauthorized\\b', '\\brequireValidToken\\b',
|
|
55
|
+
'\\bDepends\\s*\\(\\s*get_current_user', '\\bbefore_action\\b.*authenticate',
|
|
56
|
+
].join('|')
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
// Calls that prove the OPPOSITE: the route is explicitly public.
|
|
60
|
+
const PUBLIC_RE = /\bpublicProcedure\b|\bpublicRoute\b|\ballowAnonymous\b|\bskipAuth\b/;
|
|
61
|
+
|
|
62
|
+
// Data-mutating work.
|
|
63
|
+
const WRITE_RE = new RegExp(
|
|
64
|
+
[
|
|
65
|
+
'\\.(?:create|createMany|update|updateMany|upsert|delete|deleteMany|save|insert|insertOne|insertMany|destroy|bulkCreate|findOneAndUpdate|findOneAndDelete|findByIdAndUpdate|findByIdAndDelete)\\s*\\(',
|
|
66
|
+
'\\bsave\\s*\\(\\s*\\)',
|
|
67
|
+
'\\.(?:set|increment|decrement|push|splice)\\s*\\(', // doc/array mutation on a loaded record
|
|
68
|
+
'\\bwriteFile(?:Sync)?\\s*\\(', '\\bappendFile(?:Sync)?\\s*\\(', '\\bunlink(?:Sync)?\\s*\\(',
|
|
69
|
+
'\\brm(?:Sync)?\\s*\\(', '\\bmkdir(?:Sync)?\\s*\\(',
|
|
70
|
+
'\\bexec(?:Sync)?\\s*\\(', '\\bspawn(?:Sync)?\\s*\\(',
|
|
71
|
+
'\\bfetch\\s*\\(', '\\baxios\\.(?:post|put|patch|delete)\\b',
|
|
72
|
+
'\\b(?:insert\\s+into|update\\s+\\w+\\s+set|delete\\s+from|drop\\s+table|alter\\s+table)\\b',
|
|
73
|
+
'\\bbenchmark\\.invoke\\b', '\\bqueue\\.add\\b', '\\bsendMail\\b', '\\bsendEmail\\b',
|
|
74
|
+
].join('|'),
|
|
75
|
+
'i'
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
// Reads of an object identifier straight from the request.
|
|
79
|
+
const ID_PARAM_RE = new RegExp(
|
|
80
|
+
[
|
|
81
|
+
'\\bparams\\s*\\.\\s*(id|uuid|slug|key|token|userId|user_id)\\b',
|
|
82
|
+
'\\bparams\\s*\\[\\s*[\'"](id|uuid|slug|key|token|userId|user_id)[\'"]\\s*\\]',
|
|
83
|
+
'\\breq\\.params\\.(id|uuid|slug|key|token|userId|user_id)\\b',
|
|
84
|
+
'\\bsearchParams\\.get\\(\\s*[\'"](id|uuid|slug|key|token|userId|user_id)[\'"]\\s*\\)',
|
|
85
|
+
'\\bquery\\.(id|uuid|slug|key|token|userId|user_id)\\b',
|
|
86
|
+
'\\breq\\.query\\.(id|uuid|slug|key|token|userId|user_id)\\b',
|
|
87
|
+
'\\brequest\\.query\\.(id|uuid|slug|key|token|userId|user_id)\\b',
|
|
88
|
+
'\\bc\\.req\\.param\\(\\s*[\'"](id|uuid|slug|key|token)[\'"]\\s*\\)',
|
|
89
|
+
'\\bctx\\.params\\.(id|uuid|slug|key|token)\\b',
|
|
90
|
+
'\\{\\s*(id|uuid|slug|key|token|userId|user_id)\\s*\\}[\\s\\S]{0,30}?=\\s*req\\.params',
|
|
91
|
+
'\\bfrom\\s+[\\w.]+\\s+where\\s+id\\s*=\\s*\\$?\\d',
|
|
92
|
+
].join('|'),
|
|
93
|
+
'i'
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
// An ownership / tenant predicate near the object fetch.
|
|
97
|
+
const OWNER_RE = new RegExp(
|
|
98
|
+
[
|
|
99
|
+
'\\b(userId|user_id|ownerId|owner_id|tenantId|tenant_id|orgId|org_id|accountId|account_id|authorId|author_id|workspaceId|workspace_id|customerId|customer_id|teamId|team_id)\\b',
|
|
100
|
+
'\\bauth\\.uid\\(\\)', '\\bcurrentUser\\(\\)\\.id', '\\bsession\\.user\\.id',
|
|
101
|
+
'\\bctx\\.user\\.(?:id|userId)', '\\breq\\.user\\.(?:id|userId)',
|
|
102
|
+
].join('|')
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
// Rate-limit presence (login/chat/OTP endpoints without it are brute-forceable).
|
|
106
|
+
const RATELIMIT_RE = /\b(?:rateLimit|rateLimiter|rate_limit|ratelimit|limiter|throttle|express-rate-limit|upstash\/ratelimit|slowDown)\b/i;
|
|
107
|
+
|
|
108
|
+
const ENTRYPOINT_FILE_RULES = [
|
|
109
|
+
{ re: /(?:^|\/)app\/.*\/route\.(?:js|jsx|ts|tsx|mjs)$/, framework: 'next-app' },
|
|
110
|
+
{ re: /(?:^|\/)pages\/api\/.*\.(?:js|jsx|ts|tsx)$/, framework: 'next-pages' },
|
|
111
|
+
{ re: /(?:^|\/)middleware\.(?:js|ts)$/, framework: 'next-middleware' },
|
|
112
|
+
{ re: /(?:^|\/)supabase\/functions\/[^/]+\/(?:index|main)\.(?:ts|js)$/, framework: 'supabase-edge' },
|
|
113
|
+
{ re: /(?:^|\/)netlify\/functions\/.*\.(?:js|ts)$/, framework: 'netlify' },
|
|
114
|
+
// Serverless: only a real api/ or vercel api/ directory — not test folders.
|
|
115
|
+
{ re: /(?:^|\/)(?:src\/)?api\/[^/]+\.(?:js|ts)$/, framework: 'serverless' },
|
|
116
|
+
];
|
|
117
|
+
|
|
118
|
+
function frameworkOfFile(rel) {
|
|
119
|
+
const p = String(rel || '').replace(/\\/g, '/');
|
|
120
|
+
if (isFixtureLike(p)) return null;
|
|
121
|
+
for (const r of ENTRYPOINT_FILE_RULES) {
|
|
122
|
+
if (r.re.test(p)) return r.framework;
|
|
123
|
+
}
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ---------------------------------------------------------------------------
|
|
128
|
+
// Body windowing
|
|
129
|
+
// ---------------------------------------------------------------------------
|
|
130
|
+
|
|
131
|
+
// Find the line index (0-based) where the `{` opening a block that starts at or
|
|
132
|
+
// after `startIdx` opens, then return the matching close line by counting braces
|
|
133
|
+
// while skipping strings/template literals/comments. Falls back to a bounded
|
|
134
|
+
// window when braces are unbalanced (JSX, broken code).
|
|
135
|
+
function braceWindow(lines, startIdx, maxLines = 200) {
|
|
136
|
+
let depth = 0;
|
|
137
|
+
let opened = false;
|
|
138
|
+
let start = startIdx;
|
|
139
|
+
let end = Math.min(lines.length - 1, startIdx + 40);
|
|
140
|
+
let inBlockComment = false;
|
|
141
|
+
|
|
142
|
+
for (let i = startIdx; i < lines.length && i <= startIdx + maxLines; i++) {
|
|
143
|
+
const line = lines[i];
|
|
144
|
+
let quote = null;
|
|
145
|
+
for (let j = 0; j < line.length; j++) {
|
|
146
|
+
const ch = line[j];
|
|
147
|
+
const nx = line[j + 1];
|
|
148
|
+
if (inBlockComment) {
|
|
149
|
+
if (ch === '*' && nx === '/') { inBlockComment = false; j++; }
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (quote) {
|
|
153
|
+
if (ch === '\\') { j++; continue; }
|
|
154
|
+
if (ch === quote) quote = null;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (ch === '/' && nx === '/') break; // line comment
|
|
158
|
+
if (ch === '/' && nx === '*') { inBlockComment = true; j++; continue; }
|
|
159
|
+
if (ch === "'" || ch === '"' || ch === '`') { quote = ch; continue; }
|
|
160
|
+
if (ch === '{') { depth++; opened = true; }
|
|
161
|
+
else if (ch === '}') {
|
|
162
|
+
depth--;
|
|
163
|
+
if (opened && depth === 0) { end = i; i = lines.length; break; }
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
if (opened && depth === 0) { end = i; break; }
|
|
167
|
+
}
|
|
168
|
+
if (!opened) end = startIdx; // one-liner handler: the registration line IS the body
|
|
169
|
+
return { start, end };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function bodyText(lines, start, end) {
|
|
173
|
+
return lines.slice(start, end + 1).join('\n');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Does the query that reads the request id also constrain an owner/tenant column
|
|
177
|
+
// with the CALLER's identity? The identity reference is required — a bare
|
|
178
|
+
// `userId` identifier is usually the request parameter itself, not a filter.
|
|
179
|
+
const CALLER_IDENTITY_RE =
|
|
180
|
+
/req\.user\b|req\.session|res\.locals|auth\.uid\(\)|session\.user|user\.id\b|ctx\.user|currentUser\(|getServerSession|getSession\(|jwt\.verify|verifyToken/i;
|
|
181
|
+
const OWNER_COLUMN_RE =
|
|
182
|
+
/(userId|user_id|ownerId|owner_id|tenantId|tenant_id|orgId|org_id|accountId|account_id|authorId|author_id|workspaceId|teamId|customerId|profileId)/i;
|
|
183
|
+
|
|
184
|
+
function ownerCheck(lines, start, end, idMatchLine) {
|
|
185
|
+
// Strip comments across the WHOLE window first — a multi-line comment can
|
|
186
|
+
// start before the id line and end after it, so line-local stripping lies.
|
|
187
|
+
const cleaned = stripComments(lines.slice(start, end + 1).join('\n')).split('\n');
|
|
188
|
+
const idRel = Math.max(0, Math.min(cleaned.length - 1, idMatchLine - start));
|
|
189
|
+
for (let i = Math.max(0, idRel - 4); i <= Math.min(cleaned.length - 1, idRel + 4); i++) {
|
|
190
|
+
const window = cleaned.slice(i, i + 3).join('\n');
|
|
191
|
+
if (OWNER_COLUMN_RE.test(window) && CALLER_IDENTITY_RE.test(window)) return true;
|
|
192
|
+
}
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ---------------------------------------------------------------------------
|
|
197
|
+
// Auth inference
|
|
198
|
+
// ---------------------------------------------------------------------------
|
|
199
|
+
|
|
200
|
+
function guardsIn(text, callsOnly) {
|
|
201
|
+
const out = [];
|
|
202
|
+
const re = new RegExp(GUARD_RE.source, 'g');
|
|
203
|
+
let m;
|
|
204
|
+
while ((m = re.exec(text)) !== null) {
|
|
205
|
+
if (callsOnly) {
|
|
206
|
+
const after = text.slice(m.index + m[0].length, m.index + m[0].length + 3);
|
|
207
|
+
if (!/^\s*\(/.test(after)) continue; // `user.isAdmin ? …` is not a guard call
|
|
208
|
+
}
|
|
209
|
+
out.push(m[0].replace(/\(.*$/, '').trim());
|
|
210
|
+
if (out.length > 40) break;
|
|
211
|
+
}
|
|
212
|
+
return [...new Set(out)];
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Strip comments before trust decisions — a commented-out guard is not a guard.
|
|
216
|
+
function stripComments(text) {
|
|
217
|
+
return text
|
|
218
|
+
.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
219
|
+
.replace(/(^|[^:])\/\/[^\n]*/g, '$1')
|
|
220
|
+
.replace(/(^|\s)#[^\n]*/g, '$1');
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Common auth middleware names used in mount chains: router.use(requireAuth).
|
|
224
|
+
const MOUNT_AUTH_RE = new RegExp(GUARD_RE.source, 'i');
|
|
225
|
+
|
|
226
|
+
// ---------------------------------------------------------------------------
|
|
227
|
+
// Per-framework extractors
|
|
228
|
+
// ---------------------------------------------------------------------------
|
|
229
|
+
|
|
230
|
+
const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];
|
|
231
|
+
|
|
232
|
+
// folder path -> route path for Next App Router.
|
|
233
|
+
function nextAppPath(rel) {
|
|
234
|
+
const idx = rel.lastIndexOf('/app/');
|
|
235
|
+
const tail = idx >= 0 ? rel.slice(idx + 5) : rel.replace(/^app\//, '');
|
|
236
|
+
const parts = tail.split('/').slice(0, -1); // drop route.ts
|
|
237
|
+
const segs = [];
|
|
238
|
+
for (const p of parts) {
|
|
239
|
+
if (/^\(.*\)$/.test(p)) continue; // route group
|
|
240
|
+
if (/^@/.test(p)) continue; // parallel route slot
|
|
241
|
+
if (p === 'page' || p === 'layout') continue;
|
|
242
|
+
segs.push(p.replace(/^\[\[?(\.\.\.)?([^\]]+)\]\]?$/, (_, rest, name) => (rest ? '*' : ':' + name)));
|
|
243
|
+
}
|
|
244
|
+
return '/' + segs.join('/');
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function extractNextApp(file, out) {
|
|
248
|
+
const { rel, content, lines } = file;
|
|
249
|
+
const routePath = nextAppPath(rel);
|
|
250
|
+
const base = path.basename(rel);
|
|
251
|
+
if (base === 'middleware.ts' || base === 'middleware.js') return;
|
|
252
|
+
|
|
253
|
+
// Exported route handlers: export (async) function GET(...) / export const GET = ...
|
|
254
|
+
const fnRe = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\s*\(/g;
|
|
255
|
+
const constRe = /\bexport\s+const\s+(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\s*=/g;
|
|
256
|
+
const hits = [];
|
|
257
|
+
let m;
|
|
258
|
+
while ((m = fnRe.exec(content)) !== null) hits.push({ method: m[1], index: m.index });
|
|
259
|
+
while ((m = constRe.exec(content)) !== null) hits.push({ method: m[1], index: m.index });
|
|
260
|
+
for (const h of hits) {
|
|
261
|
+
const line = content.slice(0, h.index).split('\n').length - 1;
|
|
262
|
+
const { start, end } = braceWindow(lines, line);
|
|
263
|
+
out.push(finishEntrypoint(file, {
|
|
264
|
+
kind: 'http', framework: 'next-app', method: h.method, path: routePath,
|
|
265
|
+
line: line + 1, start, end,
|
|
266
|
+
}));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function extractNextPages(file, out, expressLike) {
|
|
271
|
+
const { rel, content, lines } = file;
|
|
272
|
+
const routePath = (() => {
|
|
273
|
+
const idx = rel.lastIndexOf('/pages/api');
|
|
274
|
+
let tail = idx >= 0 ? rel.slice(idx + 10) : rel;
|
|
275
|
+
tail = tail.replace(/\.(?:js|jsx|ts|tsx)$/, '');
|
|
276
|
+
if (tail.endsWith('/index')) tail = tail.slice(0, -6);
|
|
277
|
+
tail = tail.replace(/\[\[?\.\.\.([^\]]+)\]\]?/g, '*').replace(/\[([^\]]+)\]/g, ':$1');
|
|
278
|
+
return '/api' + tail;
|
|
279
|
+
})();
|
|
280
|
+
|
|
281
|
+
const def = /\bexport\s+default\s+(?:async\s+)?(?:function\s*\w*\s*\(|\([^)]*\)\s*=>|\w+\s*=>|\w+\b)/.exec(content);
|
|
282
|
+
let line = def ? content.slice(0, def.index).split('\n').length - 1 : 0;
|
|
283
|
+
let { start, end } = def ? braceWindow(lines, line) : { start: 0, end: lines.length - 1 };
|
|
284
|
+
const body = bodyText(lines, start, end);
|
|
285
|
+
const methods = [];
|
|
286
|
+
const methodSwitch = /\breq(?:uest)?\.method\s*===?\s*['"](GET|POST|PUT|PATCH|DELETE)['"]/g;
|
|
287
|
+
let mm;
|
|
288
|
+
while ((mm = methodSwitch.exec(body)) !== null) methods.push(mm[1]);
|
|
289
|
+
if (methods.length === 0) methods.push('*');
|
|
290
|
+
for (const method of methods) {
|
|
291
|
+
out.push(finishEntrypoint(file, {
|
|
292
|
+
kind: 'http', framework: 'next-pages', method, path: routePath,
|
|
293
|
+
line: line + 1, start, end,
|
|
294
|
+
}));
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function extractExpressLike(file, out, matches) {
|
|
299
|
+
const { rel, lines } = file;
|
|
300
|
+
for (const h of matches) {
|
|
301
|
+
const { start, end } = braceWindow(lines, h.line);
|
|
302
|
+
out.push(finishEntrypoint(file, {
|
|
303
|
+
kind: 'http', framework: h.framework, method: h.method, path: h.path,
|
|
304
|
+
line: h.line + 1, start, end,
|
|
305
|
+
}));
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Server Actions: a 'use server' file makes every exported async function a
|
|
310
|
+
// remotely-callable endpoint. This is the most under-scanned attack surface in
|
|
311
|
+
// Next.js apps because nothing in the file looks like a route.
|
|
312
|
+
function extractServerActions(file, out) {
|
|
313
|
+
const { content, lines } = file;
|
|
314
|
+
if (!/['"]use server['"]/.test(content)) return;
|
|
315
|
+
const re = /\bexport\s+(?:async\s+)?function\s+(\w+)\s*\(/g;
|
|
316
|
+
let m;
|
|
317
|
+
while ((m = re.exec(content)) !== null) {
|
|
318
|
+
if (insideString(content, m.index) || !plausibleStart(content, m.index)) continue;
|
|
319
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
320
|
+
const { start, end } = braceWindow(lines, line);
|
|
321
|
+
out.push(finishEntrypoint(file, {
|
|
322
|
+
kind: 'server-action', framework: 'next-app', method: 'ACTION', path: m[1],
|
|
323
|
+
line: line + 1, start, end,
|
|
324
|
+
}));
|
|
325
|
+
}
|
|
326
|
+
// export const action = async (…) => …
|
|
327
|
+
const cre = /\bexport\s+const\s+(\w+)\s*=\s*async\b/g;
|
|
328
|
+
while ((m = cre.exec(content)) !== null) {
|
|
329
|
+
if (insideString(content, m.index) || !plausibleStart(content, m.index)) continue;
|
|
330
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
331
|
+
const { start, end } = braceWindow(lines, line);
|
|
332
|
+
out.push(finishEntrypoint(file, {
|
|
333
|
+
kind: 'server-action', framework: 'next-app', method: 'ACTION', path: m[1],
|
|
334
|
+
line: line + 1, start, end,
|
|
335
|
+
}));
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function extractTrpc(file, out) {
|
|
340
|
+
const { content, lines } = file;
|
|
341
|
+
if (!/(?:createTRPCRouter|\bt\.router|initTRPC|(?:public|protected|private)Procedure\s*[.(])/.test(content)) return;
|
|
342
|
+
// procedure entries: name: publicProcedure.protectedProcedure.query|mutation
|
|
343
|
+
const re = /(\w+)\s*:\s*(public|protected|private)Procedure\b([\s\S]{0,200}?)\.(query|mutation)\s*\(/g;
|
|
344
|
+
let m;
|
|
345
|
+
while ((m = re.exec(content)) !== null) {
|
|
346
|
+
if (insideString(content, m.index) || !plausibleStart(content, m.index)) continue;
|
|
347
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
348
|
+
const { start, end } = braceWindow(lines, line);
|
|
349
|
+
out.push(finishEntrypoint(file, {
|
|
350
|
+
kind: 'trpc', framework: 'trpc', method: m[4] === 'mutation' ? 'MUTATION' : 'QUERY',
|
|
351
|
+
path: m[1], line: line + 1, start, end,
|
|
352
|
+
explicitAuth: m[2] === 'public' ? 'none' : 'enforced',
|
|
353
|
+
}));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function extractFastify(file, out) {
|
|
358
|
+
const { content, lines } = file;
|
|
359
|
+
const re = /\b(?:fastify|app|server|router)\.(get|post|put|patch|delete|options|head)\s*\(\s*['"`]([^'"`]+)['"`]/g;
|
|
360
|
+
let m;
|
|
361
|
+
while ((m = re.exec(content)) !== null) {
|
|
362
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
363
|
+
const { start, end } = braceWindow(lines, line);
|
|
364
|
+
out.push(finishEntrypoint(file, {
|
|
365
|
+
kind: 'http', framework: 'fastify', method: m[1].toUpperCase(), path: m[2],
|
|
366
|
+
line: line + 1, start, end,
|
|
367
|
+
}));
|
|
368
|
+
}
|
|
369
|
+
const routeRe = /\b(?:fastify|app|server)\.route\s*\(\s*\{([\s\S]{0,600}?)\}\s*\)/g;
|
|
370
|
+
while ((m = routeRe.exec(content)) !== null) {
|
|
371
|
+
const block = m[1];
|
|
372
|
+
const url = /url\s*:\s*['"`]([^'"`]+)['"`]/.exec(block);
|
|
373
|
+
const method = /method\s*:\s*['"`]([A-Za-z]+)['"`]/.exec(block);
|
|
374
|
+
if (!url) continue;
|
|
375
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
376
|
+
const { start, end } = braceWindow(lines, line);
|
|
377
|
+
out.push(finishEntrypoint(file, {
|
|
378
|
+
kind: 'http', framework: 'fastify', method: (method ? method[1] : 'GET').toUpperCase(),
|
|
379
|
+
path: url[1], line: line + 1, start, end,
|
|
380
|
+
}));
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function extractHono(file, out) {
|
|
385
|
+
const { content, lines } = file;
|
|
386
|
+
if (!/\b(?:hono|app|router)\b/.test(content)) return;
|
|
387
|
+
const re = /\b(?:app|router|api)\.(get|post|put|patch|delete|all|on)\s*\(\s*['"`]([^'"`]+)['"`]/g;
|
|
388
|
+
let m;
|
|
389
|
+
while ((m = re.exec(content)) !== null) {
|
|
390
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
391
|
+
const { start, end } = braceWindow(lines, line);
|
|
392
|
+
out.push(finishEntrypoint(file, {
|
|
393
|
+
kind: 'http', framework: 'hono', method: m[1] === 'all' || m[1] === 'on' ? '*' : m[1].toUpperCase(),
|
|
394
|
+
path: m[2], line: line + 1, start, end,
|
|
395
|
+
}));
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function extractNest(file, out) {
|
|
400
|
+
const { content, lines } = file;
|
|
401
|
+
if (!/\.(?:ts|js)$/i.test(file.rel)) return;
|
|
402
|
+
const ctrl = /@Controller\s*\(\s*['"`]?([^'"`)]*)['"`]?\s*\)/.exec(content);
|
|
403
|
+
if (!ctrl) return;
|
|
404
|
+
const base = '/' + String(ctrl[1]).replace(/^\/+/, '');
|
|
405
|
+
const clsGuard = /@UseGuards\s*\(([^)]*)\)/.exec(content);
|
|
406
|
+
const re = /@(Get|Post|Put|Patch|Delete)\s*\(\s*(?:['"`]([^'"`]*)['"`])?\s*\)/g;
|
|
407
|
+
let m;
|
|
408
|
+
while ((m = re.exec(content)) !== null) {
|
|
409
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
410
|
+
const { start, end } = braceWindow(lines, line);
|
|
411
|
+
out.push(finishEntrypoint(file, {
|
|
412
|
+
kind: 'http', framework: 'nestjs', method: m[1].toUpperCase(),
|
|
413
|
+
path: (base + '/' + (m[2] || '')).replace(/\/+$/, '') || '/',
|
|
414
|
+
line: line + 1, start, end,
|
|
415
|
+
classGuard: clsGuard ? clsGuard[1].trim() : null,
|
|
416
|
+
}));
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function extractPy(file, out) {
|
|
421
|
+
const { content, lines } = file;
|
|
422
|
+
if (!/\.py$/i.test(file.rel)) return; // Python route syntax appears in JS example strings
|
|
423
|
+
const frameworks = [
|
|
424
|
+
{ re: /@(?:app|router|api)\.(get|post|put|patch|delete)\s*\(\s*['"]([^'"]+)['"]/g, framework: 'fastapi' },
|
|
425
|
+
{ re: /@(?:app|bp|blueprint)\.route\s*\(\s*['"]([^'"]+)['"](?:\s*,\s*methods\s*=\s*\[([^\]]*)\])?/g, framework: 'flask' },
|
|
426
|
+
];
|
|
427
|
+
for (const fw of frameworks) {
|
|
428
|
+
let m;
|
|
429
|
+
fw.re.lastIndex = 0;
|
|
430
|
+
while ((m = fw.re.exec(content)) !== null) {
|
|
431
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
432
|
+
// Python body = following indented lines.
|
|
433
|
+
let end = line;
|
|
434
|
+
const indent = (lines[line + 1] || '').match(/^(\s*)/)[1].length;
|
|
435
|
+
for (let i = line + 1; i < lines.length; i++) {
|
|
436
|
+
const l = lines[i];
|
|
437
|
+
if (l.trim() === '') { end = i; continue; }
|
|
438
|
+
const ind = l.match(/^(\s*)/)[1].length;
|
|
439
|
+
if (ind <= indent) break;
|
|
440
|
+
end = i;
|
|
441
|
+
}
|
|
442
|
+
const methods = m[2]
|
|
443
|
+
? m[2].split(',').map((s) => s.trim().replace(/['"]/g, '').toUpperCase()).filter(Boolean)
|
|
444
|
+
: [fw.framework === 'flask' ? 'GET' : (m[1] || 'GET').toUpperCase()];
|
|
445
|
+
for (const method of methods) {
|
|
446
|
+
out.push(finishEntrypoint(file, {
|
|
447
|
+
kind: 'http', framework: fw.framework, method,
|
|
448
|
+
path: m[2] !== undefined || fw.framework === 'fastapi' ? m[1] : m[1],
|
|
449
|
+
line: line + 1, start: line, end,
|
|
450
|
+
}));
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
// Django urlpatterns: path('users/<int:pk>/', view)
|
|
455
|
+
const dj = /\bpath\s*\(\s*['"]([^'"]+)['"]\s*,\s*([\w.]+)/g;
|
|
456
|
+
let m;
|
|
457
|
+
while ((m = dj.exec(content)) !== null) {
|
|
458
|
+
if (insideString(content, m.index)) continue;
|
|
459
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
460
|
+
out.push(finishEntrypoint(file, {
|
|
461
|
+
kind: 'http', framework: 'django', method: '*',
|
|
462
|
+
path: '/' + m[1].replace(/<[^>]+>/g, (x) => (x.includes('slug') ? ':slug' : ':id')).replace(/^\/+/, ''),
|
|
463
|
+
line: line + 1, start: line, end: Math.min(lines.length - 1, line),
|
|
464
|
+
}));
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function extractGo(file, out) {
|
|
469
|
+
const { content, lines } = file;
|
|
470
|
+
if (!/\.go$/i.test(file.rel)) return;
|
|
471
|
+
const re = /\b(?:r|router|e|app|g|mux|http)\w*\.(GET|POST|PUT|PATCH|DELETE)\s*\(\s*"([^"]+)"/g;
|
|
472
|
+
let m;
|
|
473
|
+
while ((m = re.exec(content)) !== null) {
|
|
474
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
475
|
+
const { start, end } = braceWindow(lines, line);
|
|
476
|
+
out.push(finishEntrypoint(file, {
|
|
477
|
+
kind: 'http', framework: 'go', method: m[1], path: m[2], line: line + 1, start, end,
|
|
478
|
+
}));
|
|
479
|
+
}
|
|
480
|
+
const hf = /\bhttp\.HandleFunc\s*\(\s*"([^"]+)"/g;
|
|
481
|
+
while ((m = hf.exec(content)) !== null) {
|
|
482
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
483
|
+
const { start, end } = braceWindow(lines, line);
|
|
484
|
+
out.push(finishEntrypoint(file, {
|
|
485
|
+
kind: 'http', framework: 'go', method: '*', path: m[1], line: line + 1, start, end,
|
|
486
|
+
}));
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function extractSupabaseEdge(file, out) {
|
|
491
|
+
const { content, lines } = file;
|
|
492
|
+
const m = /Deno\.serve\s*\(\s*(?:async\s*)?(?:\(|function)/.exec(content);
|
|
493
|
+
if (!m) return;
|
|
494
|
+
const relParts = file.rel.split('/');
|
|
495
|
+
const idx = relParts.indexOf('functions');
|
|
496
|
+
const name = idx >= 0 ? relParts[idx + 1] : path.basename(path.dirname(file.rel));
|
|
497
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
498
|
+
const { start, end } = braceWindow(lines, line);
|
|
499
|
+
out.push(finishEntrypoint(file, {
|
|
500
|
+
kind: 'edge-function', framework: 'supabase-edge', method: '*', path: '/' + name,
|
|
501
|
+
line: line + 1, start, end,
|
|
502
|
+
}));
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function extractRails(file, out) {
|
|
506
|
+
if (!/\.rb$/i.test(file.rel)) return; // `get 'x'` would otherwise match English text in any string
|
|
507
|
+
const { content, lines } = file;
|
|
508
|
+
const re = /\b(get|post|put|patch|delete)\s+['"]([^'"]+)['"]/g;
|
|
509
|
+
let m;
|
|
510
|
+
while ((m = re.exec(content)) !== null) {
|
|
511
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
512
|
+
out.push(finishEntrypoint(file, {
|
|
513
|
+
kind: 'http', framework: 'rails', method: m[1].toUpperCase(), path: m[2],
|
|
514
|
+
line: line + 1, start: line, end: line,
|
|
515
|
+
}));
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function extractMcpTools(file, out) {
|
|
520
|
+
const { content, lines } = file;
|
|
521
|
+
const re = /\b(?:server|mcp|toolServer)\.(?:tool|registerTool)\s*\(\s*['"`]([^'"`]+)['"`]/g;
|
|
522
|
+
let m;
|
|
523
|
+
while ((m = re.exec(content)) !== null) {
|
|
524
|
+
if (insideString(content, m.index) || !plausibleStart(content, m.index)) continue;
|
|
525
|
+
const line = content.slice(0, m.index).split('\n').length - 1;
|
|
526
|
+
const { start, end } = braceWindow(lines, line);
|
|
527
|
+
out.push(finishEntrypoint(file, {
|
|
528
|
+
kind: 'mcp-tool', framework: 'mcp', method: 'TOOL', path: m[1],
|
|
529
|
+
line: line + 1, start, end,
|
|
530
|
+
}));
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
// Express routes need their line indices; collected by a scan pass so mounting
|
|
535
|
+
// can be resolved before finalizing.
|
|
536
|
+
function collectExpressRoutes(files) {
|
|
537
|
+
const routes = []; // {file, line, method, path}
|
|
538
|
+
const mounts = []; // {file, line, base, ident, middleware}
|
|
539
|
+
const imports = new Map(); // rel -> Map(ident -> rel)
|
|
540
|
+
for (const f of files) {
|
|
541
|
+
const map = new Map();
|
|
542
|
+
const reqRe = /\b(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"](\.{1,2}\/[^'"]+)['"]\s*\)/g;
|
|
543
|
+
let m;
|
|
544
|
+
while ((m = reqRe.exec(f.content)) !== null) map.set(m[1], m[2]);
|
|
545
|
+
const impRe = /\bimport\s+(\w+)\s+from\s+['"](\.{1,2}\/[^'"]+)['"]/g;
|
|
546
|
+
while ((m = impRe.exec(f.content)) !== null) map.set(m[1], m[2]);
|
|
547
|
+
imports.set(f.rel, map);
|
|
548
|
+
}
|
|
549
|
+
const resolve = (fromRel, spec) => {
|
|
550
|
+
const dir = fromRel.includes('/') ? fromRel.slice(0, fromRel.lastIndexOf('/')) : '';
|
|
551
|
+
const base = path.posix.normalize((dir + '/' + spec).replace(/^\/+/, ''));
|
|
552
|
+
const known = files.map((x) => x.rel);
|
|
553
|
+
const cands = [base, base + '.js', base + '.ts', base + '.mjs', base + '/index.js', base + '/index.ts'];
|
|
554
|
+
return cands.find((c) => known.includes(c)) || null;
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
for (const f of files) {
|
|
558
|
+
const routeRe = /\b(app|router|server|api)\.(get|post|put|patch|delete|all)\s*\(\s*['"`]([^'"`]+)['"`]\s*,/g;
|
|
559
|
+
let m;
|
|
560
|
+
while ((m = routeRe.exec(f.content)) !== null) {
|
|
561
|
+
routes.push({
|
|
562
|
+
file: f.rel,
|
|
563
|
+
line: f.content.slice(0, m.index).split('\n').length - 1,
|
|
564
|
+
method: m[2] === 'all' ? '*' : m[2].toUpperCase(),
|
|
565
|
+
path: m[3],
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
const mountRe = /\b(app|server)\.use\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*([^)]+(?:\)[^)]*)?)\)/g;
|
|
569
|
+
while ((m = mountRe.exec(f.content)) !== null) {
|
|
570
|
+
const rawArgs = m[3].trim();
|
|
571
|
+
// `require('./routes/users')` style mounts: take the specifier directly.
|
|
572
|
+
const reqSpec = /^(?:require\s*\(\s*['"]([^'"]+)['"]\s*\)|(\w+))$/.exec(rawArgs);
|
|
573
|
+
const specInline = /require\s*\(\s*['"]([^'"]+)['"]\s*\)\s*$/.exec(rawArgs);
|
|
574
|
+
mounts.push({
|
|
575
|
+
file: f.rel,
|
|
576
|
+
base: m[2],
|
|
577
|
+
spec: (specInline && specInline[1]) || (reqSpec && reqSpec[1]) || null,
|
|
578
|
+
ident: !specInline && reqSpec && reqSpec[2] ? reqSpec[2] : null,
|
|
579
|
+
middleware: rawArgs.replace(/require\s*\([^)]*\)/, '').replace(/^,|,$/g, ''),
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// Resolve mounts to router files.
|
|
585
|
+
const mountByRel = new Map(); // rel -> [{base, middleware}]
|
|
586
|
+
for (const mo of mounts) {
|
|
587
|
+
let target = null;
|
|
588
|
+
if (mo.spec) target = resolve(mo.file, mo.spec);
|
|
589
|
+
else if (mo.ident) {
|
|
590
|
+
const spec = (imports.get(mo.file) || new Map()).get(mo.ident);
|
|
591
|
+
if (spec) target = resolve(mo.file, spec);
|
|
592
|
+
}
|
|
593
|
+
if (!target) continue;
|
|
594
|
+
if (!mountByRel.has(target)) mountByRel.set(target, []);
|
|
595
|
+
mountByRel.get(target).push({ base: mo.base.replace(/\/$/, ''), middleware: mo.middleware });
|
|
596
|
+
}
|
|
597
|
+
return { routes, mountByRel, imports, resolve };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// Is the character offset inside a quoted string on this line? Prevents reading
|
|
601
|
+
// example/demo code strings (e.g. this project's own rule database) as routes.
|
|
602
|
+
function insideString(text, idx) {
|
|
603
|
+
const lineStart = text.lastIndexOf('\n', idx) + 1;
|
|
604
|
+
const lineEnd = text.indexOf('\n', idx);
|
|
605
|
+
const line = text.slice(lineStart, lineEnd === -1 ? undefined : lineEnd);
|
|
606
|
+
const rel = idx - lineStart;
|
|
607
|
+
let quote = null;
|
|
608
|
+
for (let i = 0; i < rel && i < line.length; i++) {
|
|
609
|
+
const ch = line[i];
|
|
610
|
+
if (quote) {
|
|
611
|
+
if (ch === '\\') i++;
|
|
612
|
+
else if (ch === quote) quote = null;
|
|
613
|
+
} else if (ch === "'" || ch === '"' || ch === '`') {
|
|
614
|
+
quote = ch;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return quote !== null;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// Is the match at a plausible statement boundary? Rejects hits inside regex
|
|
621
|
+
// literals and escaped example text (`/\bapp\.post\(.../`) while accepting real
|
|
622
|
+
// calls after a newline, `;`, `{`, `}`, `,`, `(` or `)`.
|
|
623
|
+
function plausibleStart(text, idx) {
|
|
624
|
+
let i = idx - 1;
|
|
625
|
+
while (i >= 0 && (text[i] === ' ' || text[i] === '\t' || text[i] === '\r')) i--;
|
|
626
|
+
if (i < 0) return true;
|
|
627
|
+
return ['\n', ';', '{', '}', ',', '(', ')'].includes(text[i]);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// ---------------------------------------------------------------------------
|
|
631
|
+
// Handler resolution (Express-style: the route is registered by reference)
|
|
632
|
+
// ---------------------------------------------------------------------------
|
|
633
|
+
|
|
634
|
+
const TEST_FILE = /(?:^|\/)(?:test|tests|__tests__|__mocks__|spec|specs|e2e|apitest|fixtures)\//i;
|
|
635
|
+
const TEST_NAME = /\.(?:test|spec|e2e)\.(?:[cm]?[jt]sx?)$/i;
|
|
636
|
+
// Not-deployed code that lives inside the repo: challenge fixtures, code-fix
|
|
637
|
+
// snippets, examples and demos. They contain real route registrations but never
|
|
638
|
+
// run in production, and counting them inflates the attack surface by 3x.
|
|
639
|
+
const FIXTURE_FILE = /(?:^|\/)(?:data\/static|static\/codefixes|codefixes?|fixtures?|examples?|samples?)\//i;
|
|
640
|
+
function isTestLike(rel) {
|
|
641
|
+
const p = String(rel || '');
|
|
642
|
+
return TEST_FILE.test(p) || TEST_NAME.test(p);
|
|
643
|
+
}
|
|
644
|
+
function isFixtureLike(rel) {
|
|
645
|
+
const p = String(rel || '');
|
|
646
|
+
return isTestLike(p) || FIXTURE_FILE.test(p) || /codefix/i.test(p);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// Extract the argument list of a call whose `(` is at openIdx. Returns the raw
|
|
650
|
+
// argument text and where the call ends. Handles quotes, escapes and nesting.
|
|
651
|
+
function callArgs(content, openIdx) {
|
|
652
|
+
let depth = 0;
|
|
653
|
+
let quote = null;
|
|
654
|
+
let i = openIdx;
|
|
655
|
+
const start = openIdx + 1;
|
|
656
|
+
for (; i < content.length; i++) {
|
|
657
|
+
const ch = content[i];
|
|
658
|
+
if (quote) {
|
|
659
|
+
if (ch === '\\') { i++; continue; }
|
|
660
|
+
if (ch === quote) quote = null;
|
|
661
|
+
continue;
|
|
662
|
+
}
|
|
663
|
+
if (ch === "'" || ch === '"' || ch === '`') { quote = ch; continue; }
|
|
664
|
+
if (ch === '(') depth++;
|
|
665
|
+
else if (ch === ')') {
|
|
666
|
+
depth--;
|
|
667
|
+
if (depth === 0) break;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
return { argsText: content.slice(start, i), end: i };
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
function splitArgs(argsText) {
|
|
674
|
+
const out = [];
|
|
675
|
+
let depth = 0;
|
|
676
|
+
let quote = null;
|
|
677
|
+
let cur = '';
|
|
678
|
+
for (let i = 0; i < argsText.length; i++) {
|
|
679
|
+
const ch = argsText[i];
|
|
680
|
+
if (quote) {
|
|
681
|
+
cur += ch;
|
|
682
|
+
if (ch === '\\') { cur += argsText[i + 1] || ''; i++; continue; }
|
|
683
|
+
if (ch === quote) quote = null;
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
if (ch === "'" || ch === '"' || ch === '`') { quote = ch; cur += ch; continue; }
|
|
687
|
+
if ('([{'.includes(ch)) depth++;
|
|
688
|
+
if (')]}'.includes(ch)) depth--;
|
|
689
|
+
if (ch === ',' && depth === 0) { out.push(cur.trim()); cur = ''; continue; }
|
|
690
|
+
cur += ch;
|
|
691
|
+
}
|
|
692
|
+
if (cur.trim()) out.push(cur.trim());
|
|
693
|
+
return out;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// Find a function/method definition inside one file, by name (and optional
|
|
697
|
+
// member). Prefers an AST range (exact), falls back to brace matching.
|
|
698
|
+
const PARSE_CACHE = new Map();
|
|
699
|
+
|
|
700
|
+
function parsedFile(file) {
|
|
701
|
+
if (!file) return null;
|
|
702
|
+
const key = `${file.rel}:${file.content.length}`;
|
|
703
|
+
if (PARSE_CACHE.has(key)) return PARSE_CACHE.get(key);
|
|
704
|
+
let tree = null;
|
|
705
|
+
try {
|
|
706
|
+
tree = require('./ast').parseSource(file.content, file.rel);
|
|
707
|
+
} catch {
|
|
708
|
+
tree = null;
|
|
709
|
+
}
|
|
710
|
+
PARSE_CACHE.set(key, tree);
|
|
711
|
+
return tree;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
function isFunctionNode(n) {
|
|
715
|
+
return (
|
|
716
|
+
n &&
|
|
717
|
+
(n.type === 'FunctionDeclaration' ||
|
|
718
|
+
n.type === 'FunctionExpression' ||
|
|
719
|
+
n.type === 'ArrowFunctionExpression')
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// Depth-first search for a handler definition. Cheap on the files that hold
|
|
724
|
+
// route tables (they are small); bounded by node count.
|
|
725
|
+
function findInTree(root, ident, member) {
|
|
726
|
+
let found = null;
|
|
727
|
+
const visit = (node) => {
|
|
728
|
+
if (!node || found) return;
|
|
729
|
+
if (Array.isArray(node)) {
|
|
730
|
+
for (const n of node) visit(n);
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
if (typeof node !== 'object') return;
|
|
734
|
+
|
|
735
|
+
if (node.type === 'AssignmentExpression' && node.left && node.left.type === 'MemberExpression') {
|
|
736
|
+
const left = node.left;
|
|
737
|
+
const prop = left.property && left.property.name;
|
|
738
|
+
if (member && prop === member && isFunctionNode(node.right)) {
|
|
739
|
+
found = node.right;
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
if (!member && left.object && left.object.name === 'exports' && prop === ident && isFunctionNode(node.right)) {
|
|
743
|
+
found = node.right;
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
if (node.type === 'VariableDeclarator' && !member && node.id && node.id.name === ident && isFunctionNode(node.init)) {
|
|
748
|
+
found = node.init;
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
if (node.type === 'FunctionDeclaration' && !member && node.id && node.id.name === ident) {
|
|
752
|
+
found = node;
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
if (node.type === 'MethodDefinition' && member && isFunctionNode(node.value)) {
|
|
756
|
+
const key = node.key && (node.key.name || node.key.value);
|
|
757
|
+
if (key === member) {
|
|
758
|
+
found = node.value;
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
if (node.type === 'Property' && member && isFunctionNode(node.value)) {
|
|
763
|
+
const key = node.key && (node.key.name || node.key.value);
|
|
764
|
+
if (key === member) {
|
|
765
|
+
found = node.value;
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
for (const key of Object.keys(node)) {
|
|
770
|
+
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end' || key === 'type') continue;
|
|
771
|
+
visit(node[key]);
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
visit(root);
|
|
775
|
+
return found;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
function findDefinition(file, ident, member) {
|
|
779
|
+
if (!file) return null;
|
|
780
|
+
|
|
781
|
+
const tree = parsedFile(file);
|
|
782
|
+
if (tree) {
|
|
783
|
+
const node = findInTree(tree, ident, member);
|
|
784
|
+
if (node && node.loc) {
|
|
785
|
+
return { rel: file.rel, start: node.loc.start.line - 1, end: node.loc.end.line - 1 };
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// Fallback: text patterns + brace matching.
|
|
790
|
+
const { content, lines } = file;
|
|
791
|
+
const patterns = [];
|
|
792
|
+
if (member) {
|
|
793
|
+
patterns.push(new RegExp(`this\\.${member}\\s*=\\s*(?:async\\s*)?(?:function\\s*)?\\(`, 'g'));
|
|
794
|
+
patterns.push(new RegExp(`(?:^|\\n)\\s*(?:async\\s+)?${member}\\s*\\([^)]*\\)\\s*\\{`, 'g'));
|
|
795
|
+
patterns.push(new RegExp(`exports\\.${member}\\s*=\\s*(?:async\\s*)?(?:function\\s*)?\\(`, 'g'));
|
|
796
|
+
} else {
|
|
797
|
+
patterns.push(new RegExp(`(?:^|\\n)\\s*(?:async\\s+)?function\\s+${ident}\\s*\\(`, 'g'));
|
|
798
|
+
patterns.push(new RegExp(`(?:const|let|var)\\s+${ident}\\s*=\\s*(?:async\\s*)?(?:function\\s*)?\\(`, 'g'));
|
|
799
|
+
}
|
|
800
|
+
for (const re of patterns) {
|
|
801
|
+
re.lastIndex = 0;
|
|
802
|
+
const m = re.exec(content);
|
|
803
|
+
if (!m) continue;
|
|
804
|
+
const index = m.index + (m[0].startsWith('\n') ? 1 : 0);
|
|
805
|
+
const line = content.slice(0, index).split('\n').length - 1;
|
|
806
|
+
const { start, end } = braceWindow(lines, line);
|
|
807
|
+
return { rel: file.rel, start, end };
|
|
808
|
+
}
|
|
809
|
+
return null;
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// Range of the inline handler passed to `app.<method>('<path>', …)` — precise
|
|
813
|
+
// AST bounds instead of brace guessing, which over-attributed findings from
|
|
814
|
+
// unrelated code in big server files.
|
|
815
|
+
function findRouteCallRange(file, method, path, nearLine) {
|
|
816
|
+
const tree = parsedFile(file);
|
|
817
|
+
if (!tree) return null;
|
|
818
|
+
let found = null;
|
|
819
|
+
const wanted = String(method).toLowerCase();
|
|
820
|
+
const visit = (node) => {
|
|
821
|
+
if (!node || found) return;
|
|
822
|
+
if (Array.isArray(node)) {
|
|
823
|
+
for (const n of node) visit(n);
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
if (typeof node !== 'object') return;
|
|
827
|
+
if (node.type === 'CallExpression' && node.callee && node.callee.type === 'MemberExpression') {
|
|
828
|
+
const prop = node.callee.property && node.callee.property.name;
|
|
829
|
+
const args = node.arguments || [];
|
|
830
|
+
const first = args[0];
|
|
831
|
+
const firstVal =
|
|
832
|
+
first && first.type === 'Literal' ? String(first.value)
|
|
833
|
+
: first && first.type === 'TemplateLiteral' && first.expressions.length === 0 ? first.quasis[0].value.cooked
|
|
834
|
+
: null;
|
|
835
|
+
if (
|
|
836
|
+
prop === wanted &&
|
|
837
|
+
firstVal === path &&
|
|
838
|
+
node.loc &&
|
|
839
|
+
Math.abs(node.loc.start.line - 1 - nearLine) <= 3
|
|
840
|
+
) {
|
|
841
|
+
const fn = [...args].reverse().find((a) => isFunctionNode(a));
|
|
842
|
+
if (fn && fn.loc) found = fn;
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
for (const key of Object.keys(node)) {
|
|
847
|
+
if (key === 'loc' || key === 'range' || key === 'start' || key === 'end' || key === 'type') continue;
|
|
848
|
+
visit(node[key]);
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
visit(tree);
|
|
852
|
+
return found ? { start: found.loc.start.line - 1, end: found.loc.end.line - 1 } : null;
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
function resolveHandlerExpr(ctx, fromRel, expr) {
|
|
856
|
+
if (!ctx || !expr) return null;
|
|
857
|
+
const cleaned = String(expr).replace(/^(?:await\s+)/, '').trim();
|
|
858
|
+
const simple = /^([A-Za-z_$][\w$]*)(?:\.([A-Za-z_$][\w$]*))?$/.exec(cleaned);
|
|
859
|
+
if (!simple) return null; // inline arrow/function — the registration window covers it
|
|
860
|
+
const ident = simple[1];
|
|
861
|
+
const member = simple[2] || null;
|
|
862
|
+
|
|
863
|
+
const here = ctx.filesByRel.get(fromRel);
|
|
864
|
+
const local = findDefinition(here, ident, member);
|
|
865
|
+
if (local) return local;
|
|
866
|
+
|
|
867
|
+
// `const allocationsHandler = new AllocationsHandler(db)` — the handler is a
|
|
868
|
+
// method on an instance of an imported class.
|
|
869
|
+
if (member && here) {
|
|
870
|
+
const instantiate = new RegExp(`(?:const|let|var)\\s+${ident}\\s*=\\s*new\\s+([A-Za-z_$][\\w$]*)\\s*\\(`, 'g');
|
|
871
|
+
const im = instantiate.exec(here.content);
|
|
872
|
+
if (im) {
|
|
873
|
+
const classSpec = (ctx.imports.get(fromRel) || new Map()).get(im[1]);
|
|
874
|
+
if (classSpec) {
|
|
875
|
+
const target = ctx.resolve(fromRel, classSpec);
|
|
876
|
+
if (target) {
|
|
877
|
+
const found = findDefinition(ctx.filesByRel.get(target), im[1], member);
|
|
878
|
+
if (found) return found;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
const spec = (ctx.imports.get(fromRel) || new Map()).get(ident);
|
|
885
|
+
if (!spec) return null;
|
|
886
|
+
const target = ctx.resolve(fromRel, spec);
|
|
887
|
+
if (!target) return null;
|
|
888
|
+
return findDefinition(ctx.filesByRel.get(target), ident, member);
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
// ---------------------------------------------------------------------------
|
|
892
|
+
// Finalize: attach auth, ownership, writer facts to an entrypoint
|
|
893
|
+
// ---------------------------------------------------------------------------
|
|
894
|
+
|
|
895
|
+
function finishEntrypoint(file, e, ctx) {
|
|
896
|
+
// Analyse the resolved handler body when we have one; otherwise the window
|
|
897
|
+
// from the registration line (inline handlers, Next.js exports).
|
|
898
|
+
let bodyFile = file;
|
|
899
|
+
let start = Math.max(0, e.start);
|
|
900
|
+
let end = Math.min(file.lines.length - 1, e.end);
|
|
901
|
+
if (e.handler) {
|
|
902
|
+
const resolved = ctx && ctx.filesByRel.get(e.handler.rel);
|
|
903
|
+
if (resolved) {
|
|
904
|
+
bodyFile = resolved;
|
|
905
|
+
start = Math.max(0, e.handler.start);
|
|
906
|
+
end = Math.min(resolved.lines.length - 1, e.handler.end);
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
const lines = bodyFile.lines;
|
|
910
|
+
const rel = file.rel;
|
|
911
|
+
const raw = bodyText(lines, start, end);
|
|
912
|
+
const body = stripComments(raw);
|
|
913
|
+
const explicit = e.explicitAuth || null;
|
|
914
|
+
|
|
915
|
+
// Guards can be: inherited from a mount, a class decorator, an explicit
|
|
916
|
+
// public/protected qualifier, a middleware argument on the registration line,
|
|
917
|
+
// or a call inside the handler body.
|
|
918
|
+
const guardArgs = guardsIn(e.middlewareText || '');
|
|
919
|
+
const guards = [...new Set([...guardArgs, ...guardsIn(body, true)])];
|
|
920
|
+
const inherited = e.inheritedAuth || null;
|
|
921
|
+
const isPublic = PUBLIC_RE.test(body);
|
|
922
|
+
|
|
923
|
+
let auth;
|
|
924
|
+
if (inherited === 'enforced' || (e.classGuard && e.classGuard.length > 0)) auth = 'enforced';
|
|
925
|
+
else if (explicit === 'enforced') auth = 'enforced';
|
|
926
|
+
else if (explicit === 'none' || isPublic) auth = 'none';
|
|
927
|
+
else if (guards.length > 0) auth = 'enforced';
|
|
928
|
+
else if (e.handlerUnresolved) auth = 'unknown';
|
|
929
|
+
else auth = 'none';
|
|
930
|
+
|
|
931
|
+
const stateChanging =
|
|
932
|
+
!['GET', 'HEAD', 'OPTIONS'].includes(String(e.method).toUpperCase()) ||
|
|
933
|
+
e.kind === 'server-action' || e.kind === 'mcp-tool';
|
|
934
|
+
|
|
935
|
+
// Where does the request id enter this handler?
|
|
936
|
+
const idRe = new RegExp(ID_PARAM_RE.source, 'i');
|
|
937
|
+
const idMatch = idRe.exec(body);
|
|
938
|
+
const idLine = idMatch ? start + body.slice(0, idMatch.index).split('\n').length - 1 : -1;
|
|
939
|
+
// Alternatives carry different capture groups; take the first that matched.
|
|
940
|
+
const idParam = idMatch ? (idMatch.slice(1).find(Boolean) || 'id') : null;
|
|
941
|
+
|
|
942
|
+
// Ownership: an owner/tenant column constrains the same query. When it does
|
|
943
|
+
// not, an identity-shaped id param (userId/accountId/…) with no session
|
|
944
|
+
// reference is the classic IDOR shape.
|
|
945
|
+
let ownership = 'n/a';
|
|
946
|
+
if (idParam) {
|
|
947
|
+
const near = ownerCheck(lines, start, end, idLine);
|
|
948
|
+
if (near) ownership = 'scoped';
|
|
949
|
+
else {
|
|
950
|
+
const idVar = idParam.replace(/[^\w$]/g, '');
|
|
951
|
+
const queryNearById =
|
|
952
|
+
new RegExp(
|
|
953
|
+
`(?:DAO\\.|\\.query\\(|\\bfind\\w*\\(|where\\s*:|\\beq\\(|\\b(?:get|set|load|fetch|delete|update|remove)[A-Z]\\w*\\s*\\()[\\s\\S]{0,200}?\\b${idVar}\\b`,
|
|
954
|
+
'i'
|
|
955
|
+
).test(body) ||
|
|
956
|
+
new RegExp(`\\b${idVar}\\b[\\s\\S]{0,120}?(?:DAO\\.|\\.query\\(|\\bfind\\w*\\()`, 'i').test(body);
|
|
957
|
+
const identityShaped = /^(?:userId|user_id|accountId|account_id|customerId|customer_id|memberId|uid|ownerId|owner_id|profile)$/i.test(idParam);
|
|
958
|
+
const sessionRef = /req\.session|res\.locals|req\.user\b|session\.user|user\.id|auth\(\)|getServerSession|getSession|getUser|currentUser|ctx\.user/i.test(body);
|
|
959
|
+
// A handler that reads an object id from the request and never touches
|
|
960
|
+
// the caller's identity is the shape of IDOR; with a session reference
|
|
961
|
+
// present, only the identity-shaped params (userId/accountId/…) count.
|
|
962
|
+
if (queryNearById && (!sessionRef || identityShaped)) ownership = 'missing';
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
const writes = WRITE_RE.test(body);
|
|
967
|
+
const rateLimited = RATELIMIT_RE.test(body);
|
|
968
|
+
// Login / OTP / auth endpoints are brute-forceable when unthrottled.
|
|
969
|
+
const sensitive =
|
|
970
|
+
/\b(login|signin|sign_in|otp|verify|reset|forgot|register|signup|sign_up|token|password)\b/i.test(
|
|
971
|
+
String(e.path)
|
|
972
|
+
);
|
|
973
|
+
|
|
974
|
+
return {
|
|
975
|
+
id: `${e.kind}:${rel}:${e.line}:${e.method}:${e.path}`,
|
|
976
|
+
kind: e.kind,
|
|
977
|
+
framework: e.framework,
|
|
978
|
+
method: e.method,
|
|
979
|
+
path: e.path,
|
|
980
|
+
file: rel,
|
|
981
|
+
line: e.line,
|
|
982
|
+
bodyFile: bodyFile.rel,
|
|
983
|
+
startLine: start + 1,
|
|
984
|
+
endLine: end + 1,
|
|
985
|
+
guards,
|
|
986
|
+
auth,
|
|
987
|
+
stateChanging,
|
|
988
|
+
writes,
|
|
989
|
+
readsObjectId: !!idParam,
|
|
990
|
+
idParam,
|
|
991
|
+
ownership,
|
|
992
|
+
rateLimited,
|
|
993
|
+
sensitive,
|
|
994
|
+
snippet: (lines[e.line - 1] || '').trim().slice(0, 160),
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
// ---------------------------------------------------------------------------
|
|
999
|
+
// Public extraction
|
|
1000
|
+
// ---------------------------------------------------------------------------
|
|
1001
|
+
|
|
1002
|
+
function extractEntrypoints(files) {
|
|
1003
|
+
const out = [];
|
|
1004
|
+
const { mountByRel, imports, resolve } = collectExpressRoutes(files);
|
|
1005
|
+
const ctx = { filesByRel: new Map(files.map((f) => [f.rel, f])), imports, resolve };
|
|
1006
|
+
let middleware = null;
|
|
1007
|
+
|
|
1008
|
+
for (const file of files) {
|
|
1009
|
+
const rel = file.rel;
|
|
1010
|
+
if (isFixtureLike(rel)) continue; // tests and in-repo codefix/example fixtures aren't deployed endpoints
|
|
1011
|
+
const fw = frameworkOfFile(rel);
|
|
1012
|
+
|
|
1013
|
+
// HTTP route files with conventions
|
|
1014
|
+
if (fw === 'next-app') {
|
|
1015
|
+
if (/\/route\.(js|jsx|ts|tsx|mjs)$/.test(rel)) extractNextApp(file, out);
|
|
1016
|
+
else if (/\/middleware\.(js|ts)$/.test(rel)) middleware = readNextMiddleware(file);
|
|
1017
|
+
}
|
|
1018
|
+
if (fw === 'next-pages' || fw === 'netlify' || fw === 'serverless') {
|
|
1019
|
+
extractNextPages(file, out);
|
|
1020
|
+
}
|
|
1021
|
+
if (fw === 'supabase-edge') extractSupabaseEdge(file, out);
|
|
1022
|
+
|
|
1023
|
+
// Executor-level detection — one file can hold several of these. Express and
|
|
1024
|
+
// Fastify share `.get('/x', h)` syntax, so a file is classified by the
|
|
1025
|
+
// framework it actually imports to avoid emitting both. Only real code
|
|
1026
|
+
// files: tutorials/templates often contain example `app.get(...)` snippets
|
|
1027
|
+
// that are not endpoints of this program.
|
|
1028
|
+
const ext = path.extname(rel).toLowerCase();
|
|
1029
|
+
const CODE_EXT = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.py', '.go', '.rb', '.php', '.java', '.kt', '.cs', '.rs']);
|
|
1030
|
+
if (!CODE_EXT.has(ext)) continue;
|
|
1031
|
+
const contentText = file.content;
|
|
1032
|
+
const isFastify = /\bfastify\b/i.test(contentText);
|
|
1033
|
+
const isHono = /\bfrom\s+['"]hono['"]|require\(\s*['"]hono['"]\s*\)/i.test(contentText);
|
|
1034
|
+
const isExpressLike = /require\(\s*['"]express['"]\s*\)|from\s+['"]express['"]|express\.Router|\.use\s*\(\s*['"]\//i.test(contentText);
|
|
1035
|
+
|
|
1036
|
+
extractServerActions(file, out);
|
|
1037
|
+
extractTrpc(file, out);
|
|
1038
|
+
extractNest(file, out);
|
|
1039
|
+
if (isFastify) extractFastify(file, out);
|
|
1040
|
+
if (isHono) extractHono(file, out);
|
|
1041
|
+
extractPy(file, out);
|
|
1042
|
+
extractGo(file, out);
|
|
1043
|
+
extractRails(file, out);
|
|
1044
|
+
extractMcpTools(file, out);
|
|
1045
|
+
|
|
1046
|
+
// Express-family (also catches bare `app.get` files with no express import).
|
|
1047
|
+
// Handler references (`profileHandler.displayProfile`, `isLoggedIn`) are
|
|
1048
|
+
// resolved to their definitions so auth/IDOR analysis sees the real body.
|
|
1049
|
+
const routesHere = [];
|
|
1050
|
+
if (!isFastify && !isHono) {
|
|
1051
|
+
const routeRe = /\b(app|router|server|api)\.(get|post|put|patch|delete|all)\s*\(/g;
|
|
1052
|
+
let m;
|
|
1053
|
+
while ((m = routeRe.exec(contentText)) !== null) {
|
|
1054
|
+
if (insideString(contentText, m.index) || !plausibleStart(contentText, m.index)) continue;
|
|
1055
|
+
const parenIdx = m.index + m[0].lastIndexOf('(');
|
|
1056
|
+
const { argsText } = callArgs(contentText, parenIdx);
|
|
1057
|
+
const args = splitArgs(argsText);
|
|
1058
|
+
const rawPath = (args[0] || '').trim();
|
|
1059
|
+
if (!/^['"`]/.test(rawPath)) continue; // dynamic path expression
|
|
1060
|
+
const pathText = rawPath.replace(/^['"`]/, '').replace(/['"`]$/, '');
|
|
1061
|
+
if (pathText.includes('${')) continue; // template parameter, not a literal route
|
|
1062
|
+
routesHere.push({
|
|
1063
|
+
line: contentText.slice(0, m.index).split('\n').length - 1,
|
|
1064
|
+
method: m[2] === 'all' ? '*' : m[2].toUpperCase(),
|
|
1065
|
+
path: pathText,
|
|
1066
|
+
args,
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
// Prefix-scoped auth: `app.use('/api/BasketItems', security.isAuthorized())`
|
|
1071
|
+
// guards every route registered under that prefix after this line.
|
|
1072
|
+
const prefixGuards = [];
|
|
1073
|
+
{
|
|
1074
|
+
const useRe = /\b(app|server)\.use\s*\(\s*['"]([^'"]+)['"]\s*,/g;
|
|
1075
|
+
let um;
|
|
1076
|
+
while ((um = useRe.exec(contentText)) !== null) {
|
|
1077
|
+
const parenIdx = um.index + um[0].lastIndexOf('(');
|
|
1078
|
+
const { argsText } = callArgs(contentText, parenIdx);
|
|
1079
|
+
if (GUARD_RE.test(argsText) || /isAuthorized|denyAll|requireAuth|isLoggedIn/i.test(argsText)) {
|
|
1080
|
+
prefixGuards.push({
|
|
1081
|
+
base: um[2],
|
|
1082
|
+
line: contentText.slice(0, um.index).split('\n').length - 1,
|
|
1083
|
+
});
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// Chained `app.route('/path').get(handler).put(handler)` — Express style used
|
|
1089
|
+
// by larger apps to group methods. Each chained verb is its own endpoint.
|
|
1090
|
+
{
|
|
1091
|
+
const routeChainRe = /\b(app|router)\.route\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
|
1092
|
+
let rm;
|
|
1093
|
+
while ((rm = routeChainRe.exec(contentText)) !== null) {
|
|
1094
|
+
const chainStart = rm.index + rm[0].length;
|
|
1095
|
+
const chainText = contentText.slice(chainStart, chainStart + 1500);
|
|
1096
|
+
const verbRe = /\.(get|post|put|patch|delete|all)\s*\(/g;
|
|
1097
|
+
let vm;
|
|
1098
|
+
while ((vm = verbRe.exec(chainText)) !== null) {
|
|
1099
|
+
const abs = chainStart + vm.index;
|
|
1100
|
+
const paren = vm.index + vm[0].lastIndexOf('(');
|
|
1101
|
+
const { argsText } = callArgs(chainText, paren);
|
|
1102
|
+
routesHere.push({
|
|
1103
|
+
line: contentText.slice(0, abs).split('\n').length - 1,
|
|
1104
|
+
method: vm[1] === 'all' ? '*' : vm[1].toUpperCase(),
|
|
1105
|
+
path: rm[2],
|
|
1106
|
+
args: [`'${rm[2]}'`, ...splitArgs(argsText)],
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// Attach router mount prefixes + auth middleware inherited from app.use().
|
|
1113
|
+
const mountInfo = mountByRel.get(rel) || [];
|
|
1114
|
+
const inherited = mountInfo.some((mo) => MOUNT_AUTH_RE.test(mo.middleware))
|
|
1115
|
+
? 'enforced'
|
|
1116
|
+
: null;
|
|
1117
|
+
// router.use(authFn) before a route line also guards it.
|
|
1118
|
+
const useAuthLine = (() => {
|
|
1119
|
+
let best = -1;
|
|
1120
|
+
const useRe = /\b(?:router|app)\.use\s*\(\s*([^)]*)\)/g;
|
|
1121
|
+
let um;
|
|
1122
|
+
while ((um = useRe.exec(file.content)) !== null) {
|
|
1123
|
+
if (MOUNT_AUTH_RE.test(um[1])) {
|
|
1124
|
+
const ln = file.content.slice(0, um.index).split('\n').length - 1;
|
|
1125
|
+
if (ln >= 0 && (best === -1 || ln < best)) best = ln;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
return best;
|
|
1129
|
+
})();
|
|
1130
|
+
|
|
1131
|
+
for (const r of routesHere) {
|
|
1132
|
+
const prefix = mountInfo.length ? mountInfo[0].base : '';
|
|
1133
|
+
const fullPath = prefix + r.path;
|
|
1134
|
+
const prefixGuard = prefixGuards.find((pg) => fullPath.startsWith(pg.base) && pg.line <= r.line);
|
|
1135
|
+
const localInherited =
|
|
1136
|
+
inherited || (prefixGuard ? 'enforced' : null) || (useAuthLine >= 0 && useAuthLine <= r.line ? 'enforced' : null);
|
|
1137
|
+
const middlewareText = r.args.slice(1, -1).join(',');
|
|
1138
|
+
const handlerExpr = (r.args[r.args.length - 1] || '').trim();
|
|
1139
|
+
let handler = null;
|
|
1140
|
+
let handlerUnresolved = false;
|
|
1141
|
+
let bodyWindow;
|
|
1142
|
+
if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?$/.test(handlerExpr)) {
|
|
1143
|
+
handler = resolveHandlerExpr(ctx, rel, handlerExpr);
|
|
1144
|
+
if (!handler) {
|
|
1145
|
+
// The body is elsewhere and we could not follow it. Keep the analysis
|
|
1146
|
+
// window on the registration line only — expanding braces here would
|
|
1147
|
+
// pull unrelated code (and other routes' guards) into this endpoint.
|
|
1148
|
+
handlerUnresolved = true;
|
|
1149
|
+
bodyWindow = { start: r.line, end: r.line };
|
|
1150
|
+
}
|
|
1151
|
+
} else {
|
|
1152
|
+
const methodToken = r.method === '*' ? 'all' : String(r.method).toLowerCase();
|
|
1153
|
+
bodyWindow =
|
|
1154
|
+
findRouteCallRange(file, methodToken, r.path, r.line) ||
|
|
1155
|
+
braceWindow(file.lines, r.line);
|
|
1156
|
+
}
|
|
1157
|
+
const { start, end } = handler ? { start: r.line, end: r.line } : bodyWindow;
|
|
1158
|
+
out.push(finishEntrypoint(file, {
|
|
1159
|
+
kind: 'http', framework: 'express', method: r.method, path: prefix + r.path,
|
|
1160
|
+
line: r.line + 1, start, end, inheritedAuth: localInherited,
|
|
1161
|
+
middlewareText, handler, handlerUnresolved,
|
|
1162
|
+
}, ctx));
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
// Deduplicate by (kind,file,line,method,path).
|
|
1167
|
+
const seen = new Set();
|
|
1168
|
+
const unique = [];
|
|
1169
|
+
for (const e of out) {
|
|
1170
|
+
const key = `${e.kind}|${e.file}|${e.line}|${e.method}|${e.path}`;
|
|
1171
|
+
if (seen.has(key)) continue;
|
|
1172
|
+
seen.add(key);
|
|
1173
|
+
unique.push(e);
|
|
1174
|
+
}
|
|
1175
|
+
unique.sort((a, b) => (a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1));
|
|
1176
|
+
|
|
1177
|
+
const authCoverage = {
|
|
1178
|
+
total: unique.length,
|
|
1179
|
+
enforced: unique.filter((e) => e.auth === 'enforced').length,
|
|
1180
|
+
unprotected: unique.filter((e) => e.auth === 'none').length,
|
|
1181
|
+
unprotectedStateChanging: unique.filter((e) => e.auth === 'none' && e.stateChanging).length,
|
|
1182
|
+
idorCandidates: unique.filter((e) => e.ownership === 'missing').length,
|
|
1183
|
+
unthrottledSensitive: unique.filter((e) => e.sensitive && !e.rateLimited).length,
|
|
1184
|
+
coverage:
|
|
1185
|
+
unique.length > 0
|
|
1186
|
+
? Math.round((unique.filter((e) => e.auth === 'enforced').length / unique.length) * 100)
|
|
1187
|
+
: 100,
|
|
1188
|
+
};
|
|
1189
|
+
|
|
1190
|
+
return { entrypoints: unique, authCoverage, middleware };
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
function readNextMiddleware(file) {
|
|
1194
|
+
const matcher = /matcher\s*:\s*\[([\s\S]{0,400}?)\]/.exec(file.content);
|
|
1195
|
+
const patterns = matcher ? [...matcher[1].matchAll(/['"]([^'"]+)['"]/g)].map((m) => m[1]) : [];
|
|
1196
|
+
const hasAuth = MOUNT_AUTH_RE.test(file.content);
|
|
1197
|
+
// A matcher that excludes /api means middleware cannot be the only auth gate.
|
|
1198
|
+
const apiExcluded = patterns.some((p) => /api/i.test(p) && /\(\?!.*api/.test(p));
|
|
1199
|
+
return { file: file.rel, line: 1, patterns, hasAuth, apiExcluded };
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
module.exports = {
|
|
1203
|
+
extractEntrypoints,
|
|
1204
|
+
frameworkOfFile,
|
|
1205
|
+
nextAppPath,
|
|
1206
|
+
GUARD_RE,
|
|
1207
|
+
OWNER_RE,
|
|
1208
|
+
ID_PARAM_RE,
|
|
1209
|
+
WRITE_RE,
|
|
1210
|
+
};
|