hullproof 0.0.0-stage → 0.5.0

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.
Files changed (363) hide show
  1. package/LICENSE +222 -0
  2. package/NOTICE +32 -0
  3. package/README.md +313 -2
  4. package/checks/db.firebase-rules-not-open.json +24 -0
  5. package/checks/db.rls-every-table.json +25 -0
  6. package/checks/log.no-credential-in-logs.json +30 -0
  7. package/checks/secrets.no-env-file-committed.json +31 -0
  8. package/checks/secrets.no-secret-in-public-env.json +37 -0
  9. package/checks/storage.firebase-rules-not-open.json +22 -0
  10. package/checks/supply.no-untrusted-event-in-run.json +23 -0
  11. package/checks/web.cors-no-reflected-origin.json +31 -0
  12. package/detectors/ai.json +25 -0
  13. package/detectors/auth.json +27 -0
  14. package/detectors/ci.json +19 -0
  15. package/detectors/containers.json +8 -0
  16. package/detectors/data_stores.json +38 -0
  17. package/detectors/frameworks.json +94 -0
  18. package/detectors/hosting.json +44 -0
  19. package/detectors/iac.json +43 -0
  20. package/detectors/languages.json +48 -0
  21. package/detectors/mobile.json +22 -0
  22. package/detectors/package_managers.json +39 -0
  23. package/detectors/payments.json +19 -0
  24. package/detectors/runtimes.json +17 -0
  25. package/dist/checks/code/admin-role.js +46 -0
  26. package/dist/checks/code/owner-filter.js +91 -0
  27. package/dist/checks/code/shared.js +84 -0
  28. package/dist/checks/code/webhook-verify.js +77 -0
  29. package/dist/checks/context.js +64 -0
  30. package/dist/checks/map/config-checks.js +74 -0
  31. package/dist/checks/map/entry-checks.js +97 -0
  32. package/dist/checks/map/shared.js +44 -0
  33. package/dist/checks/ops.js +307 -0
  34. package/dist/checks/pro-map.js +1 -0
  35. package/dist/checks/run.js +92 -0
  36. package/dist/checks/types.js +1 -0
  37. package/dist/ci/comment.js +44 -0
  38. package/dist/ci/sarif-check.js +157 -0
  39. package/dist/ci/sarif.js +61 -0
  40. package/dist/cli.js +358 -0
  41. package/dist/commands/ci.js +115 -0
  42. package/dist/commands/git.js +58 -0
  43. package/dist/commands/hooks.js +30 -0
  44. package/dist/commands/hunt-pro.js +1 -0
  45. package/dist/commands/hunt.js +86 -0
  46. package/dist/commands/map.js +33 -0
  47. package/dist/commands/mcp.js +17 -0
  48. package/dist/commands/pack.js +48 -0
  49. package/dist/commands/prove-pro.js +1 -0
  50. package/dist/commands/prove.js +173 -0
  51. package/dist/commands/report-gate.js +92 -0
  52. package/dist/commands/scan.js +158 -0
  53. package/dist/confirm/agreement.js +18 -0
  54. package/dist/confirm/chain.js +84 -0
  55. package/dist/confirm/confirm.js +112 -0
  56. package/dist/confirm/honesty.js +75 -0
  57. package/dist/confirm/lead.js +92 -0
  58. package/dist/confirm/merge.js +88 -0
  59. package/dist/confirm/query.js +145 -0
  60. package/dist/confirm/rule.js +86 -0
  61. package/dist/confirm/store.js +42 -0
  62. package/dist/confirm/summary.js +6 -0
  63. package/dist/confirm/synthesis.js +28 -0
  64. package/dist/discover/detectors.js +50 -0
  65. package/dist/discover/discover.js +270 -0
  66. package/dist/discover/extract.js +282 -0
  67. package/dist/discover/git.js +40 -0
  68. package/dist/discover/kit-files.js +47 -0
  69. package/dist/discover/walk.js +110 -0
  70. package/dist/env.js +57 -0
  71. package/dist/gate/gate.js +173 -0
  72. package/dist/hooks/install.js +153 -0
  73. package/dist/hooks/run.js +112 -0
  74. package/dist/map/analyze.js +201 -0
  75. package/dist/map/build.js +253 -0
  76. package/dist/map/candidates.js +49 -0
  77. package/dist/map/cblocks.js +77 -0
  78. package/dist/map/config.js +291 -0
  79. package/dist/map/dotnet.js +242 -0
  80. package/dist/map/entry.js +78 -0
  81. package/dist/map/expo.js +190 -0
  82. package/dist/map/go.js +292 -0
  83. package/dist/map/js-express.js +143 -0
  84. package/dist/map/js-misc.js +295 -0
  85. package/dist/map/js-next.js +292 -0
  86. package/dist/map/laravel.js +389 -0
  87. package/dist/map/lex-more.js +305 -0
  88. package/dist/map/lex.js +425 -0
  89. package/dist/map/light-index.js +191 -0
  90. package/dist/map/light-profiles.js +324 -0
  91. package/dist/map/light.js +574 -0
  92. package/dist/map/local-vocab.js +27 -0
  93. package/dist/map/mobile.js +326 -0
  94. package/dist/map/py-django.js +281 -0
  95. package/dist/map/py.js +391 -0
  96. package/dist/map/rails.js +391 -0
  97. package/dist/map/repo.js +178 -0
  98. package/dist/map/rust.js +312 -0
  99. package/dist/map/spring.js +207 -0
  100. package/dist/map/taint.js +96 -0
  101. package/dist/map/touches.js +355 -0
  102. package/dist/map/vocab.js +88 -0
  103. package/dist/mapping/controls.js +34 -0
  104. package/dist/mapping/dependency-policy.js +44 -0
  105. package/dist/mapping/map.js +44 -0
  106. package/dist/mapping/maps/gitleaks.json +12 -0
  107. package/dist/mapping/maps/osv-scanner.json +7 -0
  108. package/dist/mapping/maps/trivy.json +13 -0
  109. package/dist/mcp/confine.js +59 -0
  110. package/dist/mcp/protocol.js +140 -0
  111. package/dist/mcp/schema.js +43 -0
  112. package/dist/mcp/server.js +37 -0
  113. package/dist/mcp/tools.js +238 -0
  114. package/dist/packs/coverage.js +79 -0
  115. package/dist/packs/manifest.js +36 -0
  116. package/dist/packs/validate.js +271 -0
  117. package/dist/prove/container.js +276 -0
  118. package/dist/prove/exec-main.js +20 -0
  119. package/dist/prove/executor.js +149 -0
  120. package/dist/prove/local.js +131 -0
  121. package/dist/prove/probes.js +65 -0
  122. package/dist/prove/recipe.js +278 -0
  123. package/dist/prove/run.js +136 -0
  124. package/dist/prove/runner.js +1 -0
  125. package/dist/prove/safety.js +126 -0
  126. package/dist/prove/spec.js +357 -0
  127. package/dist/prove/store.js +65 -0
  128. package/dist/report/build.js +297 -0
  129. package/dist/report/entry-points.js +75 -0
  130. package/dist/report/hunt-section.js +71 -0
  131. package/dist/report/kit.js +41 -0
  132. package/dist/report/load.js +35 -0
  133. package/dist/report/messages.js +273 -0
  134. package/dist/report/prove-section.js +65 -0
  135. package/dist/report/report.js +156 -0
  136. package/dist/report/surface.js +21 -0
  137. package/dist/report/test-code.js +51 -0
  138. package/dist/report/tiers.js +44 -0
  139. package/dist/scanners/common.js +162 -0
  140. package/dist/scanners/gitleaks.js +90 -0
  141. package/dist/scanners/index.js +113 -0
  142. package/dist/scanners/osv-scanner.js +77 -0
  143. package/dist/scanners/run-targets.js +34 -0
  144. package/dist/scanners/secret-noise.js +89 -0
  145. package/dist/scanners/semgrep.js +142 -0
  146. package/dist/scanners/trivy.js +65 -0
  147. package/dist/scanners/types.js +1 -0
  148. package/dist/types/check.js +1 -0
  149. package/dist/types/codemap.js +1 -0
  150. package/dist/types/findings.js +5 -0
  151. package/dist/types/hunt.js +1 -0
  152. package/dist/types/index.js +1 -0
  153. package/dist/types/prove.js +1 -0
  154. package/dist/types/results.js +2 -0
  155. package/dist/types/scan.js +1 -0
  156. package/dist/types/stack.js +5 -0
  157. package/dist/util.js +71 -0
  158. package/dist/version.js +2 -0
  159. package/package.json +46 -4
  160. package/packs/android/fixture-result.json +43 -0
  161. package/packs/android/pack.json +56 -0
  162. package/packs/dotnet/fixture-result.json +62 -0
  163. package/packs/dotnet/pack.json +88 -0
  164. package/packs/expo/answer-key.json +51 -0
  165. package/packs/expo/fixture-result.json +62 -0
  166. package/packs/expo/pack.json +79 -0
  167. package/packs/firebase/answer-key.json +27 -0
  168. package/packs/firebase/fixture-result.json +43 -0
  169. package/packs/firebase/pack.json +58 -0
  170. package/packs/go/answer-key.json +101 -0
  171. package/packs/go/fixture-result.json +64 -0
  172. package/packs/go/pack.json +99 -0
  173. package/packs/ios/fixture-result.json +43 -0
  174. package/packs/ios/pack.json +55 -0
  175. package/packs/laravel/answer-key.json +84 -0
  176. package/packs/laravel/fixture-result.json +60 -0
  177. package/packs/laravel/pack.json +91 -0
  178. package/packs/node-ts/answer-key.json +220 -0
  179. package/packs/node-ts/fixture-result.json +114 -0
  180. package/packs/node-ts/pack.json +134 -0
  181. package/packs/python/answer-key.json +195 -0
  182. package/packs/python/fixture-result.json +119 -0
  183. package/packs/python/pack.json +121 -0
  184. package/packs/rails/answer-key.json +84 -0
  185. package/packs/rails/fixture-result.json +60 -0
  186. package/packs/rails/pack.json +78 -0
  187. package/packs/rust/fixture-result.json +43 -0
  188. package/packs/rust/pack.json +69 -0
  189. package/packs/spring/fixture-result.json +63 -0
  190. package/packs/spring/pack.json +103 -0
  191. package/packs/supabase/answer-key.json +52 -0
  192. package/packs/supabase/fixture-result.json +58 -0
  193. package/packs/supabase/pack.json +60 -0
  194. package/rules/gitleaks.toml +256 -0
  195. package/rules/semgrep/api-route-no-auth.yaml +31 -0
  196. package/rules/semgrep/cors-reflect-origin.yaml +48 -0
  197. package/rules/semgrep/eval-or-new-function.yaml +185 -0
  198. package/rules/semgrep/log-session-token.yaml +48 -0
  199. package/rules/semgrep/math-random-tokens.yaml +24 -0
  200. package/rules/semgrep/next-public-secret-name.yaml +32 -0
  201. package/rules/semgrep/postgrest-filter-injection.yaml +78 -0
  202. package/rules/semgrep/raw-sql-concat.yaml +42 -0
  203. package/rules/semgrep/read-by-id-no-owner.yaml +49 -0
  204. package/rules/semgrep/server-action-no-auth.yaml +26 -0
  205. package/rules/semgrep/sql-variants.yaml +99 -0
  206. package/rules/semgrep/ssrf-unguarded-url.yaml +137 -0
  207. package/rules/semgrep/subprocess-injection.yaml +163 -0
  208. package/rules/semgrep/taint-go.yaml +333 -0
  209. package/rules/semgrep/taint-java.yaml +317 -0
  210. package/rules/semgrep/taint-javascript.yaml +412 -0
  211. package/rules/semgrep/taint-php.yaml +361 -0
  212. package/rules/semgrep/taint-python.yaml +414 -0
  213. package/rules/semgrep/tool-endpoint-admin-client.yaml +86 -0
  214. package/rules/semgrep/user-metadata-authz.yaml +22 -0
  215. package/rules/semgrep/verify-result-unused.yaml +62 -0
  216. package/rules/semgrep/webhook-parse-before-verify.yaml +29 -0
  217. package/rules/test-artifact-ids.json +4 -0
  218. package/rules/tiers.json +427 -0
  219. package/schemas/check-results.schema.json +55 -0
  220. package/schemas/check.schema.json +41 -0
  221. package/schemas/codemap.schema.json +216 -0
  222. package/schemas/findings.schema.json +1048 -0
  223. package/schemas/hunt-output.schema.json +46 -0
  224. package/schemas/hunt-result.schema.json +58 -0
  225. package/schemas/results.schema.json +17 -0
  226. package/schemas/scan-hits.schema.json +32 -0
  227. package/schemas/scan-meta.schema.json +25 -0
  228. package/schemas/stack.schema.json +93 -0
  229. package/src/checks/README.md +32 -0
  230. package/src/checks/code/admin-role.ts +49 -0
  231. package/src/checks/code/owner-filter.ts +95 -0
  232. package/src/checks/code/shared.ts +66 -0
  233. package/src/checks/code/webhook-verify.ts +75 -0
  234. package/src/checks/context.ts +72 -0
  235. package/src/checks/map/config-checks.ts +79 -0
  236. package/src/checks/map/entry-checks.ts +116 -0
  237. package/src/checks/map/shared.ts +63 -0
  238. package/src/checks/ops.ts +280 -0
  239. package/src/checks/pro-map.ts +4 -0
  240. package/src/checks/run.ts +80 -0
  241. package/src/checks/types.ts +12 -0
  242. package/src/ci/comment.ts +52 -0
  243. package/src/ci/sarif-check.ts +100 -0
  244. package/src/ci/sarif.ts +72 -0
  245. package/src/cli.ts +273 -0
  246. package/src/commands/ci.ts +104 -0
  247. package/src/commands/git.ts +59 -0
  248. package/src/commands/hooks.ts +27 -0
  249. package/src/commands/hunt-pro.ts +4 -0
  250. package/src/commands/hunt.ts +68 -0
  251. package/src/commands/map.ts +27 -0
  252. package/src/commands/mcp.ts +18 -0
  253. package/src/commands/pack.ts +34 -0
  254. package/src/commands/prove-pro.ts +4 -0
  255. package/src/commands/prove.ts +126 -0
  256. package/src/commands/report-gate.ts +75 -0
  257. package/src/commands/scan.ts +156 -0
  258. package/src/confirm/agreement.ts +23 -0
  259. package/src/confirm/chain.ts +67 -0
  260. package/src/confirm/confirm.ts +107 -0
  261. package/src/confirm/honesty.ts +65 -0
  262. package/src/confirm/lead.ts +76 -0
  263. package/src/confirm/merge.ts +89 -0
  264. package/src/confirm/query.ts +126 -0
  265. package/src/confirm/rule.ts +76 -0
  266. package/src/confirm/store.ts +42 -0
  267. package/src/confirm/summary.ts +9 -0
  268. package/src/confirm/synthesis.ts +33 -0
  269. package/src/discover/detectors.ts +71 -0
  270. package/src/discover/discover.ts +253 -0
  271. package/src/discover/extract.ts +235 -0
  272. package/src/discover/git.ts +31 -0
  273. package/src/discover/kit-files.ts +37 -0
  274. package/src/discover/walk.ts +88 -0
  275. package/src/env.ts +51 -0
  276. package/src/gate/gate.ts +169 -0
  277. package/src/hooks/install.ts +142 -0
  278. package/src/hooks/run.ts +121 -0
  279. package/src/map/analyze.ts +219 -0
  280. package/src/map/build.ts +206 -0
  281. package/src/map/candidates.ts +47 -0
  282. package/src/map/cblocks.ts +55 -0
  283. package/src/map/config.ts +207 -0
  284. package/src/map/dotnet.ts +205 -0
  285. package/src/map/entry.ts +80 -0
  286. package/src/map/expo.ts +171 -0
  287. package/src/map/go.ts +271 -0
  288. package/src/map/js-express.ts +135 -0
  289. package/src/map/js-misc.ts +221 -0
  290. package/src/map/js-next.ts +282 -0
  291. package/src/map/laravel.ts +327 -0
  292. package/src/map/lex-more.ts +152 -0
  293. package/src/map/lex.ts +274 -0
  294. package/src/map/light-index.ts +134 -0
  295. package/src/map/light-profiles.ts +363 -0
  296. package/src/map/light.ts +484 -0
  297. package/src/map/local-vocab.ts +30 -0
  298. package/src/map/mobile.ts +263 -0
  299. package/src/map/py-django.ts +239 -0
  300. package/src/map/py.ts +329 -0
  301. package/src/map/rails.ts +291 -0
  302. package/src/map/repo.ts +150 -0
  303. package/src/map/rust.ts +256 -0
  304. package/src/map/spring.ts +185 -0
  305. package/src/map/taint.ts +86 -0
  306. package/src/map/touches.ts +296 -0
  307. package/src/map/vocab.ts +106 -0
  308. package/src/mapping/controls.ts +47 -0
  309. package/src/mapping/dependency-policy.ts +55 -0
  310. package/src/mapping/map.ts +59 -0
  311. package/src/mapping/maps/gitleaks.json +12 -0
  312. package/src/mapping/maps/osv-scanner.json +7 -0
  313. package/src/mapping/maps/trivy.json +13 -0
  314. package/src/mcp/confine.ts +44 -0
  315. package/src/mcp/protocol.ts +144 -0
  316. package/src/mcp/schema.ts +35 -0
  317. package/src/mcp/server.ts +32 -0
  318. package/src/mcp/tools.ts +235 -0
  319. package/src/packs/coverage.ts +98 -0
  320. package/src/packs/manifest.ts +97 -0
  321. package/src/packs/validate.ts +204 -0
  322. package/src/prove/container.ts +237 -0
  323. package/src/prove/exec-main.ts +16 -0
  324. package/src/prove/executor.ts +130 -0
  325. package/src/prove/local.ts +100 -0
  326. package/src/prove/probes.ts +68 -0
  327. package/src/prove/recipe.ts +215 -0
  328. package/src/prove/run.ts +124 -0
  329. package/src/prove/runner.ts +28 -0
  330. package/src/prove/safety.ts +98 -0
  331. package/src/prove/spec.ts +256 -0
  332. package/src/prove/store.ts +48 -0
  333. package/src/report/build.ts +304 -0
  334. package/src/report/entry-points.ts +78 -0
  335. package/src/report/hunt-section.ts +67 -0
  336. package/src/report/kit.ts +59 -0
  337. package/src/report/load.ts +49 -0
  338. package/src/report/messages.ts +270 -0
  339. package/src/report/prove-section.ts +61 -0
  340. package/src/report/report.ts +160 -0
  341. package/src/report/surface.ts +32 -0
  342. package/src/report/test-code.ts +56 -0
  343. package/src/report/tiers.ts +50 -0
  344. package/src/scanners/common.ts +149 -0
  345. package/src/scanners/gitleaks.ts +89 -0
  346. package/src/scanners/index.ts +103 -0
  347. package/src/scanners/osv-scanner.ts +90 -0
  348. package/src/scanners/run-targets.ts +35 -0
  349. package/src/scanners/secret-noise.ts +80 -0
  350. package/src/scanners/semgrep.ts +139 -0
  351. package/src/scanners/trivy.ts +66 -0
  352. package/src/scanners/types.ts +98 -0
  353. package/src/types/check.ts +52 -0
  354. package/src/types/codemap.ts +142 -0
  355. package/src/types/findings.ts +107 -0
  356. package/src/types/hunt.ts +97 -0
  357. package/src/types/index.ts +10 -0
  358. package/src/types/prove.ts +83 -0
  359. package/src/types/results.ts +15 -0
  360. package/src/types/scan.ts +63 -0
  361. package/src/types/stack.ts +61 -0
  362. package/src/util.ts +59 -0
  363. package/src/version.ts +2 -0
@@ -0,0 +1,295 @@
1
+ import { empty, joinPath, makeEntry, paramNames } from './entry.js';
2
+ import { closeOf, jsFunction, splitArgs } from './lex.js';
3
+ import { paramsOf, resolveFunction } from './js-next.js';
4
+ const NEST_VERBS = /@(Get|Post|Put|Patch|Delete|All|Options|Head)\s*\(/g;
5
+ const NEST_OTHER = /@(Query|Mutation|Subscription|ResolveField|MessagePattern|EventPattern|SubscribeMessage|Cron|Interval|Timeout|Process)\s*\(/g;
6
+ const PUBLIC_MARK = /@(?:Public|AllowAnonymous|SkipAuth|IsPublic|NoAuth|AllowUnauthenticated)\s*\(/;
7
+ const dtoCache = new WeakMap();
8
+ // Whether a class of this name in the repository carries class-validator decorators.
9
+ function dtoValidated(repo, name) {
10
+ let cache = dtoCache.get(repo);
11
+ if (!cache) {
12
+ cache = new Map();
13
+ dtoCache.set(repo, cache);
14
+ }
15
+ const hit = cache.get(name);
16
+ if (hit !== undefined)
17
+ return hit;
18
+ let ok = false;
19
+ for (const f of repo.filesOf('js')) {
20
+ const t = repo.ctx.text(f);
21
+ const m = new RegExp(`class\\s+${name}\\b[^{]*\\{`).exec(t);
22
+ if (!m)
23
+ continue;
24
+ const body = t.slice(m.index, m.index + 4000);
25
+ if (/@(?:Is[A-Z]\w*|Min|Max|Length|MinLength|MaxLength|Matches|Validate\w*|Allow|ArrayMaxSize|ArrayMinSize|Contains|NotEquals|Equals|IsOptional)\s*\(/.test(body)) {
26
+ ok = true;
27
+ break;
28
+ }
29
+ }
30
+ cache.set(name, ok);
31
+ return ok;
32
+ }
33
+ export function extractNest(repo, v) {
34
+ const out = empty();
35
+ if (!/@(?:Controller|Resolver|Cron|Interval|Timeout|MessagePattern|EventPattern|SubscribeMessage|Process|Processor)\s*\(|APP_GUARD|useGlobalPipes|consumer\s*\.\s*apply\s*\(/.test(v.text))
36
+ return out;
37
+ const { masked, text } = v;
38
+ // Global guards and pipes become gates.
39
+ for (const m of masked.matchAll(/provide\s*:\s*APP_GUARD/g)) {
40
+ const seg = text.slice(m.index, m.index + 160);
41
+ const cls = /useClass\s*:\s*([A-Za-z_$][\w$]*)/.exec(seg)?.[1] ?? 'APP_GUARD';
42
+ const protections = [];
43
+ const line = v.lines.at(m.index);
44
+ if (/auth|jwt|session|firebase|supabase/i.test(cls))
45
+ protections.push({ kind: 'session_read', scope: 'global', file: v.file, line, via: `APP_GUARD ${cls}`, enforced: true, confidence: 'medium' });
46
+ if (/role|permission|admin|abac|casl/i.test(cls))
47
+ protections.push({ kind: 'role_check', scope: 'global', file: v.file, line, via: `APP_GUARD ${cls}`, enforced: true, confidence: 'medium' });
48
+ if (/throttl|rate/i.test(cls))
49
+ protections.push({ kind: 'rate_limit', scope: 'global', file: v.file, line, via: `APP_GUARD ${cls}`, enforced: true, confidence: 'high' });
50
+ if (protections.length)
51
+ out.gates.push({ id: `${v.file}:${line}:APP_GUARD:${cls}`, kind: 'guard', framework: 'nest', file: v.file, line, paths: ['*'], methods: [], protections, confidence: 'medium' });
52
+ }
53
+ // Module middleware: consumer.apply(AuthMiddleware).forRoutes('path', { path: 'x', method: RequestMethod.GET }). One gate per route spec.
54
+ for (const m of masked.matchAll(/\.\s*apply\s*\(([^)]*)\)/g)) {
55
+ const statementEnd = masked.indexOf(';', m.index);
56
+ const chain = text.slice(m.index, statementEnd < 0 ? m.index + 600 : statementEnd);
57
+ const fr = /\.\s*forRoutes\s*\(/.exec(chain);
58
+ if (!fr)
59
+ continue;
60
+ const names = [...m[1].matchAll(/[A-Za-z_$][\w$]*/g)].map((x) => x[0]).filter((x) => !/^(?:new|function|req|res|next)$/.test(x));
61
+ const line = v.lines.at(m.index);
62
+ const protections = [];
63
+ for (const n of names) {
64
+ if (/auth|jwt|session|firebase|supabase|login|token/i.test(n))
65
+ protections.push({ kind: 'session_read', scope: 'middleware', file: v.file, line, via: `module middleware ${n}`, enforced: null, confidence: 'medium' });
66
+ if (/role|permission|admin|abac|casl/i.test(n))
67
+ protections.push({ kind: 'role_check', scope: 'middleware', file: v.file, line, via: `module middleware ${n}`, enforced: null, confidence: 'medium' });
68
+ if (/throttl|rate/i.test(n))
69
+ protections.push({ kind: 'rate_limit', scope: 'middleware', file: v.file, line, via: `module middleware ${n}`, enforced: null, confidence: 'medium' });
70
+ }
71
+ if (!protections.length)
72
+ continue;
73
+ const open = m.index + chain.indexOf('forRoutes') + 'forRoutes'.length;
74
+ const args = text.slice(text.indexOf('(', open - 1) + 1, text.indexOf(')', open - 1 + chain.slice(chain.indexOf('forRoutes')).length)).trim();
75
+ const specs = [];
76
+ for (const o of args.matchAll(/\{\s*path\s*:\s*['"`]([^'"`]*)['"`]\s*,\s*method\s*:\s*RequestMethod\.(\w+)\s*\}/g))
77
+ specs.push({ path: o[1], methods: o[2] === 'ALL' ? [] : [o[2]] });
78
+ const rest = args.replace(/\{[^}]*\}/g, ' ');
79
+ for (const sx of rest.matchAll(/['"`]([^'"`]*)['"`]/g))
80
+ specs.push({ path: sx[1], methods: [] });
81
+ if (!specs.length && /^\s*\*\s*$|['"`]\*['"`]/.test(args))
82
+ specs.push({ path: '*', methods: [] });
83
+ specs.forEach((sp, i) => {
84
+ const star = sp.path.replace(/\/?\*.*$/, '');
85
+ const gp = sp.path === '*' ? '*' : joinPath('/', star);
86
+ out.gates.push({ id: `${v.file}:${line}:forRoutes:${i}`, kind: 'middleware', framework: 'nest', file: v.file, line, paths: [gp], methods: sp.methods, protections, confidence: 'medium' });
87
+ });
88
+ }
89
+ for (const m of masked.matchAll(/useGlobalPipes\s*\(\s*new\s+ValidationPipe/g)) {
90
+ const line = v.lines.at(m.index);
91
+ const g = { id: `${v.file}:${line}:ValidationPipe`, kind: 'global_pipe', framework: 'nest', file: v.file, line, paths: ['*'], methods: [], protections: [{ kind: 'input_validation', scope: 'global', file: v.file, line, via: 'global ValidationPipe', enforced: true, confidence: 'medium' }], confidence: 'medium' };
92
+ out.gates.push(g);
93
+ }
94
+ for (const cm of masked.matchAll(/(?<![\w$])class\s+([A-Za-z_$][\w$]*)\b/g)) {
95
+ const classKw = cm.index;
96
+ let ds = classKw;
97
+ for (let k = classKw - 1; k >= 0 && classKw - k < 900; k--) {
98
+ const c = masked[k];
99
+ if (c === '}' || c === ';')
100
+ break;
101
+ ds = k;
102
+ }
103
+ const classDeco = text.slice(ds, classKw);
104
+ const bodyOpen = masked.indexOf('{', classKw);
105
+ if (bodyOpen < 0)
106
+ continue;
107
+ const bodyClose = closeOf(masked, bodyOpen);
108
+ if (bodyClose < 0)
109
+ continue;
110
+ const isController = /@Controller\s*\(/.test(classDeco);
111
+ const isResolver = /@Resolver\s*\(/.test(classDeco);
112
+ const prefix = isController ? (/@Controller\s*\(\s*(?:['"`]([^'"`]*)['"`]|\{[^}]*?path\s*:\s*['"`]([^'"`]*)['"`])/.exec(classDeco)?.slice(1).find((x) => x !== undefined) ?? '') : '';
113
+ const body = masked.slice(bodyOpen, bodyClose);
114
+ const verbRe = isController ? NEST_VERBS : NEST_OTHER;
115
+ verbRe.lastIndex = 0;
116
+ const hits = [...body.matchAll(isController ? NEST_VERBS : new RegExp(NEST_OTHER.source, 'g'))];
117
+ if (!hits.length)
118
+ continue;
119
+ for (const h of hits) {
120
+ const at = bodyOpen + h.index;
121
+ const decoOpen = at + h[0].length - 1;
122
+ const decoClose = closeOf(masked, decoOpen);
123
+ if (decoClose < 0)
124
+ continue;
125
+ // Skip further decorators, then read the method name and signature.
126
+ let i = decoClose;
127
+ for (;;) {
128
+ const nxt = /^\s*@[\w$.]+\s*(?:\()?/.exec(masked.slice(i, i + 80));
129
+ if (!nxt)
130
+ break;
131
+ const o = i + nxt[0].length - 1;
132
+ if (masked[o] === '(') {
133
+ const c = closeOf(masked, o);
134
+ if (c < 0)
135
+ break;
136
+ i = c;
137
+ }
138
+ else
139
+ i += nxt[0].length;
140
+ }
141
+ const sig = /^\s*(?:(?:public|private|protected|async|static|override)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^>(]*>)?\s*\(/.exec(masked.slice(i, i + 200));
142
+ if (!sig)
143
+ continue;
144
+ const parenIdx = i + sig[0].length - 1;
145
+ const f = jsFunction(masked, parenIdx, true);
146
+ if (!f)
147
+ continue;
148
+ let ms = at;
149
+ for (let k = at - 1; k > bodyOpen && at - k < 700; k--) {
150
+ const c = masked[k];
151
+ if (c === '}' || c === ';' || c === '{')
152
+ break;
153
+ ms = k;
154
+ }
155
+ const methodDeco = text.slice(ms, at + (decoClose - at));
156
+ const argText = text.slice(decoOpen + 1, decoClose - 1);
157
+ const litPath = /^\s*['"`]([^'"`]*)['"`]/.exec(argText)?.[1] ?? '';
158
+ const deco = [{ view: v, start: ds, end: classKw, scope: 'router' }, { view: v, start: ms, end: i, scope: 'handler' }];
159
+ const name = sig[1];
160
+ const params = paramNames(masked, parenIdx);
161
+ let kind = 'http_route';
162
+ let method = h[1].toUpperCase();
163
+ let path = null;
164
+ if (isController) {
165
+ method = h[1] === 'All' ? 'ANY' : h[1].toUpperCase();
166
+ path = joinPath('/' + prefix, litPath);
167
+ if (path === '')
168
+ path = '/';
169
+ }
170
+ else if (/^(?:Query|Mutation|Subscription|ResolveField)$/.test(h[1])) {
171
+ kind = 'graphql_resolver';
172
+ method = h[1] === 'ResolveField' ? 'FIELD' : h[1].toUpperCase();
173
+ path = name;
174
+ }
175
+ else if (/^(?:MessagePattern|EventPattern)$/.test(h[1])) {
176
+ kind = 'message_consumer';
177
+ method = null;
178
+ path = litPath || argText.trim().slice(0, 60) || name;
179
+ }
180
+ else if (h[1] === 'SubscribeMessage') {
181
+ kind = 'websocket';
182
+ method = null;
183
+ path = litPath || name;
184
+ }
185
+ else {
186
+ kind = 'job';
187
+ method = null;
188
+ path = litPath || (argText.trim().slice(0, 40) || name);
189
+ }
190
+ if (!isController && !isResolver && kind === 'graphql_resolver')
191
+ continue;
192
+ const e = makeEntry(repo, { kind, framework: 'nest', file: v.file, line: v.lines.at(at), method, path, name, confidence: 'high', handlerView: v, spec: { start: f.start, end: f.end, seeds: params, decorators: deco, extraCalls: [], returnsJson: true }, tags: PUBLIC_MARK.test(classDeco) || PUBLIC_MARK.test(methodDeco) ? ['public'] : [] });
193
+ // Parameter decorators are request reads; a typed @Body() is checked against class-validator decorators on the DTO.
194
+ const sigText = text.slice(parenIdx, f.bodyStart);
195
+ const reads = [['body', /@Body\s*\(/], ['query', /@Query\s*\(/], ['params', /@Param\s*\(/], ['headers', /@Headers?\s*\(/], ['file', /@(?:UploadedFiles?|UploadedFile)\s*\(/]];
196
+ for (const [source, re] of reads) {
197
+ const rm = re.exec(sigText);
198
+ if (rm && !e.reads.some((r) => r.source === source))
199
+ e.reads.push({ source, line: v.lines.at(parenIdx + rm.index) });
200
+ }
201
+ if (e.reads.some((r) => r.source === 'file') && !e.tags.includes('upload'))
202
+ e.tags = [...e.tags, 'upload'].sort();
203
+ if (/@(?:UseInterceptors\s*\(\s*(?:FileInterceptor|FilesInterceptor))/.test(methodDeco) && !e.reads.some((r) => r.source === 'file'))
204
+ e.reads.push({ source: 'file', line: e.line });
205
+ for (const dm of sigText.matchAll(/@Body\s*\([^)]*\)\s*[A-Za-z_$][\w$]*\s*:\s*([A-Z][\w$]*)/g)) {
206
+ if (dtoValidated(repo, dm[1]))
207
+ e.protections.push({ kind: 'input_validation', scope: 'handler', file: v.file, line: v.lines.at(parenIdx + dm.index), via: `DTO ${dm[1]}`, enforced: null, confidence: 'medium' });
208
+ }
209
+ e.protections.sort((a, b) => a.line - b.line || (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0) || (a.via < b.via ? -1 : a.via > b.via ? 1 : 0));
210
+ e.reads.sort((a, b) => (a.source < b.source ? -1 : 1));
211
+ out.entries.push(e);
212
+ }
213
+ }
214
+ return out;
215
+ }
216
+ const JOB_CALL = /(?<![\w$])(cron\.schedule|schedule\.scheduleJob|scheduleJob|new\s+CronJob|agenda\.define|new\s+Worker|\w*[qQ]ueue\w*\.process|boss\.work|inngest\.createFunction|\w+\.addRepeatableJob|setInterval)\s*\(/g;
217
+ export function extractJobs(repo, v) {
218
+ const out = empty();
219
+ if (!/cron|schedule|agenda|Worker|[qQ]ueue|boss|inngest/.test(v.text))
220
+ return out;
221
+ for (const m of v.masked.matchAll(JOB_CALL)) {
222
+ if (m[1] === 'setInterval')
223
+ continue;
224
+ const open = m.index + m[0].length - 1;
225
+ const args = splitArgs(v.masked, open);
226
+ const first = args[0];
227
+ const lit = first && /^['"`]/.test(v.masked[first.start]) ? v.text.slice(first.start + 1, first.end - 1) : null;
228
+ const fa = args.map((a) => ({ a, r: resolveFunction(repo, v, a.start, a.end) })).find((x) => x.r);
229
+ if (!fa?.r)
230
+ continue;
231
+ const framework = /cron|schedule/i.test(m[1]) ? 'node-cron' : /Worker|process|work/.test(m[1]) ? 'queue' : m[1];
232
+ out.entries.push(makeEntry(repo, { kind: 'job', framework, file: v.file, line: v.lines.at(m.index), method: null, path: lit, name: lit && !/[\s*]/.test(lit) ? lit : null, confidence: 'high', handlerView: fa.r.view, spec: { start: fa.r.start, end: fa.r.end, seeds: fa.r.params, decorators: [], returnsJson: false } }));
233
+ }
234
+ return out;
235
+ }
236
+ const TOOL_OBJECT = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?=\s*\{/g;
237
+ const TOOLISH = /tool|function|handler|action|capabilit/i;
238
+ export function extractAiTools(repo, v) {
239
+ const out = empty();
240
+ if (!/tool|function_call|mcp|[aA]gent|llm|openai|anthropic|generateText|assistant/.test(v.text))
241
+ return out;
242
+ const seen = new Set();
243
+ const push = (name, f, line, framework) => {
244
+ if (seen.has(f.start))
245
+ return;
246
+ seen.add(f.start);
247
+ out.entries.push(makeEntry(repo, { kind: 'ai_tool', framework, file: v.file, line, method: null, path: null, name, confidence: 'medium', handlerView: v, spec: { start: f.start, end: f.end, seeds: paramsOf(v.masked, f).slice(0, 1), decorators: [], returnsJson: false } }));
248
+ };
249
+ // 1. An object of functions named like tools: { read_note: (args) => ..., send: async (args) => ... }
250
+ for (const m of v.masked.matchAll(TOOL_OBJECT)) {
251
+ if (!TOOLISH.test(m[1]) || !/\b(?:tool|function|openai|anthropic|llm|assistant|agent|model)/i.test(v.text))
252
+ continue;
253
+ const open = m.index + m[0].length - 1;
254
+ const close = closeOf(v.masked, open);
255
+ if (close < 0)
256
+ continue;
257
+ for (const seg of splitArgs(v.masked, open)) {
258
+ const head = /^(?:async\s+)?\[?['"]?([\w$-]+)['"]?\]?\s*(:|\()/.exec(v.text.slice(seg.start, seg.end).replace(/^async\s+/, 'async '));
259
+ if (!head)
260
+ continue;
261
+ const name = head[1];
262
+ let at = seg.start + head[0].length - 1;
263
+ if (head[2] === ':')
264
+ at = seg.start + head[0].length;
265
+ const f = jsFunction(v.masked, head[2] === '(' ? at : at);
266
+ if (f && f.end <= seg.end + 1)
267
+ push(name, f, v.lines.at(seg.start), 'ai-tools');
268
+ }
269
+ }
270
+ // 2. tool({ description, parameters, execute })
271
+ for (const m of v.masked.matchAll(/(?<![\w$])tool\s*\(\s*\{/g)) {
272
+ const open = v.masked.indexOf('{', m.index);
273
+ for (const seg of splitArgs(v.masked, open)) {
274
+ const ex = /^execute\s*(:|\()/.exec(v.masked.slice(seg.start, seg.end));
275
+ if (!ex)
276
+ continue;
277
+ const f = jsFunction(v.masked, seg.start + (ex[1] === ':' ? ex[0].length : ex[0].length - 1));
278
+ if (!f)
279
+ continue;
280
+ const before = v.text.slice(Math.max(0, m.index - 80), m.index);
281
+ const nm = /([A-Za-z_$][\w$]*)\s*(?::|=)\s*$/.exec(before)?.[1] ?? null;
282
+ push(nm, f, v.lines.at(m.index), 'ai-sdk');
283
+ }
284
+ }
285
+ // 3. MCP: server.tool('name', schema, handler)
286
+ for (const m of v.masked.matchAll(/\.\s*(?:tool|registerTool)\s*\(\s*(['"])/g)) {
287
+ const open = v.masked.indexOf('(', m.index);
288
+ const args = splitArgs(v.masked, open);
289
+ const nm = v.text.slice(args[0].start + 1, args[0].end - 1);
290
+ const fa = args.map((a) => jsFunction(v.masked, a.start)).filter((x) => x).pop();
291
+ if (fa)
292
+ push(nm, fa, v.lines.at(m.index), 'mcp');
293
+ }
294
+ return out;
295
+ }
@@ -0,0 +1,292 @@
1
+ import { analyze } from './analyze.js';
2
+ import { empty, joinPath, makeEntry, normPath, paramNames } from './entry.js';
3
+ import { closeOf, jsFunction, splitArgs } from './lex.js';
4
+ import { ADMIN_PATH } from './vocab.js';
5
+ const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
6
+ export function resolveFunction(repo, v, at, limit) {
7
+ const m = v.masked;
8
+ const direct = jsFunction(m, at);
9
+ if (direct && direct.end <= limit + 1)
10
+ return { view: v, start: direct.start, end: direct.end, wrapper: null, resolved: false, params: paramsOf(m, direct) };
11
+ const call = /^\s*([A-Za-z_$][\w$.]*)\s*(?:<[^>(]*>)?\s*\(/.exec(m.slice(at, limit));
12
+ if (call) {
13
+ const open = at + call[0].length - 1;
14
+ const args = splitArgs(m, open);
15
+ for (const a of args) {
16
+ const f = jsFunction(m, a.start);
17
+ if (f && f.end <= a.end + 1)
18
+ return { view: v, start: f.start, end: f.end, wrapper: { name: call[1], from: at, to: a.start }, resolved: false, params: paramsOf(m, f) };
19
+ }
20
+ for (const a of args) {
21
+ const id = /^([A-Za-z_$][\w$]*)(?:\s*\([\s\S]*\))?$/.exec(m.slice(a.start, a.end));
22
+ if (id) {
23
+ const r = repo.defs('js', id[1]).filter((d) => d.view.file === v.file).concat(repo.defs('js', id[1]))[0];
24
+ if (r)
25
+ return { view: r.view, start: r.start, end: r.end, wrapper: { name: call[1], from: at, to: a.start }, resolved: true, params: paramsOf(r.view.masked, { start: r.start, end: r.end, bodyStart: r.start }), defName: id[1] };
26
+ }
27
+ }
28
+ return null;
29
+ }
30
+ const id = /^\s*([A-Za-z_$][\w$]*)\s*[;,)]?\s*$/.exec(m.slice(at, limit)) ?? /^\s*(?:[A-Za-z_$][\w$]*\s*\.\s*)*([A-Za-z_$][\w$]*)\s*[;,)]?\s*$/.exec(m.slice(at, limit));
31
+ if (id) {
32
+ const defs = repo.defs('js', id[1]);
33
+ const r = defs.find((d) => d.view.file === v.file) ?? (defs.length === 1 ? defs[0] : null);
34
+ if (r)
35
+ return { view: r.view, start: r.start, end: r.end, wrapper: null, resolved: true, params: paramsOf(r.view.masked, { start: r.start, end: r.end, bodyStart: r.start }), defName: id[1] };
36
+ }
37
+ return null;
38
+ }
39
+ export function paramsOf(masked, f) {
40
+ const head = masked.slice(f.start, f.bodyStart);
41
+ const open = head.indexOf('(');
42
+ if (open >= 0 && (head.indexOf('=>') < 0 || open < head.indexOf('=>')))
43
+ return paramNames(masked, f.start + open);
44
+ const single = /^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/.exec(head);
45
+ return single ? [single[1]] : [];
46
+ }
47
+ export const nextRoutePath = (file, strip) => {
48
+ const m = /(?:^|\/)(?:src\/)?app\/(.*)$/.exec(file);
49
+ if (!m)
50
+ return null;
51
+ const segs = m[1].replace(strip, '').split('/').filter((s) => s && !/^\(.*\)$/.test(s) && !s.startsWith('@'));
52
+ return normPath('/' + segs.join('/'));
53
+ };
54
+ // Exported names in a file with where their value starts: export function X, export const X = ..., export { a as X }.
55
+ export function exportedFunctions(repo, v) {
56
+ const m = v.masked;
57
+ const out = [];
58
+ for (const x of m.matchAll(/\bexport\s+(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g)) {
59
+ const at = x.index + (/\bexport\s+(?:default\s+)?/.exec(x[0])[0].length);
60
+ const f = jsFunction(m, at);
61
+ if (f)
62
+ out.push({ exportName: x[1], r: { view: v, start: f.start, end: f.end, wrapper: null, resolved: false, params: paramsOf(m, f) }, line: v.lines.at(x.index), at });
63
+ }
64
+ for (const x of m.matchAll(/\bexport\s+const\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?=\s*/g)) {
65
+ const at = x.index + x[0].length;
66
+ const limit = statementLimit(m, at);
67
+ const r = resolveFunction(repo, v, at, limit);
68
+ if (r)
69
+ out.push({ exportName: x[1], r, line: v.lines.at(x.index), at });
70
+ }
71
+ for (const x of m.matchAll(/\bexport\s*\{([^}]*)\}/g)) {
72
+ for (const part of x[1].split(',')) {
73
+ const [local, alias] = part.trim().split(/\s+as\s+/);
74
+ if (!local)
75
+ continue;
76
+ const defs = repo.defs('js', local);
77
+ const d = defs.find((q) => q.view.file === v.file);
78
+ if (d)
79
+ out.push({ exportName: alias ?? local, r: { view: d.view, start: d.start, end: d.end, wrapper: null, resolved: false, params: paramsOf(d.view.masked, { start: d.start, end: d.end, bodyStart: d.start }) }, line: v.lines.at(x.index), at: x.index });
80
+ }
81
+ }
82
+ return out;
83
+ }
84
+ function statementLimit(masked, from) {
85
+ let depth = 0;
86
+ for (let i = from; i < masked.length; i++) {
87
+ const c = masked[i];
88
+ if (c === '(' || c === '[' || c === '{')
89
+ depth++;
90
+ else if (c === ')' || c === ']' || c === '}') {
91
+ if (depth === 0)
92
+ return i;
93
+ depth--;
94
+ }
95
+ else if (c === ';' && depth === 0)
96
+ return i;
97
+ else if (c === '\n' && depth === 0 && /\n\s*(?:export|const|let|var|function|async|import|type|interface|\/\/)/.test(masked.slice(i, i + 40)))
98
+ return i;
99
+ }
100
+ return masked.length;
101
+ }
102
+ function spec(r, decorators, seeds, extra = []) {
103
+ const deco = decorators ?? [];
104
+ return { start: r.start, end: r.end, seeds, decorators: deco, extraCalls: extra, returnsJson: true };
105
+ }
106
+ const wrapperDeco = (v, r) => (r.wrapper ? [{ view: v, start: r.wrapper.from, end: r.wrapper.to, scope: 'wrapper' }] : []);
107
+ export function extractNext(repo, v) {
108
+ const out = empty();
109
+ const file = v.file;
110
+ const text = v.text;
111
+ // App router route handlers.
112
+ if (/(?:^|\/)(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/.test(file)) {
113
+ const path = nextRoutePath(file, /\/?route\.[cm]?[jt]sx?$/);
114
+ for (const e of exportedFunctions(repo, v)) {
115
+ if (!METHODS.includes(e.exportName))
116
+ continue;
117
+ const r = e.r;
118
+ const seeds = r.params.length ? r.params : ['req', 'request', 'params'];
119
+ out.entries.push(makeEntry(repo, { kind: 'http_route', framework: 'next-app', file, line: e.line, method: e.exportName, path, name: e.exportName, confidence: 'high', handlerView: r.view, spec: spec(r, wrapperDeco(v, r), [...seeds, 'params', 'searchParams'], r.wrapper ? [r.wrapper.name.split('.').pop()] : []) }));
120
+ }
121
+ }
122
+ // App router pages.
123
+ if (/(?:^|\/)(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/.test(file)) {
124
+ const path = nextRoutePath(file, /\/?page\.[cm]?[jt]sx?$/);
125
+ const ex = defaultExport(repo, v);
126
+ if (ex) {
127
+ const r = ex.r;
128
+ out.entries.push(makeEntry(repo, { kind: 'page', framework: 'next-app', file, line: v.lines.at(r.start), method: 'GET', path, name: ex.exportName, confidence: 'high', handlerView: r.view, spec: spec(r, [], ['params', 'searchParams', ...r.params]) }));
129
+ }
130
+ }
131
+ // Pages router API routes.
132
+ if (/(?:^|\/)(?:src\/)?pages\/api\/.+\.[cm]?[jt]sx?$/.test(file)) {
133
+ const path = normPath('/api/' + (/pages\/api\/(.*)$/.exec(file)[1]).replace(/\.[cm]?[jt]sx?$/, '').replace(/\/?index$/, ''));
134
+ const ex = defaultExport(repo, v);
135
+ if (ex) {
136
+ const r = ex.r;
137
+ const methods = [...new Set([...v.text.slice(r.start, r.end).matchAll(/\bmethod\s*(?:===?|!==?)\s*['"](\w+)['"]|\bcase\s+['"](GET|POST|PUT|PATCH|DELETE)['"]/g)].map((x) => (x[1] ?? x[2]).toUpperCase()))].filter((x) => METHODS.includes(x)).sort();
138
+ for (const method of methods.length ? methods : ['ANY']) {
139
+ out.entries.push(makeEntry(repo, { kind: 'http_route', framework: 'next-pages', file, line: v.lines.at(r.start), method, path, name: ex.exportName, confidence: 'high', handlerView: r.view, spec: spec(r, wrapperDeco(v, r), r.params.length ? r.params : ['req'], r.wrapper ? [r.wrapper.name.split('.').pop()] : []) }));
140
+ }
141
+ }
142
+ }
143
+ // Server actions: a "use server" file, or the directive inside a function.
144
+ const fileDirective = /^\s*(?:\/\/[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*)*['"]use server['"]/.test(text);
145
+ if (fileDirective) {
146
+ for (const e of exportedFunctions(repo, v)) {
147
+ const r = e.r;
148
+ out.entries.push(makeEntry(repo, { kind: 'server_action', framework: 'next-app', file, line: v.lines.at(r.start), method: 'POST', path: null, name: e.exportName, confidence: 'high', handlerView: r.view, spec: spec(r, wrapperDeco(v, r), r.params, r.wrapper ? [r.wrapper.name.split('.').pop()] : []) }));
149
+ }
150
+ }
151
+ else if (/['"]use server['"]/.test(text)) {
152
+ for (const x of v.masked.matchAll(/(?:\basync\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(|\b(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=\s*async\s*\(/g)) {
153
+ const at = x.index;
154
+ const f = jsFunction(v.masked, at);
155
+ if (!f || !/^\s*\{\s*['"]use server['"]/.test(text.slice(f.bodyStart, f.bodyStart + 60)))
156
+ continue;
157
+ out.entries.push(makeEntry(repo, { kind: 'server_action', framework: 'next-app', file, line: v.lines.at(at), method: 'POST', path: null, name: x[1] ?? x[2], confidence: 'high', handlerView: v, spec: { start: f.start, end: f.end, seeds: paramsOf(v.masked, f), decorators: [], returnsJson: true } }));
158
+ }
159
+ }
160
+ // Middleware (a gate, not an entry point).
161
+ if (/(?:^|\/)(?:src\/)?(?:middleware|proxy)\.[cm]?[jt]s$/.test(file)) {
162
+ const named = exportedFunctions(repo, v).find((e) => e.exportName === 'middleware' || e.exportName === 'proxy');
163
+ const dflt = named ? null : defaultExport(repo, v);
164
+ const fn = named ? { r: named.r } : dflt ? { r: dflt.r } : null;
165
+ if (fn) {
166
+ const a = analyze(v, spec(fn.r, wrapperDeco(v, fn.r), fn.r.params.length ? fn.r.params : ['req', 'request']), repo.helpers('js'));
167
+ const matcher = /\bmatcher\s*:\s*(\[[^\]]*\]|['"][^'"]*['"])/.exec(text);
168
+ const matcherPaths = matcher ? [...matcher[1].matchAll(/['"]([^'"]*)['"]/g)].map((x) => gatePrefix(x[1])) : [];
169
+ // A check inside "if (pathname.startsWith('/admin'))" covers only those prefixes, not the whole matcher.
170
+ const blocks = [...v.masked.slice(fn.r.start, fn.r.end).matchAll(/\bif\s*\(/g)].map((x) => {
171
+ const open = fn.r.start + x.index + x[0].length - 1;
172
+ const condEnd = closeOf(v.masked, open);
173
+ if (condEnd < 0)
174
+ return null;
175
+ const prefixes = [...text.slice(open, condEnd).matchAll(/startsWith\(\s*['"](\/[^'"]*)['"]/g)].map((y) => normPath(y[1].replace(/\/$/, '') || '/'));
176
+ const b = v.masked.indexOf('{', condEnd);
177
+ const bEnd = b < 0 ? -1 : closeOf(v.masked, b);
178
+ return prefixes.length && b >= 0 && bEnd > 0 && /^\s*\{/.test(v.masked.slice(condEnd, b + 1)) ? { start: b, end: bEnd, prefixes } : null;
179
+ }).filter((x) => x !== null);
180
+ const groups = new Map();
181
+ const blockAt = (pos) => blocks.filter((b) => pos >= b.start && pos <= b.end).sort((x, y) => (x.end - x.start) - (y.end - y.start))[0];
182
+ for (const p of a.protections.filter((q) => q.kind !== 'owner_filter')) {
183
+ const at = v.lines.start(p.line);
184
+ let prefixes = blockAt(at)?.prefixes ?? null;
185
+ if (!prefixes) {
186
+ // The value is stored in a variable and tested later: use the blocks that test it, when all of them are inside one.
187
+ const lineText = text.slice(at, text.indexOf('\n', at) < 0 ? text.length : text.indexOf('\n', at));
188
+ const name = /(?:const|let|var)\s+(\w+)\s*=/.exec(lineText)?.[1];
189
+ if (name) {
190
+ const uses = [...v.masked.slice(fn.r.start, fn.r.end).matchAll(new RegExp(`(?<![\\w$.])${name}\\b`, 'g'))].map((x) => fn.r.start + x.index).filter((pos) => v.lines.at(pos) !== p.line);
191
+ const inBlocks = uses.map((pos) => blockAt(pos));
192
+ if (uses.length && inBlocks.every((b) => b))
193
+ prefixes = [...new Set(inBlocks.flatMap((b) => b.prefixes))];
194
+ }
195
+ }
196
+ const key = prefixes ? [...new Set(prefixes)].sort().join('\u0000') : '*';
197
+ groups.set(key, [...(groups.get(key) ?? []), { ...p, scope: 'middleware' }]);
198
+ }
199
+ for (const [key, protections] of [...groups.entries()].sort()) {
200
+ const paths = key === '*' ? (matcherPaths.length ? [...new Set(matcherPaths)].sort() : ['*']) : key.split('\u0000');
201
+ const gate = {
202
+ id: `${file}:${v.lines.at(fn.r.start)}:middleware:${key === '*' ? 'all' : paths.join(',')}`, kind: 'middleware', framework: 'next-app', file, line: v.lines.at(fn.r.start),
203
+ paths, methods: [], protections, confidence: 'medium',
204
+ };
205
+ out.gates.push(gate);
206
+ }
207
+ }
208
+ }
209
+ // Supabase edge functions.
210
+ const edge = /(?:^|\/)supabase\/functions\/([^/_][^/]*)\/index\.[cm]?[jt]sx?$/.exec(file);
211
+ if (edge) {
212
+ const serve = /\b(?:Deno\.)?serve\s*\(/.exec(v.masked);
213
+ if (serve) {
214
+ const open = serve.index + serve[0].length - 1;
215
+ const args = splitArgs(v.masked, open);
216
+ const fa = args.map((a) => ({ a, r: resolveFunction(repo, v, a.start, a.end) })).find((x) => x.r);
217
+ if (fa?.r) {
218
+ const e = makeEntry(repo, { kind: 'http_route', framework: 'supabase-edge', file, line: v.lines.at(serve.index), method: 'ANY', path: `/functions/v1/${edge[1]}`, name: edge[1], confidence: 'high', handlerView: fa.r.view, spec: spec(fa.r, [], fa.r.params.length ? fa.r.params : ['req', 'request']) });
219
+ const cfg = repo.ctx.text('supabase/config.toml');
220
+ const sec = new RegExp(`\\[functions\\.${edge[1].replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&')}\\]([^\\[]*)`).exec(cfg);
221
+ const off = sec ? /verify_jwt\s*=\s*false/.test(sec[1]) : false;
222
+ if (!off)
223
+ e.protections.push({ kind: 'session_read', scope: 'global', file: cfg ? 'supabase/config.toml' : file, line: 1, via: 'supabase verify_jwt (default on)', enforced: true, confidence: cfg ? 'high' : 'medium' });
224
+ e.protections.sort((x, y) => x.line - y.line || (x.kind < y.kind ? -1 : 1));
225
+ out.entries.push(e);
226
+ }
227
+ }
228
+ }
229
+ // tRPC procedures.
230
+ if (/[pP]rocedure\b/.test(v.masked) && /trpc|Procedure/.test(v.imports + v.text.slice(0, 3000))) {
231
+ for (const x of v.masked.matchAll(/(?<![.\w$])([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*[pP]rocedure)\b/g)) {
232
+ let i = x.index + x[0].length;
233
+ let verb = null;
234
+ let handler = null;
235
+ const chain = [];
236
+ for (let guard = 0; guard < 12; guard++) {
237
+ while (/\s/.test(v.masked[i] ?? ''))
238
+ i++;
239
+ if (v.masked[i] !== '.')
240
+ break;
241
+ const call = /^\.\s*(\w+)\s*\(/.exec(v.masked.slice(i));
242
+ if (!call)
243
+ break;
244
+ const open = i + call[0].length - 1;
245
+ const close = closeOf(v.masked, open);
246
+ if (close < 0)
247
+ break;
248
+ chain.push(call[1]);
249
+ if (['query', 'mutation', 'subscription'].includes(call[1])) {
250
+ verb = call[1];
251
+ const a = splitArgs(v.masked, open)[0];
252
+ handler = a ? jsFunction(v.masked, a.start) : null;
253
+ i = close;
254
+ break;
255
+ }
256
+ i = close;
257
+ }
258
+ if (!verb || !handler)
259
+ continue;
260
+ const procName = x[2];
261
+ const deco = [{ view: v, start: x.index + x[1].length, end: handler.start, scope: 'router' }];
262
+ const e = makeEntry(repo, { kind: 'rpc', framework: 'trpc', file, line: v.lines.at(x.index), method: verb.toUpperCase(), path: x[1], name: x[1], confidence: 'high', handlerView: v, spec: { start: handler.start, end: handler.end, seeds: ['input', 'ctx', ...paramsOf(v.masked, handler)], decorators: deco, returnsJson: true } });
263
+ if (/protected|auth|private|member|user|admin|session|staff/i.test(procName))
264
+ e.protections.push({ kind: 'session_read', scope: 'router', file, line: e.line, via: `procedure ${procName}`, enforced: true, confidence: 'medium' });
265
+ if (/admin|staff|owner/i.test(procName) || ADMIN_PATH.test(procName))
266
+ e.protections.push({ kind: 'role_check', scope: 'router', file, line: e.line, via: `procedure ${procName}`, enforced: true, confidence: 'medium' });
267
+ if (chain.includes('input'))
268
+ e.protections.push({ kind: 'input_validation', scope: 'router', file, line: e.line, via: 'trpc .input()', enforced: true, confidence: 'high' });
269
+ e.protections.sort((a, b) => a.line - b.line || (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0) || (a.via < b.via ? -1 : 1));
270
+ out.entries.push(e);
271
+ }
272
+ }
273
+ return out;
274
+ }
275
+ function defaultExport(repo, v) {
276
+ const m = v.masked;
277
+ const x = /\bexport\s+default\s+/.exec(m);
278
+ if (!x)
279
+ return null;
280
+ const at = x.index + x[0].length;
281
+ const limit = statementLimit(m, at);
282
+ const direct = jsFunction(m, at);
283
+ const named = /^(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/.exec(m.slice(at, at + 80));
284
+ const r = direct ? { view: v, start: direct.start, end: direct.end, wrapper: null, resolved: false, params: paramsOf(m, direct) } : resolveFunction(repo, v, at, limit);
285
+ return r ? { exportName: named?.[1] ?? null, r } : null;
286
+ }
287
+ // A middleware matcher such as "/admin/:path*" or "/api/(.*)" as the path prefix it covers.
288
+ function gatePrefix(matcher) {
289
+ const p = matcher.replace(/\/?(?::\w+\*?|\(\.\*\)|\*)$/g, '').replace(/\/\(\.\*\)$/, '');
290
+ return normPath(p === '' ? '*' : p.startsWith('/') ? p : `/${p}`);
291
+ }
292
+ export { joinPath };