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,190 @@
1
+ import { testCodeReason } from '../report/test-code.js';
2
+ import { empty, makeEntry, normPath } from './entry.js';
3
+ import { splitArgs } from './lex.js';
4
+ import { exportedFunctions, resolveFunction } from './js-next.js';
5
+ const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
6
+ const SOURCE_EXT = /\.[cm]?[jt]sx?$/;
7
+ // Session reads in mobile code: auth hooks and contexts, provider SDK calls, secure storage of a token.
8
+ const EXPO_SESSION = [
9
+ { re: /\b(?:useAuth|isSignedIn|useSession|useUser|useAuthContext|useAuthState|useSupabaseSession|useConvexAuth|useKindeAuth|useAuth0)\b/, via: 'auth hook', conf: 'medium' },
10
+ { re: /\bsupabase\.auth\.(?:getSession|getUser|onAuthStateChange)\b|\bonAuthStateChanged\s*\(|\bgetAuth\s*\(|\bfirebase\.auth\(\)|\bauth\(\)\.currentUser|\bClerkProvider\b|\bSignedIn\b|\bSignedOut\b/, via: 'auth provider', conf: 'high' },
11
+ { re: /\b(?:SecureStore|AsyncStorage|storage)\.(?:getItem|getItemAsync|get|getString)\s*\(\s*['"][\w.-]*(?:token|session|jwt|auth)[\w.-]*['"]/i, via: 'stored token', conf: 'medium' },
12
+ { re: /\b(?:isAuthenticated|isLoggedIn|isAuthed|signedIn|loggedIn)\b/, via: 'signed in flag', conf: 'medium' },
13
+ ];
14
+ const GUARD_REDIRECT = /<Redirect\b[^>]*\bhref\b|\brouter\.(?:replace|push|navigate)\s*\(|\bnavigation\.(?:replace|navigate|reset)\s*\(|\bProtected\b[^>]*\bguard\s*=|\bredirect\s*\(/;
15
+ const GUARD_CONDITION = /\bif\s*\(\s*!\s*\(?\s*\w*(?:session|user|token|signedIn|isSignedIn|isAuthenticated|isLoggedIn|authenticated|auth)\w*|\bguard\s*=\s*\{|[?&]{2}\s*<Redirect|:\s*<Redirect/i;
16
+ // The status compared with a string, as in if (status === 'signOut'): the string is blank in the masked copy, so this reads the text.
17
+ const GUARD_STATUS = /\bif\s*\([^)]*['"](?:signOut|signedOut|unauthenticated|loggedOut|logged_out|anonymous|guest)['"]/i;
18
+ const PUBLIC_GROUP = /\((?:auth|public|login|sign-?in|sign-?up|onboarding|welcome|landing|guest|unauth\w*)\)/i;
19
+ function roots(repo) {
20
+ const out = [];
21
+ for (const f of repo.ctx.files) {
22
+ if (!/(?:^|\/)package\.json$/.test(f) || /node_modules\//.test(f))
23
+ continue;
24
+ if (/"expo-router"|"expo"\s*:/.test(repo.ctx.text(f)))
25
+ out.push(f.replace(/package\.json$/, ''));
26
+ }
27
+ return out.sort();
28
+ }
29
+ const routePath = (rel) => {
30
+ const segs = rel.replace(SOURCE_EXT, '').split('/').filter((s) => s && !/^\(.*\)$/.test(s) && !s.startsWith('@'));
31
+ if (segs[segs.length - 1] === 'index')
32
+ segs.pop();
33
+ return normPath('/' + segs.join('/').replace(/\[\.\.\.(\w+)\]/g, '*$1').replace(/\[(\w+)\]/g, ':$1'));
34
+ };
35
+ function layoutGuard(v) {
36
+ const session = EXPO_SESSION.some((s) => s.re.test(v.masked));
37
+ const redirect = GUARD_REDIRECT.exec(v.masked);
38
+ if (!session || !redirect)
39
+ return null;
40
+ const cond = GUARD_CONDITION.test(v.masked) || GUARD_STATUS.test(v.text);
41
+ if (!cond && !/\bProtected\b/.test(v.masked))
42
+ return null;
43
+ return { line: v.lines.at(redirect.index), enforced: cond ? true : null };
44
+ }
45
+ export function extractExpo(repo) {
46
+ const out = empty();
47
+ for (const root of roots(repo)) {
48
+ const appDir = [`${root}app/`, `${root}src/app/`].find((d) => repo.ctx.files.some((f) => f.startsWith(d)));
49
+ const files = repo.ctx.files.filter((f) => f.startsWith(root) && !/node_modules\//.test(f) && SOURCE_EXT.test(f) && !/\.d\.ts$/.test(f));
50
+ if (appDir) {
51
+ // Layout guards, by directory.
52
+ const guards = [];
53
+ for (const f of files) {
54
+ if (!f.startsWith(appDir) || !/(?:^|\/)_layout\.[cm]?[jt]sx?$/.test(f))
55
+ continue;
56
+ const v = repo.view(f);
57
+ const g = v ? layoutGuard(v) : null;
58
+ if (v && g)
59
+ guards.push({ dir: f.slice(0, f.lastIndexOf('/') + 1), file: f, fact: g, text: v.masked });
60
+ }
61
+ for (const f of files) {
62
+ if (!f.startsWith(appDir))
63
+ continue;
64
+ const rel = f.slice(appDir.length);
65
+ const base = rel.split('/').pop();
66
+ if (/^_layout\./.test(base) || /^\+(?:html|not-found|native-intent)\./.test(base))
67
+ continue;
68
+ const v = repo.view(f);
69
+ if (!v)
70
+ continue;
71
+ if (/\+api\.[cm]?[jt]sx?$/.test(f)) {
72
+ const path = routePath(rel.replace(/\+api(\.[cm]?[jt]sx?)$/, '$1'));
73
+ for (const e of exportedFunctions(repo, v)) {
74
+ if (!METHODS.includes(e.exportName))
75
+ continue;
76
+ const r = e.r;
77
+ const seeds = [...(r.params.length ? r.params : ['request', 'req']), 'params'];
78
+ out.entries.push(makeEntry(repo, { kind: 'http_route', framework: 'expo-api', file: f, line: e.line, method: e.exportName, path, name: e.exportName, confidence: 'high', handlerView: r.view, spec: { start: r.start, end: r.end, seeds, decorators: r.wrapper ? [{ view: v, start: r.wrapper.from, end: r.wrapper.to, scope: 'wrapper' }] : [], extraCalls: r.wrapper ? [r.wrapper.name] : [], returnsJson: true } }));
79
+ }
80
+ continue;
81
+ }
82
+ // A screen: the file under app/ with a default export that is not a layout.
83
+ const DEFAULT_EXPORT = /\bexport\s+default\b|\bexport\s*\{[^}]*(?:\bas\s+default|\bdefault\b)[^}]*\}/;
84
+ if (!DEFAULT_EXPORT.test(v.masked))
85
+ continue;
86
+ const path = routePath(rel);
87
+ const seeds = ['params', 'searchParams'];
88
+ for (const m of v.masked.matchAll(/\b(?:const|let)\s+(\{[^}]*\}|\w+)\s*=\s*use(?:Local|Global)?SearchParams\b/g))
89
+ seeds.push(...[...m[1].matchAll(/\w+/g)].map((x) => x[0]));
90
+ const dm = /\bexport\s+default\s+(?:async\s+)?function\s+(\w+)/.exec(v.masked);
91
+ const ep = makeEntry(repo, { kind: 'page', framework: 'expo-router', file: f, line: v.lines.at(dm?.index ?? Math.max(0, v.masked.search(DEFAULT_EXPORT))), method: null, path, name: dm?.[1] ?? null, confidence: 'high', handlerView: v, spec: { start: 0, end: v.text.length, seeds, returnsJson: false }, tags: ['mobile_screen'] });
92
+ const extra = [];
93
+ for (const s of EXPO_SESSION) {
94
+ const m = s.re.exec(v.masked);
95
+ if (m) {
96
+ extra.push({ kind: 'session_read', scope: 'handler', file: f, line: v.lines.at(m.index), via: s.via, enforced: null, confidence: s.conf === 'high' ? 'medium' : 'medium' });
97
+ break;
98
+ }
99
+ }
100
+ const publicGroup = PUBLIC_GROUP.test(f.slice(appDir.length));
101
+ for (const g of guards) {
102
+ if (!f.startsWith(g.dir) || publicGroup)
103
+ continue;
104
+ extra.push({ kind: 'session_read', scope: 'router', file: g.file, line: g.fact.line, via: 'expo layout guard (client side)', enforced: g.fact.enforced, confidence: 'medium' });
105
+ }
106
+ if (extra.length) {
107
+ ep.protections = [...ep.protections, ...extra].sort((a, b) => a.line - b.line || (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0) || (a.via < b.via ? -1 : 1));
108
+ if (guards.some((g) => f.startsWith(g.dir)) && !publicGroup)
109
+ ep.tags = [...new Set([...ep.tags, 'guarded'])].sort();
110
+ }
111
+ if (publicGroup)
112
+ ep.tags = [...new Set([...ep.tags, 'public'])].sort();
113
+ out.entries.push(ep);
114
+ }
115
+ }
116
+ // Deep links declared in the app config.
117
+ for (const cfg of [`${root}app.json`, `${root}app.config.json`]) {
118
+ const text = repo.ctx.text(cfg);
119
+ if (!text)
120
+ continue;
121
+ let json = null;
122
+ try {
123
+ json = JSON.parse(text);
124
+ }
125
+ catch {
126
+ json = null;
127
+ }
128
+ const expo = (json?.expo ?? json ?? {});
129
+ const lineOf = (needle) => { const i = text.indexOf(needle); return i < 0 ? 1 : text.slice(0, i).split('\n').length; };
130
+ const add = (path, name, needle, tags) => {
131
+ const line = lineOf(needle);
132
+ out.entries.push(deepLink(cfg, line, path, name, 'high', tags));
133
+ };
134
+ const scheme = expo.scheme;
135
+ for (const s of Array.isArray(scheme) ? scheme : scheme ? [scheme] : [])
136
+ if (typeof s === 'string')
137
+ add(`${s}://`, 'custom scheme', `"${s}"`, ['deep_link', 'custom_scheme']);
138
+ const ios = (expo.ios ?? {});
139
+ for (const d of Array.isArray(ios.associatedDomains) ? ios.associatedDomains : [])
140
+ if (typeof d === 'string' && d.startsWith('applinks:'))
141
+ add(`https://${d.slice(9)}/`, 'universal link', `"${d}"`, ['deep_link', 'universal_link']);
142
+ const android = (expo.android ?? {});
143
+ for (const f of android.intentFilters ?? [])
144
+ for (const d of f.data ?? [])
145
+ if (d.scheme)
146
+ add(`${d.scheme}://${d.host ?? ''}${d.pathPrefix ?? ''}`, f.autoVerify ? 'android app link' : 'android intent filter', `"${d.host ?? d.scheme}"`, ['deep_link', ...(f.autoVerify ? ['universal_link'] : ['custom_scheme'])]);
147
+ }
148
+ for (const cfg of [`${root}app.config.js`, `${root}app.config.ts`]) {
149
+ const text = repo.ctx.text(cfg);
150
+ if (!text)
151
+ continue;
152
+ for (const m of text.matchAll(/\bscheme\s*:\s*['"]([\w+.-]+)['"]/g))
153
+ out.entries.push(deepLink(cfg, text.slice(0, m.index).split('\n').length, `${m[1]}://`, 'custom scheme', 'high', ['deep_link', 'custom_scheme']));
154
+ }
155
+ // Deep links handled in code.
156
+ for (const f of files) {
157
+ const v = repo.view(f);
158
+ if (!v || !/\bLinking\b|\buseURL\b|\bprefixes\s*:/.test(v.masked))
159
+ continue;
160
+ for (const x of v.masked.matchAll(/\bLinking\.addEventListener\s*\(/g)) {
161
+ const open = x.index + x[0].length - 1;
162
+ const args = splitArgs(v.masked, open);
163
+ if (args.length < 2 || !/^['"]url['"]$/.test(v.text.slice(args[0].start, args[0].end).trim()))
164
+ continue;
165
+ const r = resolveFunction(repo, v, args[1].start, args[1].end);
166
+ const spec = r ? { start: r.start, end: r.end, seeds: r.params.length ? r.params : ['event', 'url'], returnsJson: false } : { start: x.index, end: args[args.length - 1].end, seeds: ['event', 'url'], returnsJson: false };
167
+ out.entries.push(makeEntry(repo, { kind: 'deep_link', framework: 'react-native', file: f, line: v.lines.at(x.index), method: null, path: null, name: 'Linking url listener', confidence: r ? 'high' : 'medium', handlerView: r?.view ?? v, spec, tags: ['deep_link'] }));
168
+ }
169
+ for (const x of v.masked.matchAll(/\b(?:Linking\.getInitialURL|useURL)\s*\(/g)) {
170
+ const at = x.index;
171
+ const line = v.lines.at(at);
172
+ const end = Math.min(v.text.length, v.lines.start(line + 12));
173
+ out.entries.push(makeEntry(repo, { kind: 'deep_link', framework: 'react-native', file: f, line, method: null, path: null, name: x[0].replace(/\s*\($/, ''), confidence: 'medium', handlerView: v, spec: { start: at, end, seeds: ['url', 'initialUrl', 'event'], returnsJson: false }, tags: ['deep_link'] }));
174
+ }
175
+ for (const x of v.masked.matchAll(/\bprefixes\s*:\s*\[/g)) {
176
+ const line = v.lines.at(x.index);
177
+ const prefixes = [...v.text.slice(x.index, x.index + 300).matchAll(/['"]([^'"]+:\/\/[^'"]*)['"]/g)].map((y) => y[1]);
178
+ const end = Math.min(v.text.length, v.lines.start(line + 25));
179
+ out.entries.push(makeEntry(repo, { kind: 'deep_link', framework: 'react-navigation', file: f, line, method: null, path: prefixes[0] ?? null, name: 'navigation linking config', confidence: 'medium', handlerView: v, spec: { start: x.index, end, seeds: [], returnsJson: false }, tags: ['deep_link'] }));
180
+ }
181
+ }
182
+ }
183
+ return out;
184
+ }
185
+ function deepLink(file, line, path, name, confidence, tags) {
186
+ return {
187
+ id: `${file}:${line}:deep_link:-:${path}:${name}`, kind: 'deep_link', framework: 'expo', file, line, end_line: line, method: null, path, name, handler: null, confidence,
188
+ test_code: testCodeReason(file) !== null, tags: [...tags].sort(), protections: [], reads: [{ source: 'params', line }], data: [], outbound: [],
189
+ };
190
+ }
package/dist/map/go.js ADDED
@@ -0,0 +1,292 @@
1
+ import { empty, joinPath, makeEntry } from './entry.js';
2
+ import { goFunc } from './light-index.js';
3
+ import { analyzeLight } from './light.js';
4
+ import { closeOf, splitArgs } from './lex.js';
5
+ const ROUTER_TYPE = /\*?(?:gin\.(?:Engine|RouterGroup|IRouter|IRoutes)|chi\.(?:Router|Mux)|echo\.(?:Echo|Group)|fiber\.(?:App|Router)|mux\.Router|http\.ServeMux)\b/;
6
+ const FW_BY_IMPORT = [[/gin-gonic\/gin/, 'gin'], [/go-chi\/chi/, 'chi'], [/labstack\/echo/, 'echo'], [/gofiber\/fiber/, 'fiber'], [/gorilla\/mux/, 'gorilla-mux']];
7
+ const METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'CONNECT', 'TRACE']);
8
+ const CREATE = /(?<![\w.])([A-Za-z_]\w*)\s*(?::=|=)\s*(?:chi\.NewRouter|chi\.NewMux|gin\.Default|gin\.New|echo\.New|fiber\.New|mux\.NewRouter|http\.NewServeMux|NewRouter|NewServeMux)\s*\(/g;
9
+ const ROUTE_CALLS = new Set(['Get', 'Post', 'Put', 'Patch', 'Delete', 'Head', 'Options', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'Any', 'All', 'Handle', 'HandleFunc', 'Method', 'MethodFunc', 'Match', 'Add', 'Connect', 'Trace', 'Mount', 'Use', 'Group', 'Route', 'With', 'PathPrefix', 'Subrouter', 'Static']);
10
+ const unq = (s) => /^\s*(?:"((?:\\.|[^"\\])*)"|`([^`]*)`)\s*$/.exec(s)?.slice(1).find((x) => x !== undefined) ?? null;
11
+ export function goFiles(repo) {
12
+ return repo.filesOf('go').filter((f) => { const v = repo.view(f); return !!v && /net\/http|gin-gonic|go-chi|labstack\/echo|gofiber|gorilla\/mux/.test(v.imports); });
13
+ }
14
+ export function extractGoAll(repo, fn, local) {
15
+ const out = empty();
16
+ const keyOf = (f) => `${f.file}#${f.start}`;
17
+ const funcs = [];
18
+ for (const file of goFiles(repo)) {
19
+ const v = repo.view(file);
20
+ for (const x of v.masked.matchAll(/^func\s+(?:\(\s*\w*\s*\*?\s*[\w.[\]]+\s*\)\s*)?(\w+)\s*[([]/gm)) {
21
+ const f = goFunc(v.masked, x.index);
22
+ if (f)
23
+ funcs.push({ file, view: v, start: f.start, end: f.end, bodyStart: f.bodyStart, params: f.params, name: x[1] });
24
+ }
25
+ // Package level routing, outside any function: var mux = http.NewServeMux(); func init() is a function and is covered above.
26
+ }
27
+ const scanned = new Map();
28
+ const mounted = new Map();
29
+ const scan = (f, base) => {
30
+ const r = scanFunction(repo, fn, local, f, base);
31
+ return r;
32
+ };
33
+ for (const f of funcs)
34
+ scanned.set(keyOf(f), scan(f, null));
35
+ // Mounted routers: scan the function that builds them again at the mount prefix, and drop its standalone result.
36
+ const queue = [...scanned.values()].flatMap((s) => s.mounts);
37
+ for (let depth = 0; depth < 4 && queue.length; depth++) {
38
+ const next = [];
39
+ for (const m of queue.splice(0)) {
40
+ for (const name of m.targets) {
41
+ const t = fn.defs(name).filter((d) => d.view.lang === 'go' && funcs.some((f) => f.file === d.view.file && f.start === d.start))[0];
42
+ if (!t)
43
+ continue;
44
+ const ref = funcs.find((f) => f.file === t.view.file && f.start === t.start);
45
+ const key = keyOf(ref);
46
+ if (mounted.has(key))
47
+ continue;
48
+ const env = { prefix: m.prefix, mws: m.mws, fw: m.fw, param: true };
49
+ mounted.set(key, env);
50
+ const res = scan(ref, env);
51
+ scanned.set(key, res);
52
+ next.push(...res.mounts);
53
+ }
54
+ }
55
+ queue.push(...next);
56
+ }
57
+ for (const [, s] of [...scanned.entries()].sort(([a], [b]) => (a < b ? -1 : 1)))
58
+ out.entries.push(...s.entries);
59
+ return out;
60
+ }
61
+ function scanFunction(repo, fn, local, f, base) {
62
+ const v = f.view;
63
+ const fw0 = FW_BY_IMPORT.find(([re]) => re.test(v.imports))?.[1] ?? 'net-http';
64
+ const entries = [];
65
+ const mounts = [];
66
+ const env = new Map();
67
+ let baseUsed = false;
68
+ const fresh = () => { if (base && !baseUsed) {
69
+ baseUsed = true;
70
+ return { ...base, mws: base.mws.slice() };
71
+ } return { prefix: '', mws: [], fw: fw0, param: false }; };
72
+ // Routers handed in as parameters.
73
+ for (const part of f.params.split(',')) {
74
+ const m = /^\s*(\w+)\s+(.+)$/.exec(part);
75
+ if (m && ROUTER_TYPE.test(m[2]))
76
+ env.set(m[1], base ? { ...base, mws: base.mws.slice() } : { prefix: '', mws: [], fw: fw0, param: true });
77
+ }
78
+ if (base && env.size)
79
+ baseUsed = true;
80
+ if (/"net\/http"/.test(v.imports))
81
+ env.set('http', { prefix: '', mws: [], fw: 'net-http', param: false });
82
+ const text = v.text;
83
+ const masked = v.masked;
84
+ const mwOf = (a, scope, only = null) => ({ view: v, start: a.start, end: a.end, scope, only });
85
+ const route = (e, recv, method, open, chained, at, forced) => {
86
+ const args = splitArgs(masked, open);
87
+ if (!args.length)
88
+ return;
89
+ let verb = forced;
90
+ let pathIdx = 0;
91
+ if (method === 'Handle' && args.length >= 3 && unq(text.slice(args[0].start, args[0].end)) && METHODS.has(unq(text.slice(args[0].start, args[0].end)))) {
92
+ verb = unq(text.slice(args[0].start, args[0].end));
93
+ pathIdx = 1;
94
+ }
95
+ if (method === 'Add' && args.length >= 3) {
96
+ verb = unq(text.slice(args[0].start, args[0].end));
97
+ pathIdx = 1;
98
+ }
99
+ if ((method === 'Method' || method === 'MethodFunc') && args.length >= 3) {
100
+ verb = unq(text.slice(args[0].start, args[0].end))?.toUpperCase() ?? null;
101
+ pathIdx = 1;
102
+ }
103
+ if (method === 'Match' && args.length >= 3) {
104
+ verb = 'ANY';
105
+ pathIdx = 1;
106
+ }
107
+ if (!verb)
108
+ verb = ROUTE_CALLS.has(method) && METHODS.has(method.toUpperCase()) ? method.toUpperCase() : 'ANY';
109
+ let path = unq(text.slice(args[pathIdx].start, args[pathIdx].end));
110
+ if (path === null)
111
+ return;
112
+ // Go 1.22 patterns: "GET /notes/{id}", and gorilla/chi style braces.
113
+ const pm = /^([A-Z]+)\s+(\S.*)$/.exec(path);
114
+ if (pm && METHODS.has(pm[1])) {
115
+ verb = pm[1];
116
+ path = pm[2];
117
+ }
118
+ path = path.replace(/\{(\w+)(?::[^}]*)?\}/g, ':$1').replace(/:(\w+)(?=\/|$)/g, ':$1').replace(/\*(\w*)/g, (_m, n) => `*${n || 'rest'}`).replace(/\{(\w+)\.\.\.\}/g, '*$1');
119
+ const rest = args.slice(pathIdx + 1);
120
+ if (!rest.length)
121
+ return;
122
+ const echo = e.fw === 'echo';
123
+ const handlerArg = echo ? rest[0] : rest[rest.length - 1];
124
+ const perRoute = (echo ? rest.slice(1) : rest.slice(0, -1)).map((a) => mwOf(a, 'wrapper'));
125
+ const full = joinPath(e.prefix, path);
126
+ const handlerText = text.slice(handlerArg.start, handlerArg.end);
127
+ if (/\bFileServer\b|\bStripPrefix\b|\bStatic\b/.test(handlerText) && !/func\s*\(/.test(handlerText))
128
+ return;
129
+ const resolved = resolveHandler(repo, fn, v, handlerArg);
130
+ const decorators = [
131
+ ...e.mws.filter((m) => m.only === null || full.startsWith(m.only)).map((m) => ({ view: m.view, start: m.start, end: m.end, scope: m.scope })),
132
+ ...chained.map((m) => ({ view: m.view, start: m.start, end: m.end, scope: m.scope })),
133
+ ...perRoute.map((m) => ({ view: m.view, start: m.start, end: m.end, scope: m.scope })),
134
+ ...resolved.wrappers.map((w) => ({ view: v, start: w.start, end: w.end, scope: 'wrapper' })),
135
+ ];
136
+ const hv = resolved.view;
137
+ const a = analyzeLight(hv, { start: resolved.start, end: resolved.end, seeds: [], decorators, lookup: fn.find, local });
138
+ const line = v.lines.at(at);
139
+ entries.push(makeEntry(repo, {
140
+ kind: 'http_route', framework: e.fw, file: v.file, line, method: verb, path: full, name: resolved.name,
141
+ confidence: e.param || !resolved.found ? 'medium' : 'high', handlerView: hv, spec: { start: resolved.start, end: resolved.end, seeds: [] }, analysis: a,
142
+ }));
143
+ };
144
+ const evs = [];
145
+ const body = [f.bodyStart, f.end];
146
+ CREATE.lastIndex = 0;
147
+ for (const m of masked.slice(body[0], body[1]).matchAll(CREATE))
148
+ evs.push({ at: body[0] + m.index, kind: 'create', m: m });
149
+ const callRe = /(?<![\w.])([A-Za-z_]\w*)\s*\.\s*([A-Za-z_]\w*)\s*\(/g;
150
+ for (const m of masked.slice(body[0], body[1]).matchAll(callRe))
151
+ evs.push({ at: body[0] + m.index, kind: 'call', m: m });
152
+ evs.sort((a, b) => a.at - b.at || (a.kind === 'create' ? -1 : 1));
153
+ let skipTo = -1;
154
+ const handleCall = (recv, method, at, open, e, assignTo, within) => {
155
+ const args = splitArgs(masked, open);
156
+ const closeAt = closeOf(masked, open);
157
+ if (method === 'Use') {
158
+ let only = null;
159
+ let list = args;
160
+ if (e.fw === 'fiber' && args.length > 1 && unq(text.slice(args[0].start, args[0].end)) !== null) {
161
+ only = unq(text.slice(args[0].start, args[0].end));
162
+ list = args.slice(1);
163
+ }
164
+ for (const a of list)
165
+ e.mws.push(mwOf(a, 'router', only === null ? null : joinPath(e.prefix, only)));
166
+ return closeAt;
167
+ }
168
+ if ((method === 'Group' || method === 'Route') && args.length) {
169
+ // chi: r.Route("/p", func(r chi.Router) { ... }) and r.Group(func(r chi.Router) { ... })
170
+ const lit = args.find((a) => /^func\s*\(/.test(masked.slice(a.start, a.end)));
171
+ if (lit && /\bchi\b|Router/.test(masked.slice(lit.start, lit.start + 80))) {
172
+ const g = goFunc(masked, lit.start);
173
+ const pm = /^func\s*\(\s*(\w+)/.exec(masked.slice(lit.start));
174
+ if (g && pm) {
175
+ const p = method === 'Route' ? unq(text.slice(args[0].start, args[0].end)) ?? '' : '';
176
+ const child = { prefix: joinPath(e.prefix, p || '/'), mws: e.mws.slice(), fw: e.fw, param: e.param };
177
+ const inner = new Map(within);
178
+ inner.set(pm[1], child);
179
+ walkRange(g.bodyStart + 1, g.end - 1, inner);
180
+ return g.end;
181
+ }
182
+ }
183
+ if (assignTo) {
184
+ const p = unq(text.slice(args[0].start, args[0].end)) ?? '';
185
+ const child = { prefix: joinPath(e.prefix, p || '/'), mws: [...e.mws, ...args.slice(1).map((a) => mwOf(a, 'router'))], fw: e.fw, param: e.param };
186
+ within.set(assignTo, child);
187
+ return closeAt;
188
+ }
189
+ return closeAt;
190
+ }
191
+ if (method === 'PathPrefix' && assignTo) {
192
+ const p = unq(text.slice(args[0]?.start ?? 0, args[0]?.end ?? 0)) ?? '';
193
+ within.set(assignTo, { prefix: joinPath(e.prefix, p || '/'), mws: e.mws.slice(), fw: e.fw, param: e.param });
194
+ return closeAt;
195
+ }
196
+ if (method === 'With') {
197
+ const tail = /^\s*\.\s*([A-Za-z_]\w*)\s*\(/.exec(masked.slice(closeAt, closeAt + 60));
198
+ if (tail) {
199
+ const chained = args.map((a) => mwOf(a, 'wrapper'));
200
+ const open2 = closeAt + tail[0].length - 1;
201
+ route(e, recv, tail[1], open2, chained, at, null);
202
+ return closeOf(masked, open2);
203
+ }
204
+ return closeAt;
205
+ }
206
+ if (method === 'Mount') {
207
+ const p = unq(text.slice(args[0]?.start ?? 0, args[0]?.end ?? 0));
208
+ const target = args[1] ? text.slice(args[1].start, args[1].end) : '';
209
+ if (p !== null) {
210
+ const names = [...target.matchAll(/(?<![\w.])(\w+)\s*\(/g)].map((x) => x[1]).concat(/^\s*\w+\s*$/.test(target) ? [target.trim()] : []);
211
+ mounts.push({ prefix: joinPath(e.prefix, p), mws: e.mws.slice(), fw: e.fw, targets: names, from: v.file });
212
+ }
213
+ return closeAt;
214
+ }
215
+ if (method === 'Subrouter' || method === 'Static')
216
+ return closeAt;
217
+ if (ROUTE_CALLS.has(method) || METHODS.has(method.toUpperCase())) {
218
+ // gorilla/mux: r.HandleFunc("/x", h).Methods("POST")
219
+ let forced = null;
220
+ const meth = /^\s*\.\s*Methods\s*\(([^)]*)\)/.exec(masked.slice(closeAt, closeAt + 80));
221
+ if (meth)
222
+ forced = [...text.slice(closeAt, closeAt + 120).matchAll(/"(\w+)"/g)].map((x) => x[1].toUpperCase())[0] ?? null;
223
+ route(e, recv, method, open, [], at, forced);
224
+ return meth ? closeAt + meth[0].length : closeAt;
225
+ }
226
+ return closeAt;
227
+ };
228
+ const walkRange = (from, to, scope) => {
229
+ for (const ev of evs) {
230
+ if (ev.at < from || ev.at >= to || ev.at < skipTo)
231
+ continue;
232
+ if (ev.kind === 'create') {
233
+ scope.set(ev.m[1], fresh());
234
+ continue;
235
+ }
236
+ const recv = ev.m[1];
237
+ const method = ev.m[2];
238
+ const e = scope.get(recv);
239
+ if (!e)
240
+ continue;
241
+ const open = ev.at + ev.m[0].length - 1;
242
+ const pre = masked.slice(Math.max(0, ev.at - 80), ev.at);
243
+ const assign = /(?:^|\n)\s*(\w+)\s*:?=\s*$/.exec(pre)?.[1] ?? null;
244
+ const end = handleCall(recv, method, ev.at, open, e, assign, scope);
245
+ if (end > skipTo)
246
+ skipTo = end;
247
+ }
248
+ };
249
+ walkRange(body[0], body[1], env);
250
+ return { entries, mounts };
251
+ }
252
+ // A handler argument: a function literal, a name, a method value (h.CreateNote), or a call that wraps or builds a handler.
253
+ function resolveHandler(repo, fn, v, a, depth = 0) {
254
+ const m = v.masked;
255
+ const t = m.slice(a.start, a.end).trim();
256
+ const miss = { view: v, start: a.start, end: a.end, name: /^(?:\w+\.)*(\w+)$/.exec(t)?.[1] ?? null, found: false, wrappers: [] };
257
+ if (depth > 4)
258
+ return miss;
259
+ if (/^func\s*\(/.test(t)) {
260
+ const g = goFunc(m, a.start + (m.slice(a.start, a.end).length - m.slice(a.start, a.end).trimStart().length));
261
+ if (g)
262
+ return { view: v, start: g.start, end: g.end, name: null, found: true, wrappers: [] };
263
+ }
264
+ const call = /^((?:\w+\.)*\w+)\s*\(/.exec(t);
265
+ if (call) {
266
+ const at = a.start + (m.slice(a.start, a.end).length - m.slice(a.start, a.end).trimStart().length);
267
+ const open = at + call[0].length - 1;
268
+ const args = splitArgs(m, open);
269
+ const head = call[1];
270
+ const last = head.split('.').pop();
271
+ if (/^HandlerFunc$/.test(last) && args.length === 1)
272
+ return resolveHandler(repo, fn, v, args[0], depth + 1);
273
+ for (const x of args) {
274
+ const r = resolveHandler(repo, fn, v, x, depth + 1);
275
+ if (r.found)
276
+ return { ...r, wrappers: [{ start: at, end: x.start }, ...r.wrappers] };
277
+ }
278
+ // A handler factory: s.handleCreate() returns the handler, so read its body.
279
+ const def = fn.find(last, v.file) ?? fn.defs(last)[0];
280
+ if (def)
281
+ return { view: def.view, start: def.start, end: def.end, name: last, found: true, wrappers: [] };
282
+ return miss;
283
+ }
284
+ const nm = /^(?:\w+\.)*(\w+)$/.exec(t)?.[1];
285
+ if (nm) {
286
+ const defs = fn.defs(nm);
287
+ const def = fn.find(nm, v.file) ?? defs.find((d) => d.view.file === v.file) ?? defs[0];
288
+ if (def)
289
+ return { view: def.view, start: def.start, end: def.end, name: nm, found: true, wrappers: [] };
290
+ }
291
+ return miss;
292
+ }
@@ -0,0 +1,143 @@
1
+ import { analyze } from './analyze.js';
2
+ import { empty, joinPath, makeEntry } from './entry.js';
3
+ import { closeOf, jsFunction, splitArgs } from './lex.js';
4
+ import { paramsOf, resolveFunction } from './js-next.js';
5
+ const FRAMEWORK = /\b(?:express|fastify|koa|hono|restify|polka|@hapi\/hapi|itty-router|elysia|@koa\/router|koa-router|connect|h3|@fastify\/\w+)\b/;
6
+ const CREATORS = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?=\s*(?:await\s+)?(?:new\s+)?(?:express\s*\.\s*Router|express|Router|fastify|Fastify|Hono|Koa|Elysia|polka|createRouter|KoaRouter|restify\s*\.\s*createServer|\w*[rR]outer)\s*[(<]/g;
7
+ const VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'all', 'options', 'head']);
8
+ const confMin = (cs) => (cs.includes('low') ? 'low' : cs.includes('medium') ? 'medium' : 'high');
9
+ function literalPaths(v, a) {
10
+ if (!a)
11
+ return null;
12
+ const c = v.masked[a.start];
13
+ if (c === '"' || c === "'" || c === '`') {
14
+ const p = v.text.slice(a.start + 1, a.end - 1);
15
+ return p.startsWith('/') || p === '*' || p === '' ? [p] : null;
16
+ }
17
+ if (c === '[') {
18
+ const ps = [...v.text.slice(a.start, a.end).matchAll(/['"`]([^'"`]*)['"`]/g)].map((x) => x[1]).filter((p) => p.startsWith('/') || p === '*');
19
+ return ps.length ? ps : null;
20
+ }
21
+ return null;
22
+ }
23
+ export function extractExpress(repo, v) {
24
+ const out = empty();
25
+ if (!FRAMEWORK.test(v.imports) && !/\bexpress\s*\(\s*\)|\bRouter\s*\(\s*\)/.test(v.masked))
26
+ return out;
27
+ const names = new Set(['app', 'router', 'server', 'api', 'route', 'routes', 'fastify', 'instance']);
28
+ for (const m of v.masked.matchAll(CREATORS))
29
+ names.add(m[1]);
30
+ const recv = [...names].map((n) => n.replace(/\$/g, '\\$')).join('|');
31
+ const call = new RegExp(`(?<![.\\w$])(?:${recv})\\s*\\.\\s*(get|post|put|patch|delete|all|options|head|use|route)\\s*\\(`, 'g');
32
+ const imports = repo.importMap(v);
33
+ const helpers = repo.helpers('js');
34
+ const middlewareDeco = (args) => args.map((a) => ({ view: v, start: a.start, end: a.end, scope: 'wrapper' }));
35
+ const calledNames = (args) => {
36
+ const set = new Set();
37
+ for (const a of args)
38
+ for (const m of v.masked.slice(a.start, a.end).matchAll(/(?<![\w$])([A-Za-z_$][\w$]*)\s*(?:\(|,|$)/g))
39
+ set.add(m[1]);
40
+ for (const a of args) {
41
+ const t = v.masked.slice(a.start, a.end);
42
+ const id = /^[A-Za-z_$][\w$.]*$/.exec(t);
43
+ if (id)
44
+ set.add(id[0].split('.').pop());
45
+ }
46
+ return [...set].sort();
47
+ };
48
+ const register = (verb, paths, args, at) => {
49
+ if (!args.length)
50
+ return;
51
+ const last = args[args.length - 1];
52
+ const mws = args.slice(0, -1);
53
+ const r = resolveFunction(repo, v, last.start, last.end);
54
+ const line = v.lines.at(at);
55
+ for (const p of paths) {
56
+ const method = verb === 'all' ? 'ANY' : verb.toUpperCase();
57
+ const handlerView = r?.view ?? v;
58
+ const start = r?.start ?? last.start;
59
+ const end = r?.end ?? last.end;
60
+ const seeds = r ? (r.params.length ? [r.params[0]] : ['req']) : [];
61
+ const deco = middlewareDeco(mws);
62
+ if (r?.wrapper)
63
+ deco.push({ view: v, start: r.wrapper.from, end: r.wrapper.to, scope: 'wrapper' });
64
+ const extra = calledNames(mws).concat(r?.wrapper ? [r.wrapper.name.split('.').pop()] : []);
65
+ const e = makeEntry(repo, {
66
+ kind: 'http_route', framework: 'express', file: v.file, line, method, path: joinPath('', p === '' ? '/' : p), name: r?.defName ?? nameOf(v, last),
67
+ confidence: 'high', handlerView, spec: { start, end, seeds, decorators: deco, extraCalls: extra, returnsJson: true },
68
+ });
69
+ out.entries.push(e);
70
+ }
71
+ };
72
+ for (const m of v.masked.matchAll(call)) {
73
+ const verb = m[1];
74
+ const open = m.index + m[0].length - 1;
75
+ const args = splitArgs(v.masked, open);
76
+ if (verb === 'route') {
77
+ const paths = literalPaths(v, args[0]);
78
+ if (!paths)
79
+ continue;
80
+ // .route('/x').get(h).post(h): read the chain after the call.
81
+ let i = closeOf(v.masked, open);
82
+ if (i < 0)
83
+ continue;
84
+ for (let g = 0; g < 8; g++) {
85
+ const nxt = /^\s*\.\s*(get|post|put|patch|delete|all|options|head)\s*\(/.exec(v.masked.slice(i, i + 60));
86
+ if (!nxt)
87
+ break;
88
+ const o = i + nxt[0].length - 1;
89
+ register(nxt[1], paths, splitArgs(v.masked, o), i + nxt[0].indexOf(nxt[1]));
90
+ i = closeOf(v.masked, o);
91
+ if (i < 0)
92
+ break;
93
+ }
94
+ continue;
95
+ }
96
+ if (VERBS.has(verb)) {
97
+ const paths = literalPaths(v, args[0]);
98
+ if (!paths || args.length < 2)
99
+ continue;
100
+ register(verb, paths, args.slice(1), m.index);
101
+ continue;
102
+ }
103
+ // use(): a gate on a path, or a router mount.
104
+ const paths = literalPaths(v, args[0]);
105
+ const rest = paths ? args.slice(1) : args;
106
+ const prefix = paths?.[0] ?? '*';
107
+ const line = v.lines.at(m.index);
108
+ let target = null;
109
+ for (const a of rest) {
110
+ const id = /^[A-Za-z_$][\w$]*$/.exec(v.masked.slice(a.start, a.end));
111
+ const spec = id ? imports.get(id[0]) : undefined;
112
+ const file = spec ? repo.resolveImport(v.file, spec) : null;
113
+ if (file && /\bRouter\s*\(|\bexpress\.Router\b|\bnew\s+Hono\b|\bfastify\b/.test(repo.ctx.text(file)))
114
+ target = file;
115
+ }
116
+ const gateArgs = rest.filter((a) => { const id = /^[A-Za-z_$][\w$]*$/.exec(v.masked.slice(a.start, a.end)); return !(id && target && imports.get(id[0]) && repo.resolveImport(v.file, imports.get(id[0])) === target); });
117
+ const protections = [];
118
+ for (const a of gateArgs) {
119
+ const spec = { start: a.start, end: a.end, seeds: [], decorators: [], extraCalls: calledNames([a]), returnsJson: false, gate: true };
120
+ const an = analyze(v, spec, helpers);
121
+ for (const p of an.protections)
122
+ if (p.kind !== 'owner_filter' && p.kind !== 'audit_log')
123
+ protections.push({ ...p, scope: 'middleware' });
124
+ }
125
+ const joined = protections.length ? protections : [];
126
+ if (target)
127
+ out.mounts.push({ from: v.file, line, prefix: joinPath('', prefix === '*' ? '/' : prefix), target, protections: joined });
128
+ else if (joined.length) {
129
+ const gate = { id: `${v.file}:${line}:use:${prefix}`, kind: 'middleware', framework: 'express', file: v.file, line, paths: [prefix === '*' ? '*' : joinPath('', prefix)], methods: [], protections: joined, confidence: confMin(joined.map((p) => p.confidence)) === 'high' ? 'medium' : confMin(joined.map((p) => p.confidence)) };
130
+ out.gates.push(gate);
131
+ }
132
+ }
133
+ return out;
134
+ }
135
+ // A readable name for the handler argument: the function name, or the called factory, or null for an inline function.
136
+ function nameOf(v, a) {
137
+ const t = v.masked.slice(a.start, a.end);
138
+ if (/^(?:async\b|function\b|\(|[A-Za-z_$][\w$]*\s*=>)/.test(t))
139
+ return null;
140
+ const m = /^([A-Za-z_$][\w$.]*)/.exec(t);
141
+ return m ? m[1] : null;
142
+ }
143
+ export { paramsOf };