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.
- package/LICENSE +222 -0
- package/NOTICE +32 -0
- package/README.md +313 -2
- package/checks/db.firebase-rules-not-open.json +24 -0
- package/checks/db.rls-every-table.json +25 -0
- package/checks/log.no-credential-in-logs.json +30 -0
- package/checks/secrets.no-env-file-committed.json +31 -0
- package/checks/secrets.no-secret-in-public-env.json +37 -0
- package/checks/storage.firebase-rules-not-open.json +22 -0
- package/checks/supply.no-untrusted-event-in-run.json +23 -0
- package/checks/web.cors-no-reflected-origin.json +31 -0
- package/detectors/ai.json +25 -0
- package/detectors/auth.json +27 -0
- package/detectors/ci.json +19 -0
- package/detectors/containers.json +8 -0
- package/detectors/data_stores.json +38 -0
- package/detectors/frameworks.json +94 -0
- package/detectors/hosting.json +44 -0
- package/detectors/iac.json +43 -0
- package/detectors/languages.json +48 -0
- package/detectors/mobile.json +22 -0
- package/detectors/package_managers.json +39 -0
- package/detectors/payments.json +19 -0
- package/detectors/runtimes.json +17 -0
- package/dist/checks/code/admin-role.js +46 -0
- package/dist/checks/code/owner-filter.js +91 -0
- package/dist/checks/code/shared.js +84 -0
- package/dist/checks/code/webhook-verify.js +77 -0
- package/dist/checks/context.js +64 -0
- package/dist/checks/map/config-checks.js +74 -0
- package/dist/checks/map/entry-checks.js +97 -0
- package/dist/checks/map/shared.js +44 -0
- package/dist/checks/ops.js +307 -0
- package/dist/checks/pro-map.js +1 -0
- package/dist/checks/run.js +92 -0
- package/dist/checks/types.js +1 -0
- package/dist/ci/comment.js +44 -0
- package/dist/ci/sarif-check.js +157 -0
- package/dist/ci/sarif.js +61 -0
- package/dist/cli.js +358 -0
- package/dist/commands/ci.js +115 -0
- package/dist/commands/git.js +58 -0
- package/dist/commands/hooks.js +30 -0
- package/dist/commands/hunt-pro.js +1 -0
- package/dist/commands/hunt.js +86 -0
- package/dist/commands/map.js +33 -0
- package/dist/commands/mcp.js +17 -0
- package/dist/commands/pack.js +48 -0
- package/dist/commands/prove-pro.js +1 -0
- package/dist/commands/prove.js +173 -0
- package/dist/commands/report-gate.js +92 -0
- package/dist/commands/scan.js +158 -0
- package/dist/confirm/agreement.js +18 -0
- package/dist/confirm/chain.js +84 -0
- package/dist/confirm/confirm.js +112 -0
- package/dist/confirm/honesty.js +75 -0
- package/dist/confirm/lead.js +92 -0
- package/dist/confirm/merge.js +88 -0
- package/dist/confirm/query.js +145 -0
- package/dist/confirm/rule.js +86 -0
- package/dist/confirm/store.js +42 -0
- package/dist/confirm/summary.js +6 -0
- package/dist/confirm/synthesis.js +28 -0
- package/dist/discover/detectors.js +50 -0
- package/dist/discover/discover.js +270 -0
- package/dist/discover/extract.js +282 -0
- package/dist/discover/git.js +40 -0
- package/dist/discover/kit-files.js +47 -0
- package/dist/discover/walk.js +110 -0
- package/dist/env.js +57 -0
- package/dist/gate/gate.js +173 -0
- package/dist/hooks/install.js +153 -0
- package/dist/hooks/run.js +112 -0
- package/dist/map/analyze.js +201 -0
- package/dist/map/build.js +253 -0
- package/dist/map/candidates.js +49 -0
- package/dist/map/cblocks.js +77 -0
- package/dist/map/config.js +291 -0
- package/dist/map/dotnet.js +242 -0
- package/dist/map/entry.js +78 -0
- package/dist/map/expo.js +190 -0
- package/dist/map/go.js +292 -0
- package/dist/map/js-express.js +143 -0
- package/dist/map/js-misc.js +295 -0
- package/dist/map/js-next.js +292 -0
- package/dist/map/laravel.js +389 -0
- package/dist/map/lex-more.js +305 -0
- package/dist/map/lex.js +425 -0
- package/dist/map/light-index.js +191 -0
- package/dist/map/light-profiles.js +324 -0
- package/dist/map/light.js +574 -0
- package/dist/map/local-vocab.js +27 -0
- package/dist/map/mobile.js +326 -0
- package/dist/map/py-django.js +281 -0
- package/dist/map/py.js +391 -0
- package/dist/map/rails.js +391 -0
- package/dist/map/repo.js +178 -0
- package/dist/map/rust.js +312 -0
- package/dist/map/spring.js +207 -0
- package/dist/map/taint.js +96 -0
- package/dist/map/touches.js +355 -0
- package/dist/map/vocab.js +88 -0
- package/dist/mapping/controls.js +34 -0
- package/dist/mapping/dependency-policy.js +44 -0
- package/dist/mapping/map.js +44 -0
- package/dist/mapping/maps/gitleaks.json +12 -0
- package/dist/mapping/maps/osv-scanner.json +7 -0
- package/dist/mapping/maps/trivy.json +13 -0
- package/dist/mcp/confine.js +59 -0
- package/dist/mcp/protocol.js +140 -0
- package/dist/mcp/schema.js +43 -0
- package/dist/mcp/server.js +37 -0
- package/dist/mcp/tools.js +238 -0
- package/dist/packs/coverage.js +79 -0
- package/dist/packs/manifest.js +36 -0
- package/dist/packs/validate.js +271 -0
- package/dist/prove/container.js +276 -0
- package/dist/prove/exec-main.js +20 -0
- package/dist/prove/executor.js +149 -0
- package/dist/prove/local.js +131 -0
- package/dist/prove/probes.js +65 -0
- package/dist/prove/recipe.js +278 -0
- package/dist/prove/run.js +136 -0
- package/dist/prove/runner.js +1 -0
- package/dist/prove/safety.js +126 -0
- package/dist/prove/spec.js +357 -0
- package/dist/prove/store.js +65 -0
- package/dist/report/build.js +297 -0
- package/dist/report/entry-points.js +75 -0
- package/dist/report/hunt-section.js +71 -0
- package/dist/report/kit.js +41 -0
- package/dist/report/load.js +35 -0
- package/dist/report/messages.js +273 -0
- package/dist/report/prove-section.js +65 -0
- package/dist/report/report.js +156 -0
- package/dist/report/surface.js +21 -0
- package/dist/report/test-code.js +51 -0
- package/dist/report/tiers.js +44 -0
- package/dist/scanners/common.js +162 -0
- package/dist/scanners/gitleaks.js +90 -0
- package/dist/scanners/index.js +113 -0
- package/dist/scanners/osv-scanner.js +77 -0
- package/dist/scanners/run-targets.js +34 -0
- package/dist/scanners/secret-noise.js +89 -0
- package/dist/scanners/semgrep.js +142 -0
- package/dist/scanners/trivy.js +65 -0
- package/dist/scanners/types.js +1 -0
- package/dist/types/check.js +1 -0
- package/dist/types/codemap.js +1 -0
- package/dist/types/findings.js +5 -0
- package/dist/types/hunt.js +1 -0
- package/dist/types/index.js +1 -0
- package/dist/types/prove.js +1 -0
- package/dist/types/results.js +2 -0
- package/dist/types/scan.js +1 -0
- package/dist/types/stack.js +5 -0
- package/dist/util.js +71 -0
- package/dist/version.js +2 -0
- package/package.json +46 -4
- package/packs/android/fixture-result.json +43 -0
- package/packs/android/pack.json +56 -0
- package/packs/dotnet/fixture-result.json +62 -0
- package/packs/dotnet/pack.json +88 -0
- package/packs/expo/answer-key.json +51 -0
- package/packs/expo/fixture-result.json +62 -0
- package/packs/expo/pack.json +79 -0
- package/packs/firebase/answer-key.json +27 -0
- package/packs/firebase/fixture-result.json +43 -0
- package/packs/firebase/pack.json +58 -0
- package/packs/go/answer-key.json +101 -0
- package/packs/go/fixture-result.json +64 -0
- package/packs/go/pack.json +99 -0
- package/packs/ios/fixture-result.json +43 -0
- package/packs/ios/pack.json +55 -0
- package/packs/laravel/answer-key.json +84 -0
- package/packs/laravel/fixture-result.json +60 -0
- package/packs/laravel/pack.json +91 -0
- package/packs/node-ts/answer-key.json +220 -0
- package/packs/node-ts/fixture-result.json +114 -0
- package/packs/node-ts/pack.json +134 -0
- package/packs/python/answer-key.json +195 -0
- package/packs/python/fixture-result.json +119 -0
- package/packs/python/pack.json +121 -0
- package/packs/rails/answer-key.json +84 -0
- package/packs/rails/fixture-result.json +60 -0
- package/packs/rails/pack.json +78 -0
- package/packs/rust/fixture-result.json +43 -0
- package/packs/rust/pack.json +69 -0
- package/packs/spring/fixture-result.json +63 -0
- package/packs/spring/pack.json +103 -0
- package/packs/supabase/answer-key.json +52 -0
- package/packs/supabase/fixture-result.json +58 -0
- package/packs/supabase/pack.json +60 -0
- package/rules/gitleaks.toml +256 -0
- package/rules/semgrep/api-route-no-auth.yaml +31 -0
- package/rules/semgrep/cors-reflect-origin.yaml +48 -0
- package/rules/semgrep/eval-or-new-function.yaml +185 -0
- package/rules/semgrep/log-session-token.yaml +48 -0
- package/rules/semgrep/math-random-tokens.yaml +24 -0
- package/rules/semgrep/next-public-secret-name.yaml +32 -0
- package/rules/semgrep/postgrest-filter-injection.yaml +78 -0
- package/rules/semgrep/raw-sql-concat.yaml +42 -0
- package/rules/semgrep/read-by-id-no-owner.yaml +49 -0
- package/rules/semgrep/server-action-no-auth.yaml +26 -0
- package/rules/semgrep/sql-variants.yaml +99 -0
- package/rules/semgrep/ssrf-unguarded-url.yaml +137 -0
- package/rules/semgrep/subprocess-injection.yaml +163 -0
- package/rules/semgrep/taint-go.yaml +333 -0
- package/rules/semgrep/taint-java.yaml +317 -0
- package/rules/semgrep/taint-javascript.yaml +412 -0
- package/rules/semgrep/taint-php.yaml +361 -0
- package/rules/semgrep/taint-python.yaml +414 -0
- package/rules/semgrep/tool-endpoint-admin-client.yaml +86 -0
- package/rules/semgrep/user-metadata-authz.yaml +22 -0
- package/rules/semgrep/verify-result-unused.yaml +62 -0
- package/rules/semgrep/webhook-parse-before-verify.yaml +29 -0
- package/rules/test-artifact-ids.json +4 -0
- package/rules/tiers.json +427 -0
- package/schemas/check-results.schema.json +55 -0
- package/schemas/check.schema.json +41 -0
- package/schemas/codemap.schema.json +216 -0
- package/schemas/findings.schema.json +1048 -0
- package/schemas/hunt-output.schema.json +46 -0
- package/schemas/hunt-result.schema.json +58 -0
- package/schemas/results.schema.json +17 -0
- package/schemas/scan-hits.schema.json +32 -0
- package/schemas/scan-meta.schema.json +25 -0
- package/schemas/stack.schema.json +93 -0
- package/src/checks/README.md +32 -0
- package/src/checks/code/admin-role.ts +49 -0
- package/src/checks/code/owner-filter.ts +95 -0
- package/src/checks/code/shared.ts +66 -0
- package/src/checks/code/webhook-verify.ts +75 -0
- package/src/checks/context.ts +72 -0
- package/src/checks/map/config-checks.ts +79 -0
- package/src/checks/map/entry-checks.ts +116 -0
- package/src/checks/map/shared.ts +63 -0
- package/src/checks/ops.ts +280 -0
- package/src/checks/pro-map.ts +4 -0
- package/src/checks/run.ts +80 -0
- package/src/checks/types.ts +12 -0
- package/src/ci/comment.ts +52 -0
- package/src/ci/sarif-check.ts +100 -0
- package/src/ci/sarif.ts +72 -0
- package/src/cli.ts +273 -0
- package/src/commands/ci.ts +104 -0
- package/src/commands/git.ts +59 -0
- package/src/commands/hooks.ts +27 -0
- package/src/commands/hunt-pro.ts +4 -0
- package/src/commands/hunt.ts +68 -0
- package/src/commands/map.ts +27 -0
- package/src/commands/mcp.ts +18 -0
- package/src/commands/pack.ts +34 -0
- package/src/commands/prove-pro.ts +4 -0
- package/src/commands/prove.ts +126 -0
- package/src/commands/report-gate.ts +75 -0
- package/src/commands/scan.ts +156 -0
- package/src/confirm/agreement.ts +23 -0
- package/src/confirm/chain.ts +67 -0
- package/src/confirm/confirm.ts +107 -0
- package/src/confirm/honesty.ts +65 -0
- package/src/confirm/lead.ts +76 -0
- package/src/confirm/merge.ts +89 -0
- package/src/confirm/query.ts +126 -0
- package/src/confirm/rule.ts +76 -0
- package/src/confirm/store.ts +42 -0
- package/src/confirm/summary.ts +9 -0
- package/src/confirm/synthesis.ts +33 -0
- package/src/discover/detectors.ts +71 -0
- package/src/discover/discover.ts +253 -0
- package/src/discover/extract.ts +235 -0
- package/src/discover/git.ts +31 -0
- package/src/discover/kit-files.ts +37 -0
- package/src/discover/walk.ts +88 -0
- package/src/env.ts +51 -0
- package/src/gate/gate.ts +169 -0
- package/src/hooks/install.ts +142 -0
- package/src/hooks/run.ts +121 -0
- package/src/map/analyze.ts +219 -0
- package/src/map/build.ts +206 -0
- package/src/map/candidates.ts +47 -0
- package/src/map/cblocks.ts +55 -0
- package/src/map/config.ts +207 -0
- package/src/map/dotnet.ts +205 -0
- package/src/map/entry.ts +80 -0
- package/src/map/expo.ts +171 -0
- package/src/map/go.ts +271 -0
- package/src/map/js-express.ts +135 -0
- package/src/map/js-misc.ts +221 -0
- package/src/map/js-next.ts +282 -0
- package/src/map/laravel.ts +327 -0
- package/src/map/lex-more.ts +152 -0
- package/src/map/lex.ts +274 -0
- package/src/map/light-index.ts +134 -0
- package/src/map/light-profiles.ts +363 -0
- package/src/map/light.ts +484 -0
- package/src/map/local-vocab.ts +30 -0
- package/src/map/mobile.ts +263 -0
- package/src/map/py-django.ts +239 -0
- package/src/map/py.ts +329 -0
- package/src/map/rails.ts +291 -0
- package/src/map/repo.ts +150 -0
- package/src/map/rust.ts +256 -0
- package/src/map/spring.ts +185 -0
- package/src/map/taint.ts +86 -0
- package/src/map/touches.ts +296 -0
- package/src/map/vocab.ts +106 -0
- package/src/mapping/controls.ts +47 -0
- package/src/mapping/dependency-policy.ts +55 -0
- package/src/mapping/map.ts +59 -0
- package/src/mapping/maps/gitleaks.json +12 -0
- package/src/mapping/maps/osv-scanner.json +7 -0
- package/src/mapping/maps/trivy.json +13 -0
- package/src/mcp/confine.ts +44 -0
- package/src/mcp/protocol.ts +144 -0
- package/src/mcp/schema.ts +35 -0
- package/src/mcp/server.ts +32 -0
- package/src/mcp/tools.ts +235 -0
- package/src/packs/coverage.ts +98 -0
- package/src/packs/manifest.ts +97 -0
- package/src/packs/validate.ts +204 -0
- package/src/prove/container.ts +237 -0
- package/src/prove/exec-main.ts +16 -0
- package/src/prove/executor.ts +130 -0
- package/src/prove/local.ts +100 -0
- package/src/prove/probes.ts +68 -0
- package/src/prove/recipe.ts +215 -0
- package/src/prove/run.ts +124 -0
- package/src/prove/runner.ts +28 -0
- package/src/prove/safety.ts +98 -0
- package/src/prove/spec.ts +256 -0
- package/src/prove/store.ts +48 -0
- package/src/report/build.ts +304 -0
- package/src/report/entry-points.ts +78 -0
- package/src/report/hunt-section.ts +67 -0
- package/src/report/kit.ts +59 -0
- package/src/report/load.ts +49 -0
- package/src/report/messages.ts +270 -0
- package/src/report/prove-section.ts +61 -0
- package/src/report/report.ts +160 -0
- package/src/report/surface.ts +32 -0
- package/src/report/test-code.ts +56 -0
- package/src/report/tiers.ts +50 -0
- package/src/scanners/common.ts +149 -0
- package/src/scanners/gitleaks.ts +89 -0
- package/src/scanners/index.ts +103 -0
- package/src/scanners/osv-scanner.ts +90 -0
- package/src/scanners/run-targets.ts +35 -0
- package/src/scanners/secret-noise.ts +80 -0
- package/src/scanners/semgrep.ts +139 -0
- package/src/scanners/trivy.ts +66 -0
- package/src/scanners/types.ts +98 -0
- package/src/types/check.ts +52 -0
- package/src/types/codemap.ts +142 -0
- package/src/types/findings.ts +107 -0
- package/src/types/hunt.ts +97 -0
- package/src/types/index.ts +10 -0
- package/src/types/prove.ts +83 -0
- package/src/types/results.ts +15 -0
- package/src/types/scan.ts +63 -0
- package/src/types/stack.ts +61 -0
- package/src/util.ts +59 -0
- package/src/version.ts +2 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// Entry points of Next.js (app router route handlers and pages, pages router API routes, server actions, middleware),
|
|
2
|
+
// Supabase edge functions and tRPC procedures.
|
|
3
|
+
import type { Gate, Protection } from '../types/index.ts';
|
|
4
|
+
import { analyze, type FileView, type Spec } from './analyze.ts';
|
|
5
|
+
import { empty, joinPath, makeEntry, normPath, paramNames, type Extracted } from './entry.ts';
|
|
6
|
+
import { closeOf, jsFunction, splitArgs, type Extent } from './lex.ts';
|
|
7
|
+
import type { Repo } from './repo.ts';
|
|
8
|
+
import { ADMIN_PATH } from './vocab.ts';
|
|
9
|
+
|
|
10
|
+
const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
|
|
11
|
+
|
|
12
|
+
// A function-valued expression starting at `at`: a function itself, a call that wraps one (withAuth(handler)), or a name.
|
|
13
|
+
export interface Resolved { view: FileView; start: number; end: number; wrapper: { name: string; from: number; to: number } | null; resolved: boolean; params: string[]; defName?: string }
|
|
14
|
+
export function resolveFunction(repo: Repo, v: FileView, at: number, limit: number): Resolved | null {
|
|
15
|
+
const m = v.masked;
|
|
16
|
+
const direct = jsFunction(m, at);
|
|
17
|
+
if (direct && direct.end <= limit + 1) return { view: v, start: direct.start, end: direct.end, wrapper: null, resolved: false, params: paramsOf(m, direct) };
|
|
18
|
+
const call = /^\s*([A-Za-z_$][\w$.]*)\s*(?:<[^>(]*>)?\s*\(/.exec(m.slice(at, limit));
|
|
19
|
+
if (call) {
|
|
20
|
+
const open = at + call[0].length - 1;
|
|
21
|
+
const args = splitArgs(m, open);
|
|
22
|
+
for (const a of args) {
|
|
23
|
+
const f = jsFunction(m, a.start);
|
|
24
|
+
if (f && f.end <= a.end + 1) return { view: v, start: f.start, end: f.end, wrapper: { name: call[1], from: at, to: a.start }, resolved: false, params: paramsOf(m, f) };
|
|
25
|
+
}
|
|
26
|
+
for (const a of args) {
|
|
27
|
+
const id = /^([A-Za-z_$][\w$]*)(?:\s*\([\s\S]*\))?$/.exec(m.slice(a.start, a.end));
|
|
28
|
+
if (id) { const r = repo.defs('js', id[1]).filter((d) => d.view.file === v.file).concat(repo.defs('js', id[1]))[0]; if (r) 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] }; }
|
|
29
|
+
}
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
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));
|
|
33
|
+
if (id) {
|
|
34
|
+
const defs = repo.defs('js', id[1]);
|
|
35
|
+
const r = defs.find((d) => d.view.file === v.file) ?? (defs.length === 1 ? defs[0] : null);
|
|
36
|
+
if (r) 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] };
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function paramsOf(masked: string, f: Extent): string[] {
|
|
42
|
+
const head = masked.slice(f.start, f.bodyStart);
|
|
43
|
+
const open = head.indexOf('(');
|
|
44
|
+
if (open >= 0 && (head.indexOf('=>') < 0 || open < head.indexOf('=>'))) return paramNames(masked, f.start + open);
|
|
45
|
+
const single = /^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*=>/.exec(head);
|
|
46
|
+
return single ? [single[1]] : [];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const nextRoutePath = (file: string, strip: RegExp): string | null => {
|
|
50
|
+
const m = /(?:^|\/)(?:src\/)?app\/(.*)$/.exec(file);
|
|
51
|
+
if (!m) return null;
|
|
52
|
+
const segs = m[1].replace(strip, '').split('/').filter((s) => s && !/^\(.*\)$/.test(s) && !s.startsWith('@'));
|
|
53
|
+
return normPath('/' + segs.join('/'));
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// Exported names in a file with where their value starts: export function X, export const X = ..., export { a as X }.
|
|
57
|
+
export function exportedFunctions(repo: Repo, v: FileView): { exportName: string; r: Resolved; line: number; at: number }[] {
|
|
58
|
+
const m = v.masked;
|
|
59
|
+
const out: { exportName: string; r: Resolved; line: number; at: number }[] = [];
|
|
60
|
+
for (const x of m.matchAll(/\bexport\s+(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/g)) {
|
|
61
|
+
const at = x.index! + (/\bexport\s+(?:default\s+)?/.exec(x[0])![0].length);
|
|
62
|
+
const f = jsFunction(m, at);
|
|
63
|
+
if (f) 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 });
|
|
64
|
+
}
|
|
65
|
+
for (const x of m.matchAll(/\bexport\s+const\s+([A-Za-z_$][\w$]*)\s*(?::[^=\n]+)?=\s*/g)) {
|
|
66
|
+
const at = x.index! + x[0].length;
|
|
67
|
+
const limit = statementLimit(m, at);
|
|
68
|
+
const r = resolveFunction(repo, v, at, limit);
|
|
69
|
+
if (r) 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) continue;
|
|
75
|
+
const defs = repo.defs('js', local);
|
|
76
|
+
const d = defs.find((q) => q.view.file === v.file);
|
|
77
|
+
if (d) 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! });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function statementLimit(masked: string, from: number): number {
|
|
84
|
+
let depth = 0;
|
|
85
|
+
for (let i = from; i < masked.length; i++) {
|
|
86
|
+
const c = masked[i];
|
|
87
|
+
if (c === '(' || c === '[' || c === '{') depth++;
|
|
88
|
+
else if (c === ')' || c === ']' || c === '}') { if (depth === 0) return i; depth--; }
|
|
89
|
+
else if (c === ';' && depth === 0) return i;
|
|
90
|
+
else if (c === '\n' && depth === 0 && /\n\s*(?:export|const|let|var|function|async|import|type|interface|\/\/)/.test(masked.slice(i, i + 40))) return i;
|
|
91
|
+
}
|
|
92
|
+
return masked.length;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function spec(r: Resolved, decorators: Spec['decorators'], seeds: string[], extra: string[] = []): Spec {
|
|
96
|
+
const deco = decorators ?? [];
|
|
97
|
+
return { start: r.start, end: r.end, seeds, decorators: deco, extraCalls: extra, returnsJson: true };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const wrapperDeco = (v: FileView, r: Resolved): NonNullable<Spec['decorators']> => (r.wrapper ? [{ view: v, start: r.wrapper.from, end: r.wrapper.to, scope: 'wrapper' }] : []);
|
|
101
|
+
|
|
102
|
+
export function extractNext(repo: Repo, v: FileView): Extracted {
|
|
103
|
+
const out = empty();
|
|
104
|
+
const file = v.file;
|
|
105
|
+
const text = v.text;
|
|
106
|
+
|
|
107
|
+
// App router route handlers.
|
|
108
|
+
if (/(?:^|\/)(?:src\/)?app\/(?:.*\/)?route\.[cm]?[jt]sx?$/.test(file)) {
|
|
109
|
+
const path = nextRoutePath(file, /\/?route\.[cm]?[jt]sx?$/);
|
|
110
|
+
for (const e of exportedFunctions(repo, v)) {
|
|
111
|
+
if (!METHODS.includes(e.exportName)) continue;
|
|
112
|
+
const r = e.r;
|
|
113
|
+
const seeds = r.params.length ? r.params : ['req', 'request', 'params'];
|
|
114
|
+
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()!] : []) }));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// App router pages.
|
|
119
|
+
if (/(?:^|\/)(?:src\/)?app\/(?:.*\/)?page\.[cm]?[jt]sx?$/.test(file)) {
|
|
120
|
+
const path = nextRoutePath(file, /\/?page\.[cm]?[jt]sx?$/);
|
|
121
|
+
const ex = defaultExport(repo, v);
|
|
122
|
+
if (ex) {
|
|
123
|
+
const r = ex.r;
|
|
124
|
+
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]) }));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Pages router API routes.
|
|
129
|
+
if (/(?:^|\/)(?:src\/)?pages\/api\/.+\.[cm]?[jt]sx?$/.test(file)) {
|
|
130
|
+
const path = normPath('/api/' + (/pages\/api\/(.*)$/.exec(file)![1]).replace(/\.[cm]?[jt]sx?$/, '').replace(/\/?index$/, ''));
|
|
131
|
+
const ex = defaultExport(repo, v);
|
|
132
|
+
if (ex) {
|
|
133
|
+
const r = ex.r;
|
|
134
|
+
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();
|
|
135
|
+
for (const method of methods.length ? methods : ['ANY']) {
|
|
136
|
+
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()!] : []) }));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// Server actions: a "use server" file, or the directive inside a function.
|
|
142
|
+
const fileDirective = /^\s*(?:\/\/[^\n]*\n\s*|\/\*[\s\S]*?\*\/\s*)*['"]use server['"]/.test(text);
|
|
143
|
+
if (fileDirective) {
|
|
144
|
+
for (const e of exportedFunctions(repo, v)) {
|
|
145
|
+
const r = e.r;
|
|
146
|
+
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()!] : []) }));
|
|
147
|
+
}
|
|
148
|
+
} else if (/['"]use server['"]/.test(text)) {
|
|
149
|
+
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)) {
|
|
150
|
+
const at = x.index!;
|
|
151
|
+
const f = jsFunction(v.masked, at);
|
|
152
|
+
if (!f || !/^\s*\{\s*['"]use server['"]/.test(text.slice(f.bodyStart, f.bodyStart + 60))) continue;
|
|
153
|
+
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 } }));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Middleware (a gate, not an entry point).
|
|
158
|
+
if (/(?:^|\/)(?:src\/)?(?:middleware|proxy)\.[cm]?[jt]s$/.test(file)) {
|
|
159
|
+
const named = exportedFunctions(repo, v).find((e) => e.exportName === 'middleware' || e.exportName === 'proxy');
|
|
160
|
+
const dflt = named ? null : defaultExport(repo, v);
|
|
161
|
+
const fn = named ? { r: named.r } : dflt ? { r: dflt.r } : null;
|
|
162
|
+
if (fn) {
|
|
163
|
+
const a = analyze(v, spec(fn.r, wrapperDeco(v, fn.r), fn.r.params.length ? fn.r.params : ['req', 'request']), repo.helpers('js'));
|
|
164
|
+
const matcher = /\bmatcher\s*:\s*(\[[^\]]*\]|['"][^'"]*['"])/.exec(text);
|
|
165
|
+
const matcherPaths = matcher ? [...matcher[1].matchAll(/['"]([^'"]*)['"]/g)].map((x) => gatePrefix(x[1])) : [];
|
|
166
|
+
// A check inside "if (pathname.startsWith('/admin'))" covers only those prefixes, not the whole matcher.
|
|
167
|
+
const blocks = [...v.masked.slice(fn.r.start, fn.r.end).matchAll(/\bif\s*\(/g)].map((x) => {
|
|
168
|
+
const open = fn.r.start + x.index! + x[0].length - 1;
|
|
169
|
+
const condEnd = closeOf(v.masked, open);
|
|
170
|
+
if (condEnd < 0) return null;
|
|
171
|
+
const prefixes = [...text.slice(open, condEnd).matchAll(/startsWith\(\s*['"](\/[^'"]*)['"]/g)].map((y) => normPath(y[1].replace(/\/$/, '') || '/'));
|
|
172
|
+
const b = v.masked.indexOf('{', condEnd);
|
|
173
|
+
const bEnd = b < 0 ? -1 : closeOf(v.masked, b);
|
|
174
|
+
return prefixes.length && b >= 0 && bEnd > 0 && /^\s*\{/.test(v.masked.slice(condEnd, b + 1)) ? { start: b, end: bEnd, prefixes } : null;
|
|
175
|
+
}).filter((x): x is { start: number; end: number; prefixes: string[] } => x !== null);
|
|
176
|
+
const groups = new Map<string, Protection[]>();
|
|
177
|
+
const blockAt = (pos: number): { start: number; end: number; prefixes: string[] } | undefined => blocks.filter((b) => pos >= b.start && pos <= b.end).sort((x, y) => (x.end - x.start) - (y.end - y.start))[0];
|
|
178
|
+
for (const p of a.protections.filter((q) => q.kind !== 'owner_filter')) {
|
|
179
|
+
const at = v.lines.start(p.line);
|
|
180
|
+
let prefixes = blockAt(at)?.prefixes ?? null;
|
|
181
|
+
if (!prefixes) {
|
|
182
|
+
// The value is stored in a variable and tested later: use the blocks that test it, when all of them are inside one.
|
|
183
|
+
const lineText = text.slice(at, text.indexOf('\n', at) < 0 ? text.length : text.indexOf('\n', at));
|
|
184
|
+
const name = /(?:const|let|var)\s+(\w+)\s*=/.exec(lineText)?.[1];
|
|
185
|
+
if (name) {
|
|
186
|
+
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);
|
|
187
|
+
const inBlocks = uses.map((pos) => blockAt(pos));
|
|
188
|
+
if (uses.length && inBlocks.every((b) => b)) prefixes = [...new Set(inBlocks.flatMap((b) => b!.prefixes))];
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const key = prefixes ? [...new Set(prefixes)].sort().join('\u0000') : '*';
|
|
192
|
+
groups.set(key, [...(groups.get(key) ?? []), { ...p, scope: 'middleware' as const }]);
|
|
193
|
+
}
|
|
194
|
+
for (const [key, protections] of [...groups.entries()].sort()) {
|
|
195
|
+
const paths = key === '*' ? (matcherPaths.length ? [...new Set(matcherPaths)].sort() : ['*']) : key.split('\u0000');
|
|
196
|
+
const gate: Gate = {
|
|
197
|
+
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),
|
|
198
|
+
paths, methods: [], protections, confidence: 'medium',
|
|
199
|
+
};
|
|
200
|
+
out.gates.push(gate);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Supabase edge functions.
|
|
206
|
+
const edge = /(?:^|\/)supabase\/functions\/([^/_][^/]*)\/index\.[cm]?[jt]sx?$/.exec(file);
|
|
207
|
+
if (edge) {
|
|
208
|
+
const serve = /\b(?:Deno\.)?serve\s*\(/.exec(v.masked);
|
|
209
|
+
if (serve) {
|
|
210
|
+
const open = serve.index + serve[0].length - 1;
|
|
211
|
+
const args = splitArgs(v.masked, open);
|
|
212
|
+
const fa = args.map((a) => ({ a, r: resolveFunction(repo, v, a.start, a.end) })).find((x) => x.r);
|
|
213
|
+
if (fa?.r) {
|
|
214
|
+
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']) });
|
|
215
|
+
const cfg = repo.ctx.text('supabase/config.toml');
|
|
216
|
+
const sec = new RegExp(`\\[functions\\.${edge[1].replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&')}\\]([^\\[]*)`).exec(cfg);
|
|
217
|
+
const off = sec ? /verify_jwt\s*=\s*false/.test(sec[1]) : false;
|
|
218
|
+
if (!off) 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' });
|
|
219
|
+
e.protections.sort((x, y) => x.line - y.line || (x.kind < y.kind ? -1 : 1));
|
|
220
|
+
out.entries.push(e);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// tRPC procedures.
|
|
226
|
+
if (/[pP]rocedure\b/.test(v.masked) && /trpc|Procedure/.test(v.imports + v.text.slice(0, 3000))) {
|
|
227
|
+
for (const x of v.masked.matchAll(/(?<![.\w$])([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*[pP]rocedure)\b/g)) {
|
|
228
|
+
let i = x.index! + x[0].length;
|
|
229
|
+
let verb: string | null = null;
|
|
230
|
+
let handler: Extent | null = null;
|
|
231
|
+
const chain: string[] = [];
|
|
232
|
+
for (let guard = 0; guard < 12; guard++) {
|
|
233
|
+
while (/\s/.test(v.masked[i] ?? '')) i++;
|
|
234
|
+
if (v.masked[i] !== '.') break;
|
|
235
|
+
const call = /^\.\s*(\w+)\s*\(/.exec(v.masked.slice(i));
|
|
236
|
+
if (!call) break;
|
|
237
|
+
const open = i + call[0].length - 1;
|
|
238
|
+
const close = closeOf(v.masked, open);
|
|
239
|
+
if (close < 0) break;
|
|
240
|
+
chain.push(call[1]);
|
|
241
|
+
if (['query', 'mutation', 'subscription'].includes(call[1])) {
|
|
242
|
+
verb = call[1];
|
|
243
|
+
const a = splitArgs(v.masked, open)[0];
|
|
244
|
+
handler = a ? jsFunction(v.masked, a.start) : null;
|
|
245
|
+
i = close;
|
|
246
|
+
break;
|
|
247
|
+
}
|
|
248
|
+
i = close;
|
|
249
|
+
}
|
|
250
|
+
if (!verb || !handler) continue;
|
|
251
|
+
const procName = x[2];
|
|
252
|
+
const deco: NonNullable<Spec['decorators']> = [{ view: v, start: x.index! + x[1].length, end: handler.start, scope: 'router' }];
|
|
253
|
+
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 } });
|
|
254
|
+
if (/protected|auth|private|member|user|admin|session|staff/i.test(procName)) e.protections.push({ kind: 'session_read', scope: 'router', file, line: e.line, via: `procedure ${procName}`, enforced: true, confidence: 'medium' });
|
|
255
|
+
if (/admin|staff|owner/i.test(procName) || ADMIN_PATH.test(procName)) e.protections.push({ kind: 'role_check', scope: 'router', file, line: e.line, via: `procedure ${procName}`, enforced: true, confidence: 'medium' });
|
|
256
|
+
if (chain.includes('input')) e.protections.push({ kind: 'input_validation', scope: 'router', file, line: e.line, via: 'trpc .input()', enforced: true, confidence: 'high' });
|
|
257
|
+
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));
|
|
258
|
+
out.entries.push(e);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return out;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function defaultExport(repo: Repo, v: FileView): { exportName: string | null; r: Resolved } | null {
|
|
265
|
+
const m = v.masked;
|
|
266
|
+
const x = /\bexport\s+default\s+/.exec(m);
|
|
267
|
+
if (!x) return null;
|
|
268
|
+
const at = x.index + x[0].length;
|
|
269
|
+
const limit = statementLimit(m, at);
|
|
270
|
+
const direct = jsFunction(m, at);
|
|
271
|
+
const named = /^(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/.exec(m.slice(at, at + 80));
|
|
272
|
+
const r = direct ? { view: v, start: direct.start, end: direct.end, wrapper: null, resolved: false, params: paramsOf(m, direct) } : resolveFunction(repo, v, at, limit);
|
|
273
|
+
return r ? { exportName: named?.[1] ?? null, r } : null;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// A middleware matcher such as "/admin/:path*" or "/api/(.*)" as the path prefix it covers.
|
|
277
|
+
function gatePrefix(matcher: string): string {
|
|
278
|
+
const p = matcher.replace(/\/?(?::\w+\*?|\(\.\*\)|\*)$/g, '').replace(/\/\(\.\*\)$/, '');
|
|
279
|
+
return normPath(p === '' ? '*' : p.startsWith('/') ? p : `/${p}`);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export { joinPath };
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
// PHP and Laravel entry points: routes/*.php (Route::get and the other verbs, match, any, resource, apiResource, controller
|
|
2
|
+
// and middleware groups, prefix, closures and invokable controllers) joined to the controller methods they name, with the
|
|
3
|
+
// middleware each route runs (the group chain, the route chain, the controller constructor, HasMiddleware, attributes and
|
|
4
|
+
// authorizeResource) as its protections, and the api throttle group from bootstrap/app.php or the HTTP kernel.
|
|
5
|
+
import type { Protection } from '../types/index.ts';
|
|
6
|
+
import type { FileView } from './analyze.ts';
|
|
7
|
+
import { empty, joinPath, makeEntry, type Extracted } from './entry.ts';
|
|
8
|
+
import { phpFunc, type FnIndex } from './light-index.ts';
|
|
9
|
+
import { analyzeLight, type LightDeco } from './light.ts';
|
|
10
|
+
import { closeOf, splitArgs } from './lex.ts';
|
|
11
|
+
import type { LocalVocab } from './local-vocab.ts';
|
|
12
|
+
import type { Repo } from './repo.ts';
|
|
13
|
+
|
|
14
|
+
interface Mw { view: FileView; start: number; end: number }
|
|
15
|
+
interface Ctx { prefix: string; mws: Mw[]; controller: string | null; without: string[] }
|
|
16
|
+
interface Call { name: string; open: number; close: number }
|
|
17
|
+
interface CtrlFilter { view: FileView; start: number; end: number; only: string[] | null; except: string[] | null }
|
|
18
|
+
|
|
19
|
+
const VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'any']);
|
|
20
|
+
const singular = (s: string): string => (/ies$/.test(s) ? s.replace(/ies$/, 'y') : s.replace(/s$/, ''));
|
|
21
|
+
const phpPath = (p: string): string => p.replace(/\{(\w+)\??(?::[^}]*)?\}/g, ':$1');
|
|
22
|
+
const strs = (s: string): string[] => [...s.matchAll(/['"]([^'"]*)['"]/g)].map((m) => m[1]);
|
|
23
|
+
|
|
24
|
+
export function laravelFiles(repo: Repo): string[] {
|
|
25
|
+
return repo.filesOf('php').filter((f) => /(?:^|\/)routes\/(?!console|channels)[\w.-]+\.php$/.test(f));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function chainAt(v: FileView, at: number): { calls: Call[]; end: number } {
|
|
29
|
+
const m = v.masked;
|
|
30
|
+
const calls: Call[] = [];
|
|
31
|
+
let pos = at + 'Route::'.length;
|
|
32
|
+
for (let guard = 0; guard < 24; guard++) {
|
|
33
|
+
const id = /^\s*(\w+)\s*\(/.exec(m.slice(pos, pos + 800));
|
|
34
|
+
if (!id) break;
|
|
35
|
+
const open = pos + id[0].length - 1;
|
|
36
|
+
const close = closeOf(m, open);
|
|
37
|
+
if (close < 0) break;
|
|
38
|
+
calls.push({ name: id[1], open, close });
|
|
39
|
+
pos = close;
|
|
40
|
+
const arrow = /^\s*->\s*/.exec(m.slice(pos, pos + 800)); // comments are blank in the masked copy and can be long
|
|
41
|
+
if (!arrow) break;
|
|
42
|
+
pos += arrow[0].length;
|
|
43
|
+
}
|
|
44
|
+
return { calls, end: pos };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function extractLaravelAll(repo: Repo, fn: FnIndex, local: LocalVocab | null): Extracted {
|
|
48
|
+
const out = empty();
|
|
49
|
+
const files = laravelFiles(repo);
|
|
50
|
+
if (!files.length) return out;
|
|
51
|
+
|
|
52
|
+
// Classes by short name: controllers, models and middleware.
|
|
53
|
+
const classes = new Map<string, FileView>();
|
|
54
|
+
for (const f of repo.filesOf('php')) {
|
|
55
|
+
if (/(?:^|\/)(?:vendor|node_modules)\//.test(f)) continue;
|
|
56
|
+
const v = repo.view(f);
|
|
57
|
+
if (!v) continue;
|
|
58
|
+
const m = /^[ \t]*(?:final\s+|abstract\s+)?class\s+(\w+)/m.exec(v.masked);
|
|
59
|
+
if (m && !classes.has(m[1])) classes.set(m[1], v);
|
|
60
|
+
}
|
|
61
|
+
const isModel = (cls: string): boolean => { const v = classes.get(cls); return !!v && (/\/Models\//.test(v.file) || /\bextends\s+(?:Model|Authenticatable|Pivot|\\?Illuminate\\Database\\Eloquent\\Model)\b/.test(v.masked)); };
|
|
62
|
+
|
|
63
|
+
// Aliases of route middleware: 'admin' => EnsureUserIsAdmin::class.
|
|
64
|
+
const aliases = new Map<string, string>();
|
|
65
|
+
const bootText = ['bootstrap/app.php', 'app/Http/Kernel.php', 'app/Providers/RouteServiceProvider.php'].map((f) => ({ f, t: repo.ctx.text(f) }));
|
|
66
|
+
for (const { t } of bootText) for (const m of t.matchAll(/['"]([\w.-]+)['"]\s*=>\s*\\?(?:[\w\\]*\\)?(\w+)::class/g)) aliases.set(m[1], m[2]);
|
|
67
|
+
let apiThrottle: Protection | null = null;
|
|
68
|
+
for (const { f, t } of bootText) {
|
|
69
|
+
const m = /throttleApi\s*\(|['"]throttle:api['"]|['"]api['"]\s*=>\s*\[[^\]]*throttle/.exec(t);
|
|
70
|
+
if (m && !apiThrottle) apiThrottle = { kind: 'rate_limit', scope: 'global', file: f, line: t.slice(0, m.index).split('\n').length, via: 'api middleware group throttle', enforced: true, confidence: 'medium' };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Controller level middleware: constructor, HasMiddleware, attributes, authorizeResource.
|
|
74
|
+
const ctrlFilters = (cls: string): { filters: CtrlFilter[]; policy: boolean } => {
|
|
75
|
+
const v = classes.get(cls);
|
|
76
|
+
const filters: CtrlFilter[] = [];
|
|
77
|
+
let policy = false;
|
|
78
|
+
if (!v) return { filters, policy };
|
|
79
|
+
const m = v.masked;
|
|
80
|
+
const lists = (text: string): { only: string[] | null; except: string[] | null } => ({
|
|
81
|
+
only: /->\s*only\s*\(([^)]*)\)/.exec(text) ? strs(/->\s*only\s*\(([^)]*)\)/.exec(text)![1]) : null,
|
|
82
|
+
except: /->\s*except\s*\(([^)]*)\)/.exec(text) ? strs(/->\s*except\s*\(([^)]*)\)/.exec(text)![1]) : null,
|
|
83
|
+
});
|
|
84
|
+
for (const x of m.matchAll(/\$this->middleware\s*\(/g)) {
|
|
85
|
+
const open = x.index! + x[0].length - 1;
|
|
86
|
+
const close = closeOf(m, open);
|
|
87
|
+
if (close < 0) continue;
|
|
88
|
+
const stmtEnd = m.indexOf(';', close);
|
|
89
|
+
const tail = v.text.slice(close, stmtEnd < 0 ? close : stmtEnd);
|
|
90
|
+
filters.push({ view: v, start: x.index!, end: Math.max(close, stmtEnd < 0 ? close : stmtEnd), ...lists(tail) });
|
|
91
|
+
}
|
|
92
|
+
for (const x of m.matchAll(/\$this->authorizeResource\s*\(/g)) {
|
|
93
|
+
const open = x.index! + x[0].length - 1;
|
|
94
|
+
const close = closeOf(m, open);
|
|
95
|
+
policy = true;
|
|
96
|
+
filters.push({ view: v, start: x.index!, end: close < 0 ? open : close, only: null, except: null });
|
|
97
|
+
}
|
|
98
|
+
const sm = /static\s+function\s+middleware\s*\(/.exec(m);
|
|
99
|
+
if (sm) {
|
|
100
|
+
const f = phpFunc(m, sm.index);
|
|
101
|
+
if (f) {
|
|
102
|
+
const body = v.text.slice(f.bodyStart, f.end);
|
|
103
|
+
const bm = m.slice(f.bodyStart, f.end);
|
|
104
|
+
let covered = 0;
|
|
105
|
+
for (const x of bm.matchAll(/new\s+(?:\\?[\w\\]*\\)?Middleware\s*\(/g)) {
|
|
106
|
+
const open = f.bodyStart + x.index! + x[0].length - 1;
|
|
107
|
+
const close = closeOf(m, open);
|
|
108
|
+
if (close < 0) continue;
|
|
109
|
+
const t = v.text.slice(open, close);
|
|
110
|
+
filters.push({ view: v, start: open, end: close, only: /only:\s*\[([^\]]*)\]/.exec(t) ? strs(/only:\s*\[([^\]]*)\]/.exec(t)![1]) : null, except: /except:\s*\[([^\]]*)\]/.exec(t) ? strs(/except:\s*\[([^\]]*)\]/.exec(t)![1]) : null });
|
|
111
|
+
covered += close - open;
|
|
112
|
+
}
|
|
113
|
+
if (body.length) for (const x of body.matchAll(/(?<![\w(,]\s*)['"]([\w.:,-]+)['"]/g)) { void x; }
|
|
114
|
+
if (!filters.some((fl) => fl.view === v && fl.start >= f.bodyStart && fl.end <= f.end)) filters.push({ view: v, start: f.bodyStart, end: f.end, only: null, except: null });
|
|
115
|
+
void covered;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const cm = /^[ \t]*(?:#\[[^\n]*\]\s*)+(?=(?:final\s+|abstract\s+)?class\b)/m.exec(m);
|
|
119
|
+
if (cm) filters.push({ view: v, start: cm.index, end: cm.index + cm[0].length, only: null, except: null });
|
|
120
|
+
return { filters, policy };
|
|
121
|
+
};
|
|
122
|
+
const methodAttrs = (v: FileView, fnStart: number): LightDeco | null => {
|
|
123
|
+
const before = v.text.slice(Math.max(0, fnStart - 400), fnStart);
|
|
124
|
+
const am = /((?:^|\n)[ \t]*#\[[^\n]*\][ \t]*\n[ \t]*)+(?:(?:public|protected|private|static)\s+)*$/.exec(before);
|
|
125
|
+
return am ? { view: v, start: fnStart - am[0].length, end: fnStart, scope: 'router' } : null;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
for (const rf of files) {
|
|
129
|
+
const v = repo.view(rf);
|
|
130
|
+
if (!v) continue;
|
|
131
|
+
const m = v.masked;
|
|
132
|
+
const isApi = /(?:^|\/)api\.php$/.test(rf);
|
|
133
|
+
const base: Ctx = { prefix: isApi ? '/api' : '', mws: [], controller: null, without: [] };
|
|
134
|
+
// Providers that load this file through a group: Route::prefix('api/v1')->middleware('api')->group(base_path('routes/api.php'))
|
|
135
|
+
const name = /([\w-]+)\.php$/.exec(rf)![1];
|
|
136
|
+
for (const { f, t } of bootText) {
|
|
137
|
+
const pm = new RegExp(`Route::([^;]*?)->group\\s*\\(\\s*base_path\\s*\\(\\s*['"]routes/${name}\\.php['"]`).exec(t);
|
|
138
|
+
if (pm) {
|
|
139
|
+
const bv = repo.view(f);
|
|
140
|
+
const pre = /prefix\s*\(\s*['"]([^'"]*)['"]/.exec(pm[1]);
|
|
141
|
+
if (pre) base.prefix = joinPath('', pre[1]);
|
|
142
|
+
if (bv && pm.index !== undefined) base.mws.push({ view: bv, start: pm.index, end: pm.index + pm[0].length });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const handle = (calls: Call[], ctx: Ctx, at: number): void => {
|
|
147
|
+
// Modifiers before the terminal call apply to everything under it; modifiers after it apply to the route.
|
|
148
|
+
let c: Ctx = { ...ctx, mws: ctx.mws.slice(), without: ctx.without.slice() };
|
|
149
|
+
const term = calls.findIndex((x) => VERBS.has(x.name) || ['match', 'resource', 'apiResource', 'resources', 'apiResources', 'singleton', 'group', 'webhooks'].includes(x.name));
|
|
150
|
+
const route: Mw[] = [];
|
|
151
|
+
const apply = (x: Call, into: Ctx, routeLevel: boolean): void => {
|
|
152
|
+
const a = splitArgs(m, x.open);
|
|
153
|
+
const range = { view: v, start: x.open - x.name.length - 2, end: x.close };
|
|
154
|
+
if (x.name === 'prefix' && a[0]) into.prefix = joinPath(into.prefix, strs(v.text.slice(a[0].start, a[0].end))[0] ?? '');
|
|
155
|
+
else if (x.name === 'middleware') (routeLevel ? route : into.mws).push(range);
|
|
156
|
+
else if (x.name === 'can') (routeLevel ? route : into.mws).push(range);
|
|
157
|
+
else if (x.name === 'withoutMiddleware') into.without.push(...strs(v.text.slice(x.open, x.close)));
|
|
158
|
+
else if (x.name === 'controller' && a[0]) into.controller = /(\w+)::class/.exec(v.text.slice(a[0].start, a[0].end))?.[1] ?? null;
|
|
159
|
+
};
|
|
160
|
+
const mods = term < 0 ? calls : calls.slice(0, term);
|
|
161
|
+
for (const x of mods) apply(x, c, false);
|
|
162
|
+
if (term < 0) return;
|
|
163
|
+
const t = calls[term];
|
|
164
|
+
const after = calls.slice(term + 1);
|
|
165
|
+
if (t.name === 'group') {
|
|
166
|
+
const a = splitArgs(m, t.open);
|
|
167
|
+
// Route::group(['prefix' => 'x', 'middleware' => ['auth']], function () { ... })
|
|
168
|
+
if (a.length === 2) {
|
|
169
|
+
const arr = v.text.slice(a[0].start, a[0].end);
|
|
170
|
+
const px = /['"]prefix['"]\s*=>\s*['"]([^'"]*)['"]/.exec(arr);
|
|
171
|
+
if (px) c.prefix = joinPath(c.prefix, px[1]);
|
|
172
|
+
const mw = /['"]middleware['"]\s*=>/.exec(arr);
|
|
173
|
+
if (mw) c.mws.push({ view: v, start: a[0].start + mw.index, end: a[0].end });
|
|
174
|
+
}
|
|
175
|
+
const closure = a.find((x) => /^(?:static\s+)?(?:function|fn)\b/.test(m.slice(x.start, x.end)));
|
|
176
|
+
if (closure) {
|
|
177
|
+
const body = /\{/.exec(m.slice(closure.start, closure.end));
|
|
178
|
+
if (body) {
|
|
179
|
+
const bs = closure.start + body.index;
|
|
180
|
+
const be = closeOf(m, bs);
|
|
181
|
+
for (const x of after) apply(x, c, false);
|
|
182
|
+
walk(bs + 1, be < 0 ? closure.end : be - 1, c);
|
|
183
|
+
} else if (/^(?:static\s+)?fn\b/.test(m.slice(closure.start, closure.end))) walk(closure.start, closure.end, c);
|
|
184
|
+
}
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
for (const x of after) apply(x, c, true);
|
|
188
|
+
const args = splitArgs(m, t.open);
|
|
189
|
+
const line = v.lines.at(at);
|
|
190
|
+
const text = (a: { start: number; end: number }): string => v.text.slice(a.start, a.end);
|
|
191
|
+
const emit = (verb: string, path: string, handler: { start: number; end: number } | null, cls: string | null, method: string | null, extraName: string | null, ctrlOverride?: string | null): void => {
|
|
192
|
+
const full = joinPath(c.prefix, phpPath(path));
|
|
193
|
+
const cname = cls ?? ctrlOverride ?? null;
|
|
194
|
+
const cv = cname ? classes.get(cname) : undefined;
|
|
195
|
+
const fnDef = cv && method ? fn.defs(method).find((d) => d.view.file === cv.file) : undefined;
|
|
196
|
+
const mws = [...c.mws.filter((x) => !c.without.some((w) => v.text.slice(x.start, x.end).includes(w))), ...route];
|
|
197
|
+
const decos: LightDeco[] = [];
|
|
198
|
+
const extra: Protection[] = [];
|
|
199
|
+
for (const x of mws) {
|
|
200
|
+
decos.push({ view: x.view, start: x.start, end: x.end, scope: x.view === v && route.includes(x) ? 'wrapper' : 'router' });
|
|
201
|
+
// A middleware alias or class that lives in the repository: read the class.
|
|
202
|
+
for (const nm of [...strs(x.view.text.slice(x.start, x.end)), ...[...x.view.text.slice(x.start, x.end).matchAll(/(\w+)::class/g)].map((y) => y[1])]) {
|
|
203
|
+
const cls2 = aliases.get(nm.split(':')[0]) ?? nm;
|
|
204
|
+
const mv = classes.get(cls2);
|
|
205
|
+
if (mv && /Middleware\//.test(mv.file)) decos.push({ view: mv, start: 0, end: mv.text.length, scope: 'router' });
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
let policy = false;
|
|
209
|
+
let seeds: string[] = [];
|
|
210
|
+
const bound: { name: string; target: string }[] = [];
|
|
211
|
+
let hv: FileView = v;
|
|
212
|
+
let start = m.lastIndexOf('\n', at) + 1;
|
|
213
|
+
let end = t.close;
|
|
214
|
+
let params = '';
|
|
215
|
+
let found = false;
|
|
216
|
+
if (handler) {
|
|
217
|
+
const isClosure = /^(?:static\s+)?(?:function|fn)\b/.test(m.slice(handler.start, handler.end));
|
|
218
|
+
if (isClosure) {
|
|
219
|
+
const f = /^(?:static\s+)?function\b/.test(m.slice(handler.start, handler.end)) ? phpFunc(m, handler.start + m.slice(handler.start).indexOf('function')) : null;
|
|
220
|
+
if (f) { start = f.start; end = f.end; params = f.params; found = true; } else { start = handler.start; end = handler.end; params = /\(([^)]*)\)/.exec(m.slice(handler.start, handler.end))?.[1] ?? ''; found = true; }
|
|
221
|
+
}
|
|
222
|
+
} else if (fnDef && cv) {
|
|
223
|
+
hv = cv; start = fnDef.start; end = fnDef.end; found = true;
|
|
224
|
+
const f = phpFunc(cv.masked, fnDef.start);
|
|
225
|
+
params = f?.params ?? '';
|
|
226
|
+
const { filters, policy: pol } = ctrlFilters(cname!);
|
|
227
|
+
for (const fl of filters) {
|
|
228
|
+
if (fl.only && (!method || !fl.only.includes(method))) continue;
|
|
229
|
+
if (fl.except && method && fl.except.includes(method)) continue;
|
|
230
|
+
decos.push({ view: fl.view, start: fl.start, end: fl.end, scope: 'router' });
|
|
231
|
+
}
|
|
232
|
+
policy = pol;
|
|
233
|
+
const attr = methodAttrs(cv, fnDef.start);
|
|
234
|
+
if (attr) decos.push(attr);
|
|
235
|
+
}
|
|
236
|
+
for (const part of params.split(/,(?![^(]*\))/)) {
|
|
237
|
+
const pm = /^\s*(?:(?:public|protected|private|readonly)\s+)*(?:\??([\w\\]+)\s+)?(?:\.\.\.)?&?(\$\w+)/.exec(part);
|
|
238
|
+
if (!pm) continue;
|
|
239
|
+
const typ = pm[1]?.split('\\').pop() ?? null;
|
|
240
|
+
if (typ && /Request$/.test(typ)) continue;
|
|
241
|
+
if (typ && isModel(typ)) bound.push({ name: pm[2], target: typ });
|
|
242
|
+
else if (!typ || /^(?:int|string|float|bool|mixed|array)$/.test(typ)) seeds.push(pm[2]);
|
|
243
|
+
}
|
|
244
|
+
if (apiThrottle && isApi) extra.push(apiThrottle);
|
|
245
|
+
const a = analyzeLight(hv, { start, end, seeds, decorators: decos, extra, lookup: fn.find, local, policyScoped: policy, bound });
|
|
246
|
+
out.entries.push(makeEntry(repo, {
|
|
247
|
+
kind: 'http_route', framework: 'laravel', file: rf, line, method: verb, path: full || '/', name: extraName ?? (cname && method ? `${cname}@${method}` : null),
|
|
248
|
+
confidence: found ? 'high' : 'low', handlerView: hv, spec: { start, end, seeds }, analysis: a,
|
|
249
|
+
}));
|
|
250
|
+
};
|
|
251
|
+
const parseHandler = (a: { start: number; end: number } | undefined): { handler: { start: number; end: number } | null; cls: string | null; method: string | null } => {
|
|
252
|
+
if (!a) return { handler: null, cls: c.controller, method: null };
|
|
253
|
+
const t2 = text(a).trim();
|
|
254
|
+
const arr = /^\[\s*\\?(?:[\w\\]*\\)?(\w+)::class\s*,\s*['"](\w+)['"]\s*\]$/.exec(t2);
|
|
255
|
+
if (arr) return { handler: null, cls: arr[1], method: arr[2] };
|
|
256
|
+
const str = /^['"](?:[\w\\]*\\)?(\w+)@(\w+)['"]$/.exec(t2);
|
|
257
|
+
if (str) return { handler: null, cls: str[1], method: str[2] };
|
|
258
|
+
const inv = /^\\?(?:[\w\\]*\\)?(\w+)::class$/.exec(t2);
|
|
259
|
+
if (inv) return { handler: null, cls: inv[1], method: '__invoke' };
|
|
260
|
+
const mt = /^['"](\w+)['"]$/.exec(t2);
|
|
261
|
+
if (mt && c.controller) return { handler: null, cls: c.controller, method: mt[1] };
|
|
262
|
+
if (/^(?:static\s+)?(?:function|fn)\b/.test(m.slice(a.start, a.end).trim())) return { handler: a, cls: null, method: null };
|
|
263
|
+
return { handler: null, cls: null, method: null };
|
|
264
|
+
};
|
|
265
|
+
if (VERBS.has(t.name)) {
|
|
266
|
+
const p = strs(text(args[0] ?? { start: 0, end: 0 }))[0];
|
|
267
|
+
if (p === undefined) return;
|
|
268
|
+
const h = parseHandler(args[1]);
|
|
269
|
+
if (!h.handler && !h.cls && args[1] === undefined) return;
|
|
270
|
+
emit(t.name === 'any' ? 'ANY' : t.name.toUpperCase(), p, h.handler, h.cls, h.method, null);
|
|
271
|
+
} else if (t.name === 'match') {
|
|
272
|
+
const verbs = strs(text(args[0] ?? { start: 0, end: 0 })).map((x) => x.toUpperCase());
|
|
273
|
+
const p = strs(text(args[1] ?? { start: 0, end: 0 }))[0];
|
|
274
|
+
if (p === undefined) return;
|
|
275
|
+
const h = parseHandler(args[2]);
|
|
276
|
+
for (const verb of verbs.length ? verbs : ['ANY']) emit(verb, p, h.handler, h.cls, h.method, null);
|
|
277
|
+
} else if (t.name === 'resource' || t.name === 'apiResource' || t.name === 'singleton') {
|
|
278
|
+
const nm = strs(text(args[0] ?? { start: 0, end: 0 }))[0];
|
|
279
|
+
const cls = /(\w+)::class/.exec(text(args[1] ?? { start: 0, end: 0 }))?.[1] ?? null;
|
|
280
|
+
if (!nm || !cls) return;
|
|
281
|
+
const only = after.find((x) => x.name === 'only');
|
|
282
|
+
const except = after.find((x) => x.name === 'except');
|
|
283
|
+
const onlyL = only ? strs(v.text.slice(only.open, only.close)) : null;
|
|
284
|
+
const exceptL = except ? strs(v.text.slice(except.open, except.close)) : null;
|
|
285
|
+
const segs = nm.split('.');
|
|
286
|
+
const prefix = segs.slice(0, -1).map((s) => `/${s}/:${singular(s)}`).join('');
|
|
287
|
+
const last = segs[segs.length - 1];
|
|
288
|
+
const param = singular(last);
|
|
289
|
+
const acts: [string, string, string][] = t.name === 'singleton'
|
|
290
|
+
? [['show', 'GET', ''], ['update', 'PUT', ''], ['update', 'PATCH', '']]
|
|
291
|
+
: [['index', 'GET', ''], ['create', 'GET', '/create'], ['store', 'POST', ''], ['show', 'GET', `/:${param}`], ['edit', 'GET', `/:${param}/edit`], ['update', 'PUT', `/:${param}`], ['update', 'PATCH', `/:${param}`], ['destroy', 'DELETE', `/:${param}`]];
|
|
292
|
+
for (const [act, verb, sfx] of acts) {
|
|
293
|
+
if (t.name === 'apiResource' && (act === 'create' || act === 'edit')) continue;
|
|
294
|
+
if (onlyL && !onlyL.includes(act)) continue;
|
|
295
|
+
if (exceptL && exceptL.includes(act)) continue;
|
|
296
|
+
emit(verb, `${prefix}/${last}${sfx}`, null, cls, act, null);
|
|
297
|
+
}
|
|
298
|
+
} else if (t.name === 'resources' || t.name === 'apiResources') {
|
|
299
|
+
for (const x of v.text.slice(t.open, t.close).matchAll(/['"]([\w.-]+)['"]\s*=>\s*(\w+)::class/g)) {
|
|
300
|
+
const param = singular(x[1]);
|
|
301
|
+
const acts: [string, string, string][] = [['index', 'GET', ''], ['store', 'POST', ''], ['show', 'GET', `/:${param}`], ['update', 'PUT', `/:${param}`], ['update', 'PATCH', `/:${param}`], ['destroy', 'DELETE', `/:${param}`]];
|
|
302
|
+
for (const [act, verb, sfx] of acts) emit(verb, `/${x[1]}${sfx}`, null, x[2], act, null);
|
|
303
|
+
}
|
|
304
|
+
} else if (t.name === 'webhooks') {
|
|
305
|
+
const p = strs(text(args[0] ?? { start: 0, end: 0 }))[0];
|
|
306
|
+
if (p) emit('POST', p, null, null, null, 'webhook-client');
|
|
307
|
+
}
|
|
308
|
+
void c;
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
const walk = (from: number, to: number, ctx: Ctx): void => {
|
|
312
|
+
let i = from;
|
|
313
|
+
while (i < to) {
|
|
314
|
+
const at = m.indexOf('Route::', i);
|
|
315
|
+
if (at < 0 || at >= to) break;
|
|
316
|
+
const prev = m.slice(Math.max(0, at - 1), at);
|
|
317
|
+
if (/[\w$>]/.test(prev)) { i = at + 7; continue; }
|
|
318
|
+
const ch = chainAt(v, at);
|
|
319
|
+
if (!ch.calls.length) { i = at + 7; continue; }
|
|
320
|
+
handle(ch.calls, ctx, at);
|
|
321
|
+
i = Math.max(ch.end, at + 7);
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
walk(0, m.length, base);
|
|
325
|
+
}
|
|
326
|
+
return out;
|
|
327
|
+
}
|