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
package/src/map/py.ts
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
// Python entry points: Flask and FastAPI decorators, add_url_rule, Flask-RESTful resources, Celery and scheduler jobs, and
|
|
2
|
+
// tools handed to a model. Django is in py-django.ts. Pattern based, like the JavaScript extractors.
|
|
3
|
+
import type { Gate, Protection } from '../types/index.ts';
|
|
4
|
+
import { analyze, type FileView, type Spec } from './analyze.ts';
|
|
5
|
+
import { empty, joinPath, makeEntry, type Extracted } from './entry.ts';
|
|
6
|
+
import { closeOf, pyBlock, splitArgs } from './lex.ts';
|
|
7
|
+
import type { Repo } from './repo.ts';
|
|
8
|
+
|
|
9
|
+
export interface Deco { name: string; start: number; end: number; open: number }
|
|
10
|
+
export interface Group { decos: Deco[]; kind: 'def' | 'class'; name: string; lineStart: number; defStart: number }
|
|
11
|
+
|
|
12
|
+
// Decorator groups: each run of decorators followed by a def or class.
|
|
13
|
+
export function decoratorGroups(v: FileView): Group[] {
|
|
14
|
+
const out: Group[] = [];
|
|
15
|
+
const m = v.masked;
|
|
16
|
+
const re = /^[ \t]*@/gm;
|
|
17
|
+
let from = 0;
|
|
18
|
+
for (let x = re.exec(m); x; x = re.exec(m)) {
|
|
19
|
+
if (x.index < from) continue;
|
|
20
|
+
const decos: Deco[] = [];
|
|
21
|
+
let i = x.index;
|
|
22
|
+
for (;;) {
|
|
23
|
+
const at = m.indexOf('@', i);
|
|
24
|
+
if (at < 0 || /\S/.test(m.slice(i, at))) break;
|
|
25
|
+
const nm = /^@\s*([\w.]+)/.exec(m.slice(at));
|
|
26
|
+
if (!nm) break;
|
|
27
|
+
let end = at + nm[0].length;
|
|
28
|
+
let open = -1;
|
|
29
|
+
if (m[end] === '(') { open = end; const c = closeOf(m, end); if (c < 0) break; end = c; }
|
|
30
|
+
decos.push({ name: nm[1], start: at, end, open });
|
|
31
|
+
i = end;
|
|
32
|
+
const nxt = /^\s*(?=@|(?:async\s+)?def\s|class\s)/.exec(m.slice(i, i + 400));
|
|
33
|
+
if (!nxt) break;
|
|
34
|
+
i += nxt[0].length;
|
|
35
|
+
if (m[i] !== '@') break;
|
|
36
|
+
}
|
|
37
|
+
if (!decos.length) continue;
|
|
38
|
+
const tail = /^\s*((?:async\s+)?def|class)\s+([A-Za-z_]\w*)/.exec(m.slice(decos[decos.length - 1].end, decos[decos.length - 1].end + 400));
|
|
39
|
+
if (!tail) continue;
|
|
40
|
+
const nameIdx = decos[decos.length - 1].end + tail[0].length - tail[2].length;
|
|
41
|
+
const lineStart = m.lastIndexOf('\n', nameIdx) + 1;
|
|
42
|
+
out.push({ decos, kind: tail[1] === 'class' ? 'class' : 'def', name: tail[2], lineStart, defStart: nameIdx });
|
|
43
|
+
from = lineStart + 1;
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function pyParams(masked: string, from: number): string[] {
|
|
49
|
+
const open = masked.indexOf('(', from);
|
|
50
|
+
if (open < 0) return [];
|
|
51
|
+
const close = closeOf(masked, open);
|
|
52
|
+
const inner = masked.slice(open + 1, close - 1);
|
|
53
|
+
const out: string[] = [];
|
|
54
|
+
let depth = 0;
|
|
55
|
+
let cur = '';
|
|
56
|
+
const flush = (): void => {
|
|
57
|
+
const name = /^\s*\*{0,2}([A-Za-z_]\w*)/.exec(cur)?.[1];
|
|
58
|
+
if (name && name !== 'self' && name !== 'cls' && !/Depends\s*\(|Security\s*\(/.test(cur)) out.push(name);
|
|
59
|
+
cur = '';
|
|
60
|
+
};
|
|
61
|
+
for (const c of inner) { if ('([{'.includes(c)) depth++; else if (')]}'.includes(c)) depth--; if (c === ',' && depth === 0) flush(); else cur += c; }
|
|
62
|
+
flush();
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface PyImport { module: string; attr: string | null }
|
|
67
|
+
export function pyImports(v: FileView): Map<string, PyImport> {
|
|
68
|
+
const out = new Map<string, PyImport>();
|
|
69
|
+
for (const m of v.text.matchAll(/^[ \t]*from\s+(\.*[\w.]*)\s+import\s+(\([^)]*\)|[^\n]+)/gm)) {
|
|
70
|
+
for (const part of m[2].replace(/[()]/g, ' ').split(',')) {
|
|
71
|
+
const [attr, alias] = part.trim().split(/\s+as\s+/);
|
|
72
|
+
if (attr && /^[\w*]+$/.test(attr)) out.set(alias ?? attr, { module: m[1], attr });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
for (const m of v.text.matchAll(/^[ \t]*import\s+([\w.]+)(?:\s+as\s+(\w+))?/gm)) out.set(m[2] ?? m[1].split('.')[0], { module: m[1], attr: null });
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function resolvePyModule(repo: Repo, from: string, dotted: string): string | null {
|
|
80
|
+
let rel = 0;
|
|
81
|
+
while (dotted[rel] === '.') rel++;
|
|
82
|
+
const rest = dotted.slice(rel).replace(/\./g, '/');
|
|
83
|
+
const candidates = (base: string): string[] => (base ? [`${base}.py`, `${base}/__init__.py`] : []);
|
|
84
|
+
if (rel > 0) {
|
|
85
|
+
const parts = from.split('/').slice(0, -1);
|
|
86
|
+
for (let i = 1; i < rel; i++) parts.pop();
|
|
87
|
+
const base = [...parts, ...(rest ? [rest] : [])].join('/');
|
|
88
|
+
return candidates(base).find((c) => repo.fileSet.has(c)) ?? null;
|
|
89
|
+
}
|
|
90
|
+
if (!rest) return null;
|
|
91
|
+
const exact = candidates(rest).find((c) => repo.fileSet.has(c));
|
|
92
|
+
if (exact) return exact;
|
|
93
|
+
const suffix = candidates(rest).flatMap((c) => repo.ctx.files.filter((f) => f.endsWith('/' + c)));
|
|
94
|
+
return suffix.sort()[0] ?? null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const strArg = (t: string): string | null => /^\s*(?:[rRuUbB]{0,2})(['"])((?:\\.|(?!\1).)*)\1/.exec(t)?.[2] ?? null;
|
|
98
|
+
const kwStr = (args: string, key: string): string | null => { const m = new RegExp(`(?:^|[,(\\s])${key}\\s*=\\s*[rRuU]?(['"])([^'"]*)\\1`).exec(args); return m ? m[2] : null; };
|
|
99
|
+
|
|
100
|
+
interface Receiver { name: string; prefix: string; deps: { start: number; end: number } | null; isApp: boolean }
|
|
101
|
+
|
|
102
|
+
export function extractPython(repo: Repo, v: FileView): Extracted {
|
|
103
|
+
const out = empty();
|
|
104
|
+
const { masked, text } = v;
|
|
105
|
+
const flaskish = /\bflask\b|\bFlask\b|\bBlueprint\b|\bfastapi\b|\bFastAPI\b|\bAPIRouter\b|\bquart\b|\bsanic\b|\bstarlette\b|\bbottle\b|\bfalcon\b|\baiohttp\b|\blitestar\b|\bflask_restful\b|\bflask_restx\b|\bconnexion\b|\bceleryd?\b|\bshared_task\b|\bapscheduler\b|\bchalice\b|\bflask_smorest\b|\btool\b|\bmcp\b/.test(v.imports + text.slice(0, 2000));
|
|
106
|
+
if (!flaskish) return out;
|
|
107
|
+
const helpers = repo.helpers('py');
|
|
108
|
+
const imps = pyImports(v);
|
|
109
|
+
|
|
110
|
+
// Receivers: app = Flask(...), bp = Blueprint(...), router = APIRouter(...)
|
|
111
|
+
const receivers = new Map<string, Receiver>();
|
|
112
|
+
for (const m of masked.matchAll(/^[ \t]*([A-Za-z_]\w*)\s*(?::[^=\n]+)?=\s*(Flask|Blueprint|APIRouter|FastAPI|Quart|Sanic|Starlette|Router|Api|Namespace)\s*\(/gm)) {
|
|
113
|
+
const open = m.index! + m[0].length - 1;
|
|
114
|
+
const close = closeOf(masked, open);
|
|
115
|
+
if (close < 0) continue;
|
|
116
|
+
const args = text.slice(open, close);
|
|
117
|
+
const prefix = kwStr(args, 'url_prefix') ?? kwStr(args, 'prefix') ?? kwStr(args, 'path') ?? '';
|
|
118
|
+
const hasDeps = /dependencies\s*=/.test(args);
|
|
119
|
+
receivers.set(m[1], { name: m[1], prefix, deps: hasDeps ? { start: open, end: close } : null, isApp: /^(Flask|FastAPI|Quart|Sanic|Starlette)$/.test(m[2]) });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// before_request hooks: protections for every route of that receiver (app: for the whole app).
|
|
123
|
+
const hookDecos = new Map<string, { start: number; end: number }[]>();
|
|
124
|
+
const groups = decoratorGroups(v);
|
|
125
|
+
for (const g of groups) {
|
|
126
|
+
for (const d of g.decos) {
|
|
127
|
+
const hook = /^(\w+)\.(before_request|before_app_request|middleware|before_first_request)$/.exec(d.name);
|
|
128
|
+
if (!hook || g.kind !== 'def') continue;
|
|
129
|
+
const b = pyBlock(masked, v.lines, g.lineStart);
|
|
130
|
+
const rec = receivers.get(hook[1]);
|
|
131
|
+
const spec: Spec = { start: g.lineStart, end: b.end, seeds: [], decorators: [], returnsJson: false };
|
|
132
|
+
const a = analyze(v, spec, helpers);
|
|
133
|
+
const protections: Protection[] = a.protections.filter((p) => p.kind !== 'owner_filter').map((p) => ({ ...p, scope: 'middleware' as const, enforced: p.enforced ?? true }));
|
|
134
|
+
if (!protections.length) continue;
|
|
135
|
+
if (rec?.isApp || hook[2] === 'middleware') {
|
|
136
|
+
const gate: Gate = { id: `${v.file}:${v.lines.at(g.lineStart)}:${hook[2]}`, kind: 'middleware', framework: 'flask', file: v.file, line: v.lines.at(g.lineStart), paths: ['*'], methods: [], protections, confidence: 'medium' };
|
|
137
|
+
out.gates.push(gate);
|
|
138
|
+
} else {
|
|
139
|
+
const list = hookDecos.get(hook[1]) ?? [];
|
|
140
|
+
list.push({ start: g.lineStart, end: b.end });
|
|
141
|
+
hookDecos.set(hook[1], list);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Routes by decorator.
|
|
147
|
+
const reg = /^(\w+)\.(route|get|post|put|patch|delete|head|options|api_route|websocket|websocket_route|on_event)$/;
|
|
148
|
+
for (const g of groups) {
|
|
149
|
+
if (g.kind !== 'def') continue;
|
|
150
|
+
const rd = g.decos.find((d) => reg.test(d.name) && d.open >= 0);
|
|
151
|
+
if (!rd) continue;
|
|
152
|
+
const rm = reg.exec(rd.name)!;
|
|
153
|
+
if (rm[2] === 'on_event') continue;
|
|
154
|
+
const rec = receivers.get(rm[1]);
|
|
155
|
+
if (!rec && !/^(app|bp|api|router|blueprint|server|v\d+|\w*router|\w*bp|\w*app)$/i.test(rm[1])) continue;
|
|
156
|
+
const args = text.slice(rd.open, rd.end);
|
|
157
|
+
const first = splitArgs(masked, rd.open)[0];
|
|
158
|
+
const path = first ? strArg(text.slice(first.start, first.end)) ?? kwStr(args, 'path') : kwStr(args, 'path');
|
|
159
|
+
if (path === null) continue;
|
|
160
|
+
let methods: string[];
|
|
161
|
+
if (rm[2] === 'route' || rm[2] === 'api_route') {
|
|
162
|
+
const ml = /methods\s*=\s*[\[(]([^\])]*)[\])]/.exec(args);
|
|
163
|
+
methods = ml ? [...ml[1].matchAll(/['"](\w+)['"]/g)].map((x) => x[1].toUpperCase()) : ['GET'];
|
|
164
|
+
if (!methods.length) methods = ['GET'];
|
|
165
|
+
} else methods = [rm[2].startsWith('websocket') ? 'WS' : rm[2].toUpperCase()];
|
|
166
|
+
const b = pyBlock(masked, v.lines, g.lineStart);
|
|
167
|
+
const decoSpecs: NonNullable<Spec['decorators']> = g.decos.map((d) => ({ view: v, start: d.start, end: d.end, scope: 'router' as const }));
|
|
168
|
+
if (rec?.deps) decoSpecs.push({ view: v, start: rec.deps.start, end: rec.deps.end, scope: 'router' });
|
|
169
|
+
for (const h of hookDecos.get(rm[1]) ?? []) decoSpecs.push({ view: v, start: h.start, end: h.end, scope: 'router' });
|
|
170
|
+
const params = pyParams(masked, g.defStart);
|
|
171
|
+
const framework = /fastapi|starlette|litestar/i.test(v.imports) ? 'fastapi' : /quart/i.test(v.imports) ? 'quart' : /sanic/i.test(v.imports) ? 'sanic' : 'flask';
|
|
172
|
+
for (const method of methods) {
|
|
173
|
+
const e = makeEntry(repo, { kind: 'http_route', framework, file: v.file, line: v.lines.at(rd.start), method, path: joinPath(rec?.prefix ?? '', path), name: g.name, confidence: 'high', handlerView: v, spec: { start: g.lineStart, end: b.end, seeds: [...params, 'request'], decorators: decoSpecs, returnsJson: true } });
|
|
174
|
+
// FastAPI: a parameter typed with a pydantic model is validated; Form, File and Query parameters are reads.
|
|
175
|
+
fastapiParams(repo, v, g, e);
|
|
176
|
+
out.entries.push(e);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// add_url_rule('/x', view_func=f, methods=[...]) and api.add_resource(Cls, '/x').
|
|
181
|
+
for (const m of masked.matchAll(/\b(\w+)\.(add_url_rule|add_resource|add_api_route|add_route|add_websocket_route)\s*\(/g)) {
|
|
182
|
+
const open = m.index! + m[0].length - 1;
|
|
183
|
+
const args = splitArgs(masked, open);
|
|
184
|
+
const argText = (i: number): string => (args[i] ? text.slice(args[i].start, args[i].end) : '');
|
|
185
|
+
const rec = receivers.get(m[1]);
|
|
186
|
+
if (m[2] === 'add_resource') {
|
|
187
|
+
const cls = /^[A-Za-z_]\w*/.exec(argText(0))?.[0];
|
|
188
|
+
const paths = args.slice(1).map((_, i) => strArg(argText(i + 1))).filter((x): x is string => !!x);
|
|
189
|
+
if (cls && paths.length) pyClassMethods(repo, v, cls).forEach((cm) => { for (const p of paths) out.entries.push(makeEntry(repo, { kind: 'http_route', framework: 'flask-restful', file: cm.view.file, line: cm.view.lines.at(cm.start), method: cm.method, path: joinPath(rec?.prefix ?? '', p), name: `${cls}.${cm.method.toLowerCase()}`, confidence: 'medium', handlerView: cm.view, spec: { start: cm.start, end: cm.end, seeds: [...pyParams(cm.view.masked, cm.start), 'request'], decorators: classDecos(cm.view, cls), returnsJson: true } })); });
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
const path = strArg(argText(0));
|
|
193
|
+
if (path === null) continue;
|
|
194
|
+
const viewFunc = /view_func\s*=\s*([\w.]+)|^\s*[\w"']+\s*,\s*([\w.]+)\s*[,)]/.exec(argText(1) ? text.slice(args[1].start, args[args.length - 1].end) : '')?.[1] ?? (args[1] ? /^[A-Za-z_][\w.]*/.exec(argText(1))?.[0] : null) ?? null;
|
|
195
|
+
if (!viewFunc) continue;
|
|
196
|
+
const fname = viewFunc.replace(/\.as_view$/, '').split('.')[0];
|
|
197
|
+
const methods = /methods\s*=\s*[\[(]([^\])]*)[\])]/.exec(text.slice(open, closeOf(masked, open)))?.[1];
|
|
198
|
+
const ms = methods ? [...methods.matchAll(/['"](\w+)['"]/g)].map((x) => x[1].toUpperCase()) : ['GET'];
|
|
199
|
+
const fn = repo.defs('py', fname).sort((a, b) => (a.view.file === v.file ? -1 : 0) - (b.view.file === v.file ? -1 : 0))[0];
|
|
200
|
+
if (/as_view/.test(argText(1)) || /as_view/.test(text.slice(open, closeOf(masked, open)))) {
|
|
201
|
+
const cls = /(\w+)\.as_view/.exec(text.slice(open, closeOf(masked, open)))?.[1];
|
|
202
|
+
if (!cls) continue;
|
|
203
|
+
for (const cm of pyClassMethods(repo, v, cls)) out.entries.push(makeEntry(repo, { kind: 'http_route', framework: 'flask', file: cm.view.file, line: cm.view.lines.at(cm.start), method: cm.method, path: joinPath(rec?.prefix ?? '', path), name: `${cls}.${cm.method.toLowerCase()}`, confidence: 'medium', handlerView: cm.view, spec: { start: cm.start, end: cm.end, seeds: [...pyParams(cm.view.masked, cm.start), 'request'], decorators: classDecos(cm.view, cls), returnsJson: true } }));
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
if (!fn) continue;
|
|
207
|
+
const b = pyBlock(fn.view.masked, fn.view.lines, fn.start);
|
|
208
|
+
const decos = decoratorsAbove(fn.view, fn.start);
|
|
209
|
+
for (const method of ms) out.entries.push(makeEntry(repo, { kind: 'http_route', framework: 'flask', file: v.file, line: v.lines.at(m.index!), method, path: joinPath(rec?.prefix ?? '', path), name: fname, confidence: 'medium', handlerView: fn.view, spec: { start: fn.start, end: b.end, seeds: [...pyParams(fn.view.masked, fn.start), 'request'], decorators: decos, returnsJson: true } }));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Mounts: app.register_blueprint(bp, url_prefix=...), app.include_router(mod.router, prefix=..., dependencies=[...]).
|
|
213
|
+
for (const m of masked.matchAll(/\b(\w+)\.(register_blueprint|include_router|mount)\s*\(/g)) {
|
|
214
|
+
const open = m.index! + m[0].length - 1;
|
|
215
|
+
const close = closeOf(masked, open);
|
|
216
|
+
if (close < 0) continue;
|
|
217
|
+
const args = splitArgs(masked, open);
|
|
218
|
+
const first = args[0] ? text.slice(args[0].start, args[0].end) : '';
|
|
219
|
+
const head = /^([A-Za-z_]\w*)/.exec(first)?.[1];
|
|
220
|
+
const imp = head ? imps.get(head) : undefined;
|
|
221
|
+
const callText = text.slice(open, close);
|
|
222
|
+
const prefix = kwStr(callText, 'url_prefix') ?? kwStr(callText, 'prefix') ?? (m[2] === 'mount' ? strArg(first) ?? '' : '');
|
|
223
|
+
let target: string | null = null;
|
|
224
|
+
if (imp) {
|
|
225
|
+
const modName = imp.attr && imp.module ? `${imp.module.replace(/\.$/, '')}${imp.module.endsWith('.') ? '' : '.'}${imp.attr}` : imp.module;
|
|
226
|
+
target = (imp.attr ? resolvePyModule(repo, v.file, modName) : null) ?? resolvePyModule(repo, v.file, imp.module);
|
|
227
|
+
}
|
|
228
|
+
const protections: Protection[] = [];
|
|
229
|
+
if (/dependencies\s*=/.test(callText)) {
|
|
230
|
+
const a = analyze(v, { start: open, end: close, seeds: [], decorators: [], returnsJson: false }, helpers);
|
|
231
|
+
for (const p of a.protections) if (p.kind !== 'owner_filter') protections.push({ ...p, scope: 'router' });
|
|
232
|
+
}
|
|
233
|
+
if (target && target !== v.file) out.mounts.push({ from: v.file, line: v.lines.at(m.index!), prefix: joinPath('', prefix || '/'), target, protections });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Jobs: Celery tasks and scheduler jobs.
|
|
237
|
+
for (const g of groups) {
|
|
238
|
+
if (g.kind !== 'def') continue;
|
|
239
|
+
const jd = g.decos.find((d) => /(^|\.)(task|shared_task|scheduled_job|periodic_task|job|actor)$/.test(d.name) && /celery|apscheduler|dramatiq|huey|rq|shared_task|schedul/i.test(v.imports + d.name));
|
|
240
|
+
if (!jd) continue;
|
|
241
|
+
const b = pyBlock(masked, v.lines, g.lineStart);
|
|
242
|
+
out.entries.push(makeEntry(repo, { kind: 'job', framework: /celery|shared_task/i.test(v.imports + jd.name) ? 'celery' : 'scheduler', file: v.file, line: v.lines.at(jd.start), method: null, path: null, name: g.name, confidence: 'high', handlerView: v, spec: { start: g.lineStart, end: b.end, seeds: pyParams(masked, g.defStart), decorators: [], returnsJson: false } }));
|
|
243
|
+
}
|
|
244
|
+
for (const m of masked.matchAll(/\b\w+\.add_job\s*\(\s*([A-Za-z_]\w*)/g)) {
|
|
245
|
+
const fn = repo.defs('py', m[1])[0];
|
|
246
|
+
if (!fn) continue;
|
|
247
|
+
const b = pyBlock(fn.view.masked, fn.view.lines, fn.start);
|
|
248
|
+
out.entries.push(makeEntry(repo, { kind: 'job', framework: 'scheduler', file: fn.view.file, line: fn.view.lines.at(fn.start), method: null, path: null, name: m[1], confidence: 'medium', handlerView: fn.view, spec: { start: fn.start, end: b.end, seeds: pyParams(fn.view.masked, fn.start), decorators: [], returnsJson: false } }));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// AI tools: @tool (LangChain and others), @mcp.tool(), @function_tool.
|
|
252
|
+
for (const g of groups) {
|
|
253
|
+
if (g.kind !== 'def') continue;
|
|
254
|
+
const td = g.decos.find((d) => /(^|\.)(tool|function_tool|register_tool)$/.test(d.name));
|
|
255
|
+
if (!td) continue;
|
|
256
|
+
const b = pyBlock(masked, v.lines, g.lineStart);
|
|
257
|
+
out.entries.push(makeEntry(repo, { kind: 'ai_tool', framework: /mcp/i.test(td.name + v.imports) ? 'mcp' : 'ai-tools', file: v.file, line: v.lines.at(g.lineStart), method: null, path: null, name: g.name, confidence: 'medium', handlerView: v, spec: { start: g.lineStart, end: b.end, seeds: pyParams(masked, g.defStart), decorators: [], returnsJson: false } }));
|
|
258
|
+
}
|
|
259
|
+
return out;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Decorators directly above the def that starts at `defStart` (an index at the start of the def line), as spec ranges.
|
|
263
|
+
export function decoratorsAbove(v: FileView, defStart: number): NonNullable<Spec['decorators']> {
|
|
264
|
+
const g = decoratorGroups(v).find((x) => x.lineStart === defStart || v.masked.lastIndexOf('\n', x.defStart) + 1 === defStart);
|
|
265
|
+
return g ? g.decos.map((d) => ({ view: v, start: d.start, end: d.end, scope: 'router' as const })) : [];
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function classDecos(v: FileView, cls: string): NonNullable<Spec['decorators']> {
|
|
269
|
+
const m = new RegExp(`^class\\s+${cls}\\b[^\\n]*:`, 'm').exec(v.masked);
|
|
270
|
+
if (!m) return [];
|
|
271
|
+
const b = pyBlock(v.masked, v.lines, m.index);
|
|
272
|
+
const body = v.masked.slice(b.bodyStart, b.end);
|
|
273
|
+
const attrs = /\b(?:permission_classes|authentication_classes|throttle_classes|decorators|serializer_class|method_decorators)\s*=[^\n]*(?:\n[ \t]+[^\n]*)?/g;
|
|
274
|
+
const out: NonNullable<Spec['decorators']> = [{ view: v, start: m.index, end: b.bodyStart, scope: 'router' }];
|
|
275
|
+
for (const x of body.matchAll(attrs)) out.push({ view: v, start: b.bodyStart + x.index!, end: b.bodyStart + x.index! + x[0].length, scope: 'router' });
|
|
276
|
+
return out;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'];
|
|
280
|
+
// The HTTP methods a class defines (get, post ...), found in the class named `cls` in this file or elsewhere.
|
|
281
|
+
export function pyClassMethods(repo: Repo, v: FileView, cls: string): { view: FileView; method: string; start: number; end: number }[] {
|
|
282
|
+
const files = [v.file, ...repo.filesOf('py').filter((f) => f !== v.file)];
|
|
283
|
+
for (const f of files) {
|
|
284
|
+
const view = f === v.file ? v : repo.view(f);
|
|
285
|
+
if (!view) continue;
|
|
286
|
+
const m = new RegExp(`^class\\s+${cls}\\b[^\\n]*:`, 'm').exec(view.masked);
|
|
287
|
+
if (!m) continue;
|
|
288
|
+
const b = pyBlock(view.masked, view.lines, m.index);
|
|
289
|
+
const found: { view: FileView; method: string; start: number; end: number }[] = [];
|
|
290
|
+
const body = view.masked.slice(b.bodyStart, b.end);
|
|
291
|
+
for (const x of body.matchAll(/^[ \t]+(?:async\s+)?def\s+(\w+)\s*\(/gm)) {
|
|
292
|
+
const name = x[1].toLowerCase();
|
|
293
|
+
if (!HTTP_METHODS.includes(name)) continue;
|
|
294
|
+
const at = b.bodyStart + x.index!;
|
|
295
|
+
const ls = view.masked.lastIndexOf('\n', at + 1) + 1;
|
|
296
|
+
const mb = pyBlock(view.masked, view.lines, ls);
|
|
297
|
+
found.push({ view, method: name.toUpperCase(), start: ls, end: mb.end });
|
|
298
|
+
}
|
|
299
|
+
return found;
|
|
300
|
+
}
|
|
301
|
+
return [];
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function fastapiParams(repo: Repo, v: FileView, g: Group, e: ReturnType<typeof makeEntry>): void {
|
|
305
|
+
const open = v.masked.indexOf('(', g.defStart);
|
|
306
|
+
if (open < 0) return;
|
|
307
|
+
const close = closeOf(v.masked, open);
|
|
308
|
+
const sig = v.text.slice(open, close);
|
|
309
|
+
const line = v.lines.at(open);
|
|
310
|
+
const add = (source: 'body' | 'query' | 'params' | 'file' | 'form' | 'headers'): void => { if (!e.reads.some((r) => r.source === source)) e.reads.push({ source, line }); };
|
|
311
|
+
for (const m of sig.matchAll(/(\w+)\s*:\s*([A-Z]\w*)/g)) {
|
|
312
|
+
const typ = m[2];
|
|
313
|
+
if (typ === 'UploadFile') { add('file'); continue; }
|
|
314
|
+
if (/^(?:Dict|List|Any|Mapping|Sequence)$/.test(typ)) { add('body'); continue; }
|
|
315
|
+
if (['Request', 'Response', 'Depends', 'Session', 'BackgroundTasks', 'WebSocket'].includes(typ)) continue;
|
|
316
|
+
const isModel = repo.filesOf('py').some((f) => { const t = repo.ctx.text(f); return new RegExp(`class\\s+${typ}\\s*\\([^)]*(?:BaseModel|SQLModel|Schema|BaseSchema)[^)]*\\)`).test(t); });
|
|
317
|
+
if (isModel) { add('body'); e.protections.push({ kind: 'input_validation', scope: 'handler', file: v.file, line, via: `pydantic model ${typ}`, enforced: true, confidence: 'high' }); }
|
|
318
|
+
}
|
|
319
|
+
for (const m of sig.matchAll(/(\w+)\s*:\s*(?:dict|list|bytes|object)\b(?!\s*=\s*(?:Query|Header|Depends))/g)) { if (!(e.path ?? '').includes(`:${m[1]}`) && /^(POST|PUT|PATCH|DELETE)$/.test(e.method ?? '')) add('body'); }
|
|
320
|
+
if (/\bFile\s*\(|UploadFile/.test(sig)) add('file');
|
|
321
|
+
if (/\bForm\s*\(/.test(sig)) add('form');
|
|
322
|
+
if (/\bQuery\s*\(/.test(sig)) add('query');
|
|
323
|
+
if (/\bPath\s*\(/.test(sig)) add('params');
|
|
324
|
+
if (/\bBody\s*\(/.test(sig)) add('body');
|
|
325
|
+
if (/\bHeader\s*\(/.test(sig)) add('headers');
|
|
326
|
+
if (e.path && /:\w+/.test(e.path)) add('params');
|
|
327
|
+
e.reads.sort((a, b) => (a.source < b.source ? -1 : a.source > b.source ? 1 : 0));
|
|
328
|
+
e.protections.sort((a, b) => a.line - b.line || (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0) || (a.via < b.via ? -1 : a.via > b.via ? 1 : 0));
|
|
329
|
+
}
|
package/src/map/rails.ts
ADDED
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
// Ruby on Rails entry points: config/routes.rb (get, post, match, root, resources, resource, namespace, scope, member,
|
|
2
|
+
// collection, controller blocks, devise's authenticate blocks and mounted engines) joined to the controller actions they
|
|
3
|
+
// name, with the before_action filters each action runs (class level, inherited from parent controllers and from included
|
|
4
|
+
// concerns, minus skip_before_action) as its protections. Pattern based, like the other extractors.
|
|
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 type { FnIndex } from './light-index.ts';
|
|
9
|
+
import { analyzeLight, type LightDeco } from './light.ts';
|
|
10
|
+
import type { LocalVocab } from './local-vocab.ts';
|
|
11
|
+
import type { Repo } from './repo.ts';
|
|
12
|
+
|
|
13
|
+
interface Frame { kind: string; path: string; module: string; resource: { name: string; singular: boolean } | null; auth: Protection[]; controller: string | null; only: string[] | null; except: string[] | null }
|
|
14
|
+
interface RouteDef { verb: string; path: string; controller: string; action: string; line: number; auth: Protection[]; decoLine: number; mount?: string }
|
|
15
|
+
interface Filter { name: string; line: number; view: FileView; start: number; end: number; only: string[] | null; except: string[] | null; kind: 'add' | 'skip'; text: string }
|
|
16
|
+
|
|
17
|
+
const CRUD: [string, string, string, boolean][] = [
|
|
18
|
+
['index', 'GET', '', false], ['create', 'POST', '', false], ['new', 'GET', '/new', false], ['show', 'GET', '/:id', true], ['edit', 'GET', '/:id/edit', true],
|
|
19
|
+
['update', 'PATCH', '/:id', true], ['update', 'PUT', '/:id', true], ['destroy', 'DELETE', '/:id', true],
|
|
20
|
+
];
|
|
21
|
+
const sym = (s: string): string[] => (/^%[iw]/.test(s) ? s.replace(/^%[iw]\[|\]$/g, '').split(/\s+/).filter(Boolean) : [...s.matchAll(/:(\w+)|['"](\w+)['"]/g)].map((m) => m[1] ?? m[2]));
|
|
22
|
+
const listOpt = (line: string, key: string): string[] | null => {
|
|
23
|
+
const m = new RegExp(`\\b${key}:\\s*(%[iw]\\[[^\\]]*\\]|\\[[^\\]]*\\]|:\\w+|['"]\\w+['"])`).exec(line);
|
|
24
|
+
return m ? sym(m[1]) : null;
|
|
25
|
+
};
|
|
26
|
+
const strOpt = (line: string, key: string): string | null => new RegExp(`\\b${key}:\\s*(?::(\\w+)|['"]([^'"]*)['"])`).exec(line)?.slice(1).find((x) => x !== undefined) ?? null;
|
|
27
|
+
const singular = (s: string): string => (/ies$/.test(s) ? s.replace(/ies$/, 'y') : /ses$/.test(s) ? s.replace(/es$/, '') : s.replace(/s$/, ''));
|
|
28
|
+
|
|
29
|
+
export function railsFiles(repo: Repo): { routes: string[]; controllers: string[] } {
|
|
30
|
+
return {
|
|
31
|
+
routes: repo.filesOf('rb').filter((f) => /(?:^|\/)config\/routes(?:\/[^/]+)?\.rb$/.test(f)),
|
|
32
|
+
controllers: repo.filesOf('rb').filter((f) => /(?:^|\/)app\/controllers\/.*\.rb$|(?:^|\/)app\/controllers\/concerns\/.*\.rb$/.test(f)),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function parseRoutes(v: FileView): RouteDef[] {
|
|
37
|
+
const out: RouteDef[] = [];
|
|
38
|
+
const lines = v.masked.split('\n');
|
|
39
|
+
const orig = v.text.split('\n');
|
|
40
|
+
const stack: Frame[] = [{ kind: 'root', path: '', module: '', resource: null, auth: [], controller: null, only: null, except: null }];
|
|
41
|
+
const top = (): Frame => stack[stack.length - 1];
|
|
42
|
+
const authFacts = (ln: number, text: string): Protection[] => (/\b(?:authenticate|authenticated)\b/.test(text) ? [{ kind: 'session_read', scope: 'router', file: v.file, line: ln, via: 'route authenticate block', enforced: true, confidence: 'high' }] : []);
|
|
43
|
+
const roleFacts = (ln: number, text: string): Protection[] => (/\b(?:admin|role|staff|superuser|can\?)/i.test(text) ? [{ kind: 'role_check', scope: 'router', file: v.file, line: ln, via: 'route constraint', enforced: true, confidence: 'medium' }] : []);
|
|
44
|
+
const push = (verb: string, path: string, controller: string, action: string, ln: number, f: Frame, mount?: string): void => {
|
|
45
|
+
out.push({ verb, path: joinPath(f.path, path), controller, action, line: ln, auth: stack.flatMap((s) => s.auth), decoLine: ln, mount });
|
|
46
|
+
};
|
|
47
|
+
const ctrlOf = (f: Frame, name: string): string => (name.includes('/') ? name : `${f.module}${name}`);
|
|
48
|
+
const nestedPrefix = (f: Frame, member: boolean): string => {
|
|
49
|
+
const r = f.resource;
|
|
50
|
+
if (!r) return '';
|
|
51
|
+
return `/${r.name}${r.singular || !member ? '' : '/:id'}`;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
for (let i = 0; i < lines.length; i++) {
|
|
55
|
+
const raw = lines[i];
|
|
56
|
+
const l = raw.trim();
|
|
57
|
+
if (!l) continue;
|
|
58
|
+
const ln = i + 1;
|
|
59
|
+
const o = orig[i] ?? '';
|
|
60
|
+
const f = top();
|
|
61
|
+
// Multi line route calls: join following lines while the line ends with a comma.
|
|
62
|
+
let full = o.trim();
|
|
63
|
+
let j = i;
|
|
64
|
+
while (/,\s*$/.test(lines[j]) && j + 1 < lines.length && j < i + 6) { j++; full += ' ' + (orig[j] ?? '').trim(); }
|
|
65
|
+
const opens = /\bdo(?:\s*\|[^|]*\|)?\s*$/.test(lines[j].trim());
|
|
66
|
+
const blockHead = (kind: string, fr: Partial<Frame>): void => { stack.push({ ...f, kind, auth: [], only: null, except: null, ...fr }); };
|
|
67
|
+
if (/^end\b/.test(l)) { if (stack.length > 1) stack.pop(); continue; }
|
|
68
|
+
if (/^(?:if|unless|case|begin|while)\b/.test(l) && !/\bend\b/.test(l)) { stack.push({ ...f, kind: 'other', auth: [] }); continue; }
|
|
69
|
+
if (/^else\b|^elsif\b|^when\b/.test(l)) continue;
|
|
70
|
+
let m: RegExpExecArray | null;
|
|
71
|
+
if ((m = /^namespace\s+(?::(\w+)|['"]([\w/]+)['"])/.exec(full))) {
|
|
72
|
+
const n = m[1] ?? m[2];
|
|
73
|
+
const p = strOpt(full, 'path');
|
|
74
|
+
if (opens) blockHead('namespace', { path: joinPath(f.path, p ?? n), module: `${f.module}${n}/` });
|
|
75
|
+
i = j; continue;
|
|
76
|
+
}
|
|
77
|
+
if ((m = /^scope\b(.*)$/.exec(full))) {
|
|
78
|
+
const rest = m[1];
|
|
79
|
+
const pos = /^\s*\(?\s*(?::(\w+)|['"]([^'"]*)['"])/.exec(rest);
|
|
80
|
+
const p = strOpt(rest, 'path') ?? (pos ? pos[1] ?? pos[2] : null);
|
|
81
|
+
const mod = strOpt(rest, 'module');
|
|
82
|
+
if (opens) blockHead('scope', { path: p ? joinPath(f.path, p) : f.path, module: mod ? `${f.module}${mod}/` : f.module });
|
|
83
|
+
i = j; continue;
|
|
84
|
+
}
|
|
85
|
+
if ((m = /^(authenticate|authenticated)\b(.*)$/.exec(full))) {
|
|
86
|
+
if (opens) blockHead('authenticate', { auth: authFacts(ln, full) });
|
|
87
|
+
i = j; continue;
|
|
88
|
+
}
|
|
89
|
+
if ((m = /^constraints\b(.*)$/.exec(full))) {
|
|
90
|
+
if (opens) blockHead('constraints', { auth: [...authFacts(ln, full), ...roleFacts(ln, full)] });
|
|
91
|
+
i = j; continue;
|
|
92
|
+
}
|
|
93
|
+
if ((m = /^controller\s+(?::(\w+)|['"]([\w/]+)['"])/.exec(full))) {
|
|
94
|
+
if (opens) blockHead('controller', { controller: m[1] ?? m[2] });
|
|
95
|
+
i = j; continue;
|
|
96
|
+
}
|
|
97
|
+
if ((m = /^(member|collection)\s+do\b/.exec(full))) { blockHead(m[1], {}); continue; }
|
|
98
|
+
if (/^(?:concern|devise_scope|defaults|with_options|resources_for_api|direct|draw)\b/.test(l) && opens) { stack.push({ ...f, kind: 'concern', auth: [], controller: '\u0000skip' }); i = j; continue; }
|
|
99
|
+
if ((m = /^(resources|resource)\s+(.*)$/.exec(full))) {
|
|
100
|
+
const singularRes = m[1] === 'resource';
|
|
101
|
+
const names = [...m[2].split(/\b(?:only|except|controller|path|param|as|module|shallow|constraints|defaults|format)\s*:/)[0].matchAll(/:(\w+)/g)].map((x) => x[1]);
|
|
102
|
+
const only = listOpt(m[2], 'only');
|
|
103
|
+
const except = listOpt(m[2], 'except');
|
|
104
|
+
const ctrlOpt = strOpt(m[2], 'controller');
|
|
105
|
+
const pathOpt = strOpt(m[2], 'path');
|
|
106
|
+
for (const name of names) {
|
|
107
|
+
const base = f.resource ? `${nestedPrefix(f, true).replace(/:id$/, `:${singular(f.resource.name)}_id`)}` : '';
|
|
108
|
+
const urlName = pathOpt ?? name;
|
|
109
|
+
const controller = ctrlOf(f, ctrlOpt ?? name);
|
|
110
|
+
const acts = singularRes ? CRUD.filter(([a]) => a !== 'index') : CRUD;
|
|
111
|
+
for (const [act, verb, suffix, member] of acts) {
|
|
112
|
+
if (only && !only.includes(act)) continue;
|
|
113
|
+
if (except && except.includes(act)) continue;
|
|
114
|
+
const sfx = singularRes ? suffix.replace(/^\/:id/, '') : suffix;
|
|
115
|
+
if (singularRes && act === 'index') continue;
|
|
116
|
+
push(verb, `${base}/${urlName}${sfx}`, controller, act, ln, f);
|
|
117
|
+
}
|
|
118
|
+
if (opens) stack.push({ ...f, kind: 'resources', path: f.path, resource: { name: urlName, singular: singularRes }, auth: [], controller: controller });
|
|
119
|
+
}
|
|
120
|
+
if (opens && !names.length) stack.push({ ...f, kind: 'other', auth: [] });
|
|
121
|
+
i = j; continue;
|
|
122
|
+
}
|
|
123
|
+
if ((m = /^(get|post|put|patch|delete|match)\s+(.*)$/.exec(full)) && !/^(?:get|post|put|patch|delete|match)\s*=/.test(full)) {
|
|
124
|
+
const verbWord = m[1];
|
|
125
|
+
const rest = m[2];
|
|
126
|
+
const first = /^\(?\s*(?::(\w+)|['"]([^'"]*)['"])/.exec(rest);
|
|
127
|
+
let target: string | null = strOpt(rest, 'to') ?? /=>\s*['"]([\w/]+#\w+)['"]/.exec(rest)?.[1] ?? null;
|
|
128
|
+
if (/\bto:\s*(?:redirect|->|lambda|proc)\b|=>\s*redirect\b/.test(rest) || /\bto:\s*[A-Z]/.test(rest)) { if (opens) stack.push({ ...f, kind: 'other', auth: [] }); i = j; continue; }
|
|
129
|
+
let action = strOpt(rest, 'action');
|
|
130
|
+
let controller: string | null = null;
|
|
131
|
+
if (target && target.includes('#')) { const [c, a] = target.split('#'); controller = ctrlOf(f, c); action = a; }
|
|
132
|
+
else if (!target && first && /=>\s*['"]?[\w/]+#\w+/.test(rest)) { const t = /=>\s*['"]?([\w/]+)#(\w+)/.exec(rest)!; controller = ctrlOf(f, t[1]); action = t[2]; }
|
|
133
|
+
let path: string | null = first ? (first[1] ?? first[2]) : null;
|
|
134
|
+
if (!controller) {
|
|
135
|
+
const ctrlName = f.controller && f.controller !== '\u0000skip' ? f.controller : null;
|
|
136
|
+
if (ctrlName) controller = ctrlOf(f, ctrlName);
|
|
137
|
+
if (!action && path) action = path.replace(/^\//, '').split('/')[0].replace(/\W+/g, '_');
|
|
138
|
+
if (!controller && /^['"][\w/]+#\w+['"]$/.test(rest.split(',')[0].trim())) { const t = /['"]([\w/]+)#(\w+)['"]/.exec(rest)!; controller = ctrlOf(f, t[1]); action = t[2]; }
|
|
139
|
+
}
|
|
140
|
+
if (f.controller === '\u0000skip') { if (opens) stack.push({ ...f, kind: 'other', auth: [] }); i = j; continue; }
|
|
141
|
+
if (!controller || !action || path === null) { if (opens) stack.push({ ...f, kind: 'other', auth: [] }); i = j; continue; }
|
|
142
|
+
const on = strOpt(rest, 'on');
|
|
143
|
+
const inMember = f.kind === 'member' || on === 'member';
|
|
144
|
+
const inCollection = f.kind === 'collection' || on === 'collection';
|
|
145
|
+
let prefix = '';
|
|
146
|
+
if (f.resource && (inMember || inCollection)) prefix = nestedPrefix(f, inMember);
|
|
147
|
+
else if (f.resource && f.kind === 'resources') prefix = nestedPrefix(f, true).replace(/:id$/, `:${singular(f.resource.name)}_id`);
|
|
148
|
+
const verbs = verbWord === 'match' ? (listOpt(rest, 'via') ?? ['any']).map((x) => (x === 'all' || x === 'any' ? 'ANY' : x.toUpperCase())) : [verbWord.toUpperCase()];
|
|
149
|
+
for (const verb of verbs) push(verb === 'ANY' ? 'ANY' : verb, `${prefix}/${path.replace(/^\//, '')}`.replace(/\(\.:format\)/g, ''), controller, action, ln, f);
|
|
150
|
+
if (opens) stack.push({ ...f, kind: 'other', auth: [] });
|
|
151
|
+
i = j; continue;
|
|
152
|
+
}
|
|
153
|
+
if ((m = /^root\s+(.*)$/.exec(full))) {
|
|
154
|
+
const t = /['"]([\w/]+)#(\w+)['"]/.exec(m[1]);
|
|
155
|
+
if (t) push('GET', '/', ctrlOf(f, t[1]), t[2], ln, f);
|
|
156
|
+
i = j; continue;
|
|
157
|
+
}
|
|
158
|
+
if ((m = /^mount\s+(.*)$/.exec(full))) {
|
|
159
|
+
const t = /^([\w:]+)\s*(?:=>|,\s*at:)\s*['"]([^'"]+)['"]/.exec(m[1]);
|
|
160
|
+
if (t) push('ANY', t[2], t[1], '\u0000mount', ln, f, t[1]);
|
|
161
|
+
i = j; continue;
|
|
162
|
+
}
|
|
163
|
+
if (opens) stack.push({ ...f, kind: 'other', auth: [] });
|
|
164
|
+
i = j;
|
|
165
|
+
}
|
|
166
|
+
return out.filter((r) => r.path !== undefined);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
interface ControllerInfo { key: string; name: string; file: string; view: FileView; parent: string | null; includes: string[]; filters: Filter[] }
|
|
170
|
+
|
|
171
|
+
const snakeCase = (s: string): string => s.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
|
|
172
|
+
// app/controllers/admin/users_controller.rb -> admin/users ; app/controllers/concerns/authentication.rb -> concerns/authentication
|
|
173
|
+
const keyOf = (file: string): string => (/app\/controllers\/(.*)\.rb$/.exec(file)?.[1] ?? file).replace(/_controller$/, '');
|
|
174
|
+
|
|
175
|
+
function parseControllers(repo: Repo, files: string[]): { ctrls: Map<string, ControllerInfo>; concerns: Map<string, ControllerInfo> } {
|
|
176
|
+
const ctrls = new Map<string, ControllerInfo>();
|
|
177
|
+
const concerns = new Map<string, ControllerInfo>();
|
|
178
|
+
for (const file of files) {
|
|
179
|
+
const v = repo.view(file);
|
|
180
|
+
if (!v) continue;
|
|
181
|
+
const isConcern = /\/concerns\//.test(file);
|
|
182
|
+
const cl = /^[ \t]*class\s+([A-Z][\w:]*)(?:\s*<\s*([\w:]+))?/m.exec(v.masked);
|
|
183
|
+
const head = isConcern ? /^[ \t]*module\s+([A-Z][\w:]*)/m.exec(v.masked) : cl;
|
|
184
|
+
if (!head) continue;
|
|
185
|
+
const info: ControllerInfo = { key: keyOf(file), name: head[1].split('::').pop()!, file, view: v, parent: !isConcern && cl?.[2] ? cl[2] : null, includes: [...v.masked.matchAll(/^[ \t]*include\s+([\w:]+)/gm)].map((x) => x[1].split('::').pop()!), filters: [] };
|
|
186
|
+
const lines = v.masked.split('\n');
|
|
187
|
+
const orig = v.text.split('\n');
|
|
188
|
+
let defIndent = -1;
|
|
189
|
+
for (let i = 0; i < lines.length; i++) {
|
|
190
|
+
const l = lines[i].trim();
|
|
191
|
+
const indent = /^[ \t]*/.exec(lines[i])![0].length;
|
|
192
|
+
// A filter inside a method or a class_methods block is a macro definition, not a filter of this class.
|
|
193
|
+
if (defIndent >= 0) { if (indent <= defIndent && /^end\b/.test(l)) defIndent = -1; continue; }
|
|
194
|
+
if (/^(?:def\b|class_methods\b)/.test(l) && !/\bend\s*$/.test(l)) { defIndent = indent; continue; }
|
|
195
|
+
const m = /^(before_action|before_filter|prepend_before_action|append_before_action|skip_before_action|skip_before_filter|skip_forgery_protection|load_and_authorize_resource|authorize_resource|load_resource|rate_limit|allow_unauthenticated_access|require_authentication)\b/.exec(l);
|
|
196
|
+
if (!m) continue;
|
|
197
|
+
let full = orig[i] ?? '';
|
|
198
|
+
let j = i;
|
|
199
|
+
while (/,\s*$/.test(lines[j]) && j + 1 < lines.length && j < i + 5) { j++; full += ' ' + (orig[j] ?? '').trim(); }
|
|
200
|
+
const only = listOpt(full, 'only');
|
|
201
|
+
const except = listOpt(full, 'except');
|
|
202
|
+
const kw = m[1];
|
|
203
|
+
const names = [...full.replace(/\b(?:only|except|if|unless|prepend|to|within|by|with)\s*:.*$/, '').matchAll(/:(\w+[?!]?)/g)].map((x) => x[1]);
|
|
204
|
+
const start = v.lines.start(i + 1);
|
|
205
|
+
let end = Math.min(v.lines.start(j + 2) - 1, v.text.length);
|
|
206
|
+
// The options (only, except, if, unless) name actions and methods, not filters: leave them out of the text that is read.
|
|
207
|
+
const cut = v.text.slice(start, end).search(/\b(?:only|except|if|unless)\s*:/);
|
|
208
|
+
if (cut > 0) end = start + cut;
|
|
209
|
+
const add = (name: string, kind: 'add' | 'skip'): void => { info.filters.push({ name, line: i + 1, view: v, start, end, only, except, kind, text: full }); };
|
|
210
|
+
if (/^skip_/.test(kw)) for (const n of names) add(n, 'skip');
|
|
211
|
+
else if (kw === 'allow_unauthenticated_access') add('require_authentication', 'skip');
|
|
212
|
+
else if (/before_action|before_filter/.test(kw)) { if (names.length) for (const n of names) add(n, 'add'); else add('(block)', 'add'); }
|
|
213
|
+
else add(kw, 'add');
|
|
214
|
+
i = j;
|
|
215
|
+
}
|
|
216
|
+
if (isConcern) concerns.set(info.name, info); else ctrls.set(info.key, info);
|
|
217
|
+
}
|
|
218
|
+
return { ctrls, concerns };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function extractRailsAll(repo: Repo, fn: FnIndex, local: LocalVocab | null): Extracted {
|
|
222
|
+
const out = empty();
|
|
223
|
+
const { routes, controllers } = railsFiles(repo);
|
|
224
|
+
if (!routes.length) return out;
|
|
225
|
+
const { ctrls, concerns } = parseControllers(repo, controllers);
|
|
226
|
+
const parentOf = (c: ControllerInfo): ControllerInfo | undefined => {
|
|
227
|
+
if (!c.parent) return undefined;
|
|
228
|
+
const dir = c.key.includes('/') ? c.key.slice(0, c.key.lastIndexOf('/')) : '';
|
|
229
|
+
const bare = c.parent.split('::').map(snakeCase).join('/').replace(/_controller$/, '');
|
|
230
|
+
return ctrls.get(dir ? `${dir}/${bare}` : bare) ?? ctrls.get(bare);
|
|
231
|
+
};
|
|
232
|
+
for (const rf of routes) {
|
|
233
|
+
const rv = repo.view(rf);
|
|
234
|
+
if (!rv) continue;
|
|
235
|
+
for (const r of parseRoutes(rv)) {
|
|
236
|
+
if (r.action === '\u0000mount') {
|
|
237
|
+
const a = analyzeLight(rv, { start: rv.lines.start(r.line), end: rv.lines.start(r.line + 1) - 1, seeds: [], decorators: [], extra: r.auth, local });
|
|
238
|
+
out.entries.push(makeEntry(repo, { kind: 'http_route', framework: 'rails-mount', file: rf, line: r.line, method: 'ANY', path: r.path, name: r.mount ?? null, confidence: 'medium', handlerView: rv, spec: { start: rv.lines.start(r.line), end: rv.lines.start(r.line + 1) - 1, seeds: [] }, analysis: a }));
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
const ci = ctrls.get(r.controller);
|
|
242
|
+
const chain: ControllerInfo[] = [];
|
|
243
|
+
for (let cur: ControllerInfo | undefined = ci, n = 0; cur && n < 8; n++) { chain.unshift(cur); cur = parentOf(cur); }
|
|
244
|
+
// Filters in the order they run: each ancestor's included concerns, then its own lines.
|
|
245
|
+
const active: Filter[] = [];
|
|
246
|
+
const applies = (fl: Filter): boolean => (!fl.only || fl.only.includes(r.action)) && (!fl.except || !fl.except.includes(r.action));
|
|
247
|
+
for (const c of chain) {
|
|
248
|
+
const all = [...c.includes.flatMap((i) => concerns.get(i)?.filters ?? []), ...c.filters];
|
|
249
|
+
for (const fl of all) {
|
|
250
|
+
if (!applies(fl)) continue;
|
|
251
|
+
if (fl.kind === 'skip') { for (let k = active.length - 1; k >= 0; k--) if (active[k].name === fl.name) active.splice(k, 1); continue; }
|
|
252
|
+
active.push(fl);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
// A filter named authenticate_user may only look the user up (@user = ...) and let a guest through, as in Lobsters. It protects nothing then.
|
|
256
|
+
const softLookup = (fl: Filter): boolean => {
|
|
257
|
+
if (!/^authenticate_(?:user|member|account)$/.test(fl.name)) return false;
|
|
258
|
+
const d = fn.defs(fl.name).find((x) => chain.some((c) => c.file === x.view.file) || concerns.size > 0);
|
|
259
|
+
if (!d) return false;
|
|
260
|
+
const body = d.view.masked.slice(d.start, d.end);
|
|
261
|
+
return /@(?:user|current_user)\s*(?:\|\|)?=/.test(body) && !/\b(?:redirect_to|redirect_back|render|head|raise|halt|deny_access|forbidden|unauthorized)\b|\bauthenticate!?\b(?!_user)|\brequire_\w+/.test(body);
|
|
262
|
+
};
|
|
263
|
+
const decorators: LightDeco[] = active.filter((fl) => !softLookup(fl)).map((fl) => ({ view: fl.view, start: fl.start, end: fl.end, scope: 'router' as const }));
|
|
264
|
+
const policyScoped = active.some((fl) => /load_and_authorize_resource|authorize_resource/.test(fl.name));
|
|
265
|
+
// The action itself.
|
|
266
|
+
let hv: FileView = rv;
|
|
267
|
+
let start = rv.lines.start(r.line);
|
|
268
|
+
let end = rv.lines.start(r.line + 1) - 1;
|
|
269
|
+
let found = false;
|
|
270
|
+
if (ci) {
|
|
271
|
+
const d = fn.defs(r.action).find((x) => x.view.file === ci.file);
|
|
272
|
+
if (d) { hv = d.view; start = d.start; end = d.end; found = true; }
|
|
273
|
+
}
|
|
274
|
+
// A filter such as set_article loads the record before the action runs: @article = Article.find(params[:id]).
|
|
275
|
+
const bound: { name: string; target: string; owner?: boolean }[] = [];
|
|
276
|
+
for (const fl of active) {
|
|
277
|
+
const d = fn.defs(fl.name).find((x) => chain.some((c) => c.file === x.view.file));
|
|
278
|
+
if (!d) continue;
|
|
279
|
+
const body = d.view.text.slice(d.start, d.end);
|
|
280
|
+
for (const m of body.matchAll(/(@\w+)\s*=\s*(?:(@?current_\w+)\.(\w+)\.|([A-Z][\w:]*)\.)(?:find|find_by!?)\s*\(\s*(?:params\[\s*:\w+\s*\]|id:\s*params)/g)) bound.push({ name: m[1], target: m[4] ?? m[3], owner: m[2] !== undefined });
|
|
281
|
+
}
|
|
282
|
+
const a = analyzeLight(hv, { start, end, seeds: [], decorators, extra: r.auth.slice(), lookup: fn.find, local, policyScoped, bound });
|
|
283
|
+
out.entries.push(makeEntry(repo, {
|
|
284
|
+
kind: 'http_route', framework: 'rails', file: rf, line: r.line, method: r.verb, path: r.path.replace(/\(\.:format\)/g, '') || '/', name: `${r.controller}#${r.action}`,
|
|
285
|
+
confidence: found ? 'high' : 'low', handlerView: hv, spec: { start, end, seeds: [] }, analysis: a,
|
|
286
|
+
}));
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return out;
|
|
290
|
+
}
|
|
291
|
+
|