@lintsure/core 0.3.14 → 0.3.16

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.
@@ -1,6 +1,7 @@
1
1
  import type { Finding, Report } from "./types.js";
2
2
  export declare const BASELINE_FILE = ".lintsure/baseline.json";
3
3
  export declare const ACCEPTED_FILE = ".lintsure/accepted.yaml";
4
+ export declare const CONFIRMED_FILE = ".lintsure/confirmed.yaml";
4
5
  /** A short one-way hash of the rule, file and the flagged line with spacing normalised. Moving the line keeps it; editing it changes it. */
5
6
  export declare function fingerprint(ruleId: string, file: string, lineText: string): string;
6
7
  export interface Baseline {
@@ -25,6 +26,15 @@ export interface AcceptedEntry {
25
26
  export declare function toBaseline(r: Report, created: string): Baseline;
26
27
  /** Reads the simple list form of accepted.yaml: "- key: value" items with indented "key: value" lines. */
27
28
  export declare function parseAccepted(text: string): AcceptedEntry[];
29
+ /** confirmed.yaml: the same list form as accepted.yaml. Each entry needs rule, fingerprint and confirmed_by; date and
30
+ * note are optional. Pure. */
31
+ export declare function parseConfirmed(text: string): {
32
+ rule: string;
33
+ fingerprint: string;
34
+ confirmed_by: string;
35
+ date?: string;
36
+ note?: string;
37
+ }[];
28
38
  /** Adds acceptances, new/unchanged marks and the list of fixed findings, from the repo's .lintsure/ files. */
29
39
  export declare function applyReview(r: Report, root: string, today: string): Promise<Report>;
30
40
  /** Findings still needing a decision: not accepted, or accepted but past the review date. */
@@ -6,6 +6,9 @@ import { readFile } from "node:fs/promises";
6
6
  import { join } from "node:path";
7
7
  export const BASELINE_FILE = ".lintsure/baseline.json";
8
8
  export const ACCEPTED_FILE = ".lintsure/accepted.yaml";
9
+ // Findings a reviewer read against the code and found real. Same list form as accepted.yaml, so a verdict is not lost
10
+ // when the conversation that reached it ends.
11
+ export const CONFIRMED_FILE = ".lintsure/confirmed.yaml";
9
12
  /** A short one-way hash of the rule, file and the flagged line with spacing normalised. Moving the line keeps it; editing it changes it. */
10
13
  export function fingerprint(ruleId, file, lineText) {
11
14
  return createHash("sha256").update(`${ruleId}\n${file}\n${lineText.trim().replace(/\s+/g, " ")}`).digest("hex").slice(0, 16);
@@ -31,6 +34,22 @@ export function parseAccepted(text) {
31
34
  }
32
35
  return out.filter((e) => e.rule && e.fingerprint && e.reason && e.accepted_by);
33
36
  }
37
+ /** confirmed.yaml: the same list form as accepted.yaml. Each entry needs rule, fingerprint and confirmed_by; date and
38
+ * note are optional. Pure. */
39
+ export function parseConfirmed(text) {
40
+ const out = [];
41
+ for (const raw of text.split(/\r?\n/)) {
42
+ const hash = raw.search(/(^|\s)#/);
43
+ const m = (hash < 0 ? raw : raw.slice(0, hash)).match(/^([ \t]*)(-[ \t]+)?([a-z_]+)[ \t]*:(.*)$/);
44
+ if (!m)
45
+ continue;
46
+ if (m[2])
47
+ out.push({});
48
+ if (out.length)
49
+ out[out.length - 1][m[3]] = m[4].trim().replace(/^["']|["']$/g, "");
50
+ }
51
+ return out.filter((e) => e.rule && e.fingerprint && e.confirmed_by);
52
+ }
34
53
  async function readText(path) { try {
35
54
  return await readFile(path, "utf8");
36
55
  }
@@ -46,6 +65,12 @@ export async function applyReview(r, root, today) {
46
65
  if (a)
47
66
  f.accepted = { reason: a.reason, by: a.accepted_by, date: a.date, reviewBy: a.review_by, expired: !!a.review_by && a.review_by < today };
48
67
  }
68
+ const confirmedText = await readText(join(root, CONFIRMED_FILE));
69
+ for (const c of confirmedText ? parseConfirmed(confirmedText) : []) {
70
+ const f = r.findings.find((x) => x.ruleId === c.rule && x.fingerprint === c.fingerprint);
71
+ if (f)
72
+ f.confirmed = { by: c.confirmed_by, date: c.date ?? "", ...(c.note ? { note: c.note } : {}) };
73
+ }
49
74
  const baseText = await readText(join(root, BASELINE_FILE));
50
75
  if (baseText) {
51
76
  let base = null;
@@ -0,0 +1,10 @@
1
+ import type { Control, Rule } from "../types.js";
2
+ /** Rules that already exist and say something about an API risk. */
3
+ export declare const apiForExisting: Record<string, Control[]>;
4
+ /** An admin endpoint whose file shows no sign of checking who is calling, in a project whose middleware has no check
5
+ * either or lets API paths through. Line of the first handler, or nothing. Pure. */
6
+ export declare function adminRouteNoCheck(lines: string[], _shared?: string, files?: Record<string, string>): Array<{
7
+ line: number;
8
+ status: "partial";
9
+ }>;
10
+ export declare const apiRules: Rule[];
@@ -0,0 +1,43 @@
1
+ const DRAFT = { mappedBy: "beta", reviewedAt: "pending" };
2
+ const API = (n, title) => ({ framework: "owasp-api", id: `API${n}:2023`, title });
3
+ const API1 = API(1, "Broken Object Level Authorization"), API2 = API(2, "Broken Authentication"), API3 = API(3, "Broken Object Property Level Authorization"), API4 = API(4, "Unrestricted Resource Consumption"), API5 = API(5, "Broken Function Level Authorization"), API7 = API(7, "Server Side Request Forgery"), API8 = API(8, "Security Misconfiguration"), API10 = API(10, "Unsafe Consumption of APIs");
4
+ /** Rules that already exist and say something about an API risk. */
5
+ export const apiForExisting = {
6
+ "authz.no-owner-check": [API1], "supabase.rls-disabled": [API1], "supabase.policy-allows-all": [API1],
7
+ "auth.hardcoded-password": [API2], "jwt.unverified": [API2], "jwt.no-expiry": [API2], "jwt.no-algorithm-pin": [API2],
8
+ "jwt.weak-secret": [API2], "crypto.weak-password-hash": [API2], "session.cookie-insecure": [API2],
9
+ "auth.no-rate-limit": [API2, API4],
10
+ "mass-assignment": [API3],
11
+ "llm.no-output-limit": [API4], "llm.unbounded-agent-loop": [API4], "upload.unrestricted": [API4],
12
+ "cookie.trusted-role": [API5], "supabase.function-no-auth": [API5], "cloud.function-url-no-auth": [API5],
13
+ "ssrf.user-url": [API7],
14
+ "cors.any-origin": [API8], "config.debug-on": [API8], "error.stack-to-client": [API8], "graphql.introspection": [API8],
15
+ "config.allowed-hosts-any": [API8],
16
+ "transport.tls-verify-off": [API8, API10], "transport.plain-http": [API10],
17
+ };
18
+ // A route file that is its own endpoint (Next.js route handlers and API pages, Nuxt server routes, SvelteKit endpoints),
19
+ // with "admin" as a part of its path. Frameworks that mount routers elsewhere are left out: the check may sit in the
20
+ // file that mounts them.
21
+ const ADMIN_ENDPOINT = /^(?=.*(^|\/)admin[\/.-])(?=.*(^|\/)(app\/.*\/route|pages\/api\/.+|server\/api\/.+|routes\/.*\+server)\.[cm]?[jt]s$)/i;
22
+ const HANDLER = /export\s+(async\s+)?(function|const)\s+(GET|POST|PUT|PATCH|DELETE)\b|export\s+default\s+(async\s+)?function|export\s+default\s+defineEventHandler|export\s*\{[^}]*\b(GET|POST|PUT|PATCH|DELETE)\b/;
23
+ // Anything that looks like the caller is being identified or checked. "admin" alone is not it: the path already says that.
24
+ const ACCESS_CHECK = /\b(role|roles|isAdmin|is_admin|requireAdmin|adminOnly|assertAdmin|permission\w*|authori[sz]\w*|getServerSession|getSession|auth\s*\(|getUser|currentUser|session|verify\w*|clerk\w*|getToken|jwt|requireAuth|withAuth|protect\w*|guard\w*|api[-_]?key|bearer|unauthori[sz]ed|forbidden|40[13])\b|\b\w*(require|ensure|assert|check|verify|with|is)\w*Admin\w*\s*\(|\badmin(Handler|Guard|Auth|Only|Route|Middleware)\w*\s*\(/i;
25
+ // Middleware that lets every API path through unchecked: an early return for /api, or a matcher that leaves api out.
26
+ const SKIPS_API = /startsWith\(\s*["'\x60]\/api\/?["'\x60]\s*\)\s*\)?\s*\{?\s*return\s+(true|NextResponse\.next|next\()|\(\?![^)\n]*\bapi\b/;
27
+ /** An admin endpoint whose file shows no sign of checking who is calling, in a project whose middleware has no check
28
+ * either or lets API paths through. Line of the first handler, or nothing. Pure. */
29
+ export function adminRouteNoCheck(lines, _shared, files = {}) {
30
+ if (ACCESS_CHECK.test(lines.join("\n")) || Object.values(files).some((t) => ACCESS_CHECK.test(t) && !SKIPS_API.test(t)))
31
+ return [];
32
+ const i = lines.findIndex((l) => HANDLER.test(l));
33
+ return i < 0 ? [] : [{ line: i + 1, status: "partial" }];
34
+ }
35
+ export const apiRules = [
36
+ { id: "authz.admin-route-no-check", title: "Admin endpoint with no access check in sight", status: "partial", severity: "high", controls: [API5, { framework: "owasp-top10", id: "A01:2025", title: "Broken Access Control" }],
37
+ fix: "Check the caller's role at the top of the handler and return 403 when it is not an admin. Do it on the server: hiding the admin page in the browser does not protect the endpoint behind it.",
38
+ note: "Anyone who knows or guesses the address can call an endpoint. An admin endpoint that never looks at who is calling gives every visitor admin actions (CWE-862, CWE-285).",
39
+ unseen: "Lintsure looked for a role, session or token check in this file and in the project's middleware. It can't see a check in a gateway, a reverse proxy or a wrapper it doesn't recognise.",
40
+ extensions: [".ts", ".js", ".mjs", ".cjs"], pathMatch: ADMIN_ENDPOINT, unlessPath: /\.(test|spec)\.[cm]?[jt]s$/,
41
+ sharedFiles: /(^|\/)(middleware|proxy|hooks\.server)\.[cm]?[jt]s$/,
42
+ fileTest: adminRouteNoCheck, ...DRAFT },
43
+ ];
@@ -1,6 +1,10 @@
1
1
  import type { Control, Rule } from "../types.js";
2
2
  /** CRA controls for rules that already exist. Merged by id in rules/index.ts. */
3
3
  export declare const craForExisting: Record<string, Control[]>;
4
+ /** CI lines where a security scan can't fail the build: `|| true`, a soft-fail flag, or continue-on-error on the scan's step. Pure. */
5
+ export declare function scanCannotFail(lines: string[]): number[];
6
+ /** A package source that can be swapped under you. Gap for plain HTTP or TLS checks off; Partial for a second index. Pure. */
7
+ export declare function unsafeSource(l: string): boolean | "partial";
4
8
  export declare const craRules: Rule[];
5
9
  /** Lines in a GitHub Actions `run:` step that paste text an outsider controls. Pure. */
6
10
  export declare function untrustedInRun(lines: string[]): number[];
@@ -25,7 +25,57 @@ const UNTRUSTED = /\$\{\{\s*github\.(head_ref|event\.(issue|pull_request|comment
25
25
  const BINARY = /\.(exe|dll|so|dylib|jar|class|pyc|o|a|bin|msi|apk)$/i;
26
26
  const UPDATER = /^\.github\/dependabot\.ya?ml$|(^|\/)(renovate\.json5?|\.renovaterc(\.json)?)$|^\.github\/renovate\.json5?$/;
27
27
  const FIXES = P2("2", "Vulnerabilities fixed without delay");
28
+ // Security scanners people wire into CI. A scan whose failure is thrown away gates nothing.
29
+ // A scanner's name inside a path (/opt/hostedtoolcache/CodeQL) is not a scan.
30
+ const SCANNER = /(?<![\/.\w-])(trivy|semgrep|gitleaks|trufflehog|snyk|grype|checkov|tfsec|bandit|osv-scanner|pip-audit|codeql|dependency-check|zap-baseline|(npm|yarn|pnpm)\s+audit|safety\s+check)\b/i;
31
+ const CI_FILES = /(^|\/)(\.github\/workflows\/|\.gitlab-ci|\.circleci\/|azure-pipelines|bitbucket-pipelines|\.buildkite\/)/;
32
+ /** CI lines where a security scan can't fail the build: `|| true`, a soft-fail flag, or continue-on-error on the scan's step. Pure. */
33
+ export function scanCannotFail(lines) {
34
+ return lines.flatMap((l, i) => {
35
+ if (/^\s*#/.test(l))
36
+ return [];
37
+ // Output written to a file is a report collected for a later step, not a result thrown away (review: 4 of 4).
38
+ if (SCANNER.test(l) && /\|\|\s*(true\b|exit\s+0\b|:\s*$|echo\b)|--exit-code[= ]0\b|--soft-fail\b|--no-fail\b/.test(l))
39
+ return /\s>\s*\S/.test(l.replace(/[12]?>\s*(&1|\/dev\/null)/g, "")) ? [] : [i + 1];
40
+ // continue-on-error belongs to a step: look a few lines either side, stopping at the next step.
41
+ if (!/^\s*(continue-on-error|allow_failure)\s*:\s*true\b/.test(l))
42
+ return [];
43
+ const from = lines.slice(Math.max(0, i - 6), i).reverse(), to = lines.slice(i + 1, i + 7);
44
+ const cut = (xs) => { const k = xs.findIndex((x) => /^\s*-\s+(name|uses|run)\s*:/.test(x)); return k < 0 ? xs : xs.slice(0, k + 1); };
45
+ const before = cut(from), after = to.slice(0, Math.max(0, to.findIndex((x) => /^\s*-\s+(name|uses|run)\s*:/.test(x)) < 0 ? to.length : to.findIndex((x) => /^\s*-\s+(name|uses|run)\s*:/.test(x))));
46
+ // In a `uses:` line the scanner's name is part of the action's path (aquasecurity/trivy-action).
47
+ // Uploading a report, or a step named for installing the tool, is not the scan.
48
+ if ([...before, ...after].some((x) => /upload-sarif|^\s*-?\s*name\s*:.*\binstall/i.test(x)))
49
+ return [];
50
+ return [...before, ...after].some((x) => SCANNER.test(x) || /\buses:.*(trivy|semgrep|gitleaks|trufflehog|snyk|codeql|checkov|grype)/i.test(x)) ? [i + 1] : [];
51
+ });
52
+ }
53
+ // Public indexes people add on purpose and that hold their own package names (GPU builds of PyTorch and friends).
54
+ const KNOWN_INDEX = /download\.pytorch\.org|pypi\.org|pypi\.nvidia\.com|test\.pypi\.org/;
55
+ /** A package source that can be swapped under you. Gap for plain HTTP or TLS checks off; Partial for a second index. Pure. */
56
+ export function unsafeSource(l) {
57
+ if (/^\s*(#|\/\/)/.test(l))
58
+ return false;
59
+ if (/(^|\s)(--index-url|-i|--extra-index-url)[= ]\s*http:\/\/(?!localhost|127\.0\.0\.1)|^\s*(@[\w-]+:)?registry\s*=\s*http:\/\/(?!localhost|127\.0\.0\.1)|^\s*(extra-)?index-url\s*=\s*http:\/\/(?!localhost|127\.0\.0\.1)/.test(l))
60
+ return true;
61
+ if (/^\s*strict-ssl\s*=\s*false\b|\bnpm\s+config\s+set\s+strict-ssl\s+false\b/.test(l))
62
+ return true;
63
+ if (/(^|\s)--trusted-host[= ]\s*(?!localhost|127\.0\.0\.1)\S|^\s*trusted-host\s*=\s*(?!localhost|127\.0\.0\.1)\S/.test(l))
64
+ return "partial";
65
+ // pip takes the highest version from any index, so a public package with an internal name wins (dependency confusion).
66
+ return /(^|\s)--extra-index-url[= ]\s*\S|^\s*extra-index-url\s*=\s*\S/.test(l) && !KNOWN_INDEX.test(l) ? "partial" : false;
67
+ }
28
68
  export const craRules = [
69
+ { id: "ci.scan-cannot-fail", title: "Security scan in CI that can never fail the build", status: "partial", severity: "low", controls: [UPDATES, A03],
70
+ fix: "Let the scan fail the job. If it is too noisy, limit it to high severity or to new findings instead of ignoring its result.",
71
+ note: "With `|| true`, a soft-fail flag or continue-on-error, the scan runs and reports but nothing stops a build that has findings, so it gives a sense of safety it doesn't deliver. Marked Partial: some teams read the report by hand on purpose.",
72
+ extensions: [".yml", ".yaml"], pathMatch: CI_FILES, fileTest: scanCannotFail, ...DRAFT },
73
+ { id: "deps.unsafe-source", title: "Packages fetched from a source that can be swapped", status: "gap", severity: "medium", controls: [COMPONENTS, A03, A08],
74
+ fix: "Use one index or registry over https. For private packages, point only their scope or name at the private registry (npm: @scope:registry=..., pip: --index-url with a proxy that serves both) instead of adding a second index.",
75
+ note: "Over plain HTTP, or with certificate checks off, anyone on the network path can serve a different package. With a second pip index, a public package that takes an internal name with a higher version is installed instead (dependency confusion, CWE-829). Partial for the second-index case: your internal names may already be reserved.",
76
+ extensions: [".txt", ".conf", ".cfg", ".ini", ".toml", ".sh", ".bash", ".yml", ".yaml", ""],
77
+ fileName: /^(requirements[\w.-]*\.txt|constraints[\w.-]*\.txt|pip\.(conf|ini)|\.npmrc|\.yarnrc|pyproject\.toml|setup\.cfg)$|\.(sh|bash|ya?ml)$|^(Dockerfile|Containerfile)|\.Dockerfile$/i,
78
+ test: unsafeSource, ...DRAFT },
29
79
  { id: "repo.no-security-policy", title: "No way for people to report a vulnerability", status: "partial", severity: "medium", controls: [DISCLOSURE],
30
80
  fix: "Add a SECURITY.md to the repository root (or .github/) saying where to report a vulnerability, what to include and how soon you'll reply.",
31
81
  note: "The Cyber Resilience Act expects a policy for coordinated vulnerability disclosure and a contact address for reports. Marked Partial: the policy may live on your website, or you scanned a subfolder of a larger repo.",
@@ -37,18 +87,23 @@ export const craRules = [
37
87
  { id: "update.unverified-download", title: "Downloaded script run without a check", status: "partial", severity: "medium", controls: [UPDATES, A03, A08],
38
88
  fix: "Download the file first, check it against a published checksum or signature, then run it. Or install from a package manager that verifies packages.",
39
89
  note: "Piping `curl` or `wget` straight into a shell runs whatever the server sends at that moment, with no check that it is the file you expect. Marked Partial: well-known installers over HTTPS are a common, accepted risk.",
40
- extensions: [".sh", ".bash", ".yml", ".yaml", ""], fileName: /\.(sh|bash|ya?ml)$|^Dockerfile/i,
90
+ extensions: [".sh", ".bash", ".yml", ".yaml", ""], fileName: /\.(sh|bash|ya?ml)$|^(Dockerfile|Containerfile)|\.Dockerfile$/i,
41
91
  // Quoted text is dropped first: `echo "Install via: curl ... | bash"` tells a person what to run, it runs nothing (field test).
42
92
  // A script served from this machine (a CI test of the project's own installer) or an installer pinned to a version
43
93
  // in its URL is not a moving download (0.3.9 review: 8 of 10 sampled findings were these, or prose).
44
94
  test: (l) => /\b(curl|wget)\b[^|#\n]*\|\s*(sudo\s+)?(-\S+\s+)*(ba|z|da)?sh\b/.test(l.replace(/"(?:\\.|[^"\\])*"|'[^']*'/g, '""'))
45
95
  && !/\b(localhost|127\.0\.0\.1|0\.0\.0\.0)\b/.test(l) && !/https?:\/\/\S*\/v?\d+\.\d+(\.\d+)?\/\S*install/.test(l),
96
+ // The URL is a variable set to this machine a few lines up: BASE_URL=http://127.0.0.1:8765, then curl "$BASE_URL/get.sh" | bash.
97
+ // shortcut: any such assignment within 8 lines counts, tie it to the variable the curl uses if that ever hides a real one.
98
+ unlessNear: /^\s*(export\s+)?[A-Za-z_]\w*=["']?https?:\/\/(localhost|127\.0\.0\.1)\b/,
46
99
  // YAML is only run as a script in CI and compose files; elsewhere (manifests, risk registers) it is prose.
47
100
  unlessPath: /^(?!.*(\.github\/workflows|\.gitlab-ci|\.circleci|bitbucket-pipelines|azure-pipelines|\.buildkite|docker-compose|(^|\/)compose\.)).*\.ya?ml$/i, ...DRAFT },
48
101
  { id: "ci.write-all-permissions", title: "Workflow gives its token write access to everything", status: "gap", severity: "medium", controls: [UPDATES, A03],
49
102
  fix: "Replace `permissions: write-all` with only what the job needs, for example `permissions: contents: read`, and grant write access per job where it's really used.",
50
103
  note: "With write-all, any step that is compromised, including a third-party action, can push code, change releases or edit issues with the workflow's token.",
51
- extensions: [".yml", ".yaml"], pathMatch: WORKFLOWS, test: (l) => /^\s*permissions:\s*["']?write-all\b/.test(l), ...DRAFT },
104
+ extensions: [".yml", ".yaml"], pathMatch: WORKFLOWS, test: (l) => /^\s*permissions:\s*["']?write-all\b/.test(l),
105
+ // A pull_request_target workflow with no permissions block at all gets the repository default, which is often write.
106
+ fileTest: (lines) => (lines.some((l) => /^\s*permissions\s*:/.test(l)) ? [] : lines.flatMap((l, i) => (/^\s*(-\s*)?pull_request_target\b|^\s*on\s*:.*\bpull_request_target\b/.test(l) ? [{ line: i + 1, status: "partial" }] : []))), ...DRAFT },
52
107
  { id: "ci.script-injection", title: "Text from a pull request or issue pasted into a workflow command", status: "gap", severity: "high", controls: [UPDATES, A03, A08],
53
108
  fix: "Pass the value through an environment variable instead, for example `env: TITLE: ${{ github.event.issue.title }}` and then use \"$TITLE\" in the script.",
54
109
  note: "Anyone who opens an issue or pull request controls its title, body and branch name. Pasted into a `run:` step, that text becomes part of the shell command and can run anything with the workflow's secrets.",
@@ -66,8 +121,23 @@ export const craRules = [
66
121
  export function untrustedInRun(lines) {
67
122
  const out = [];
68
123
  let runIndent = -1; // indent of the `run: |` key while inside its block
124
+ // A job that only runs for people with write access gets its PR fields from trusted authors (0.3.14 review).
125
+ // shortcut: a step-level `if` counts for the rest of its job too, read job and step conditions apart if that misleads.
126
+ let trusted = false;
69
127
  lines.forEach((l, i) => {
70
128
  const indent = l.search(/\S/);
129
+ if (/^ {2}[\w-]+:\s*(#.*)?$/.test(l))
130
+ trusted = false; // next job
131
+ if (runIndent < 0 && /author_association\s*==\s*["'](OWNER|MEMBER|COLLABORATOR)["']/.test(l))
132
+ trusted = true;
133
+ if (trusted) {
134
+ if (runIndent >= 0 && indent >= 0 && indent <= runIndent)
135
+ runIndent = -1;
136
+ const r = /^(\s*-?\s*)(?:run|script):\s*[|>][-+]?\s*$/.exec(l);
137
+ if (r)
138
+ runIndent = r[1].length;
139
+ return;
140
+ }
71
141
  if (runIndent >= 0 && indent >= 0 && indent <= runIndent)
72
142
  runIndent = -1;
73
143
  // Also `script:` in actions/github-script, where the text becomes JavaScript instead of shell (review P17).
@@ -1,4 +1,5 @@
1
1
  import type { Rule } from "../types.js";
2
+ export declare const MASKED: RegExp;
2
3
  /** Shannon entropy in bits per character. Real keys are random (about 4 and up); aaaa... or xxxx... is near 0. Pure. */
3
4
  export declare function entropy(s: string): number;
4
5
  /** A Supabase (or any) JWT whose payload says role: service_role. Decoded exactly, so near-zero false alarms. Pure. */
@@ -3,6 +3,7 @@ import { stackRules } from "./stack.js";
3
3
  import { moreRules } from "./more.js";
4
4
  import { craForExisting, craRules } from "./cra.js";
5
5
  import { standardsForExisting, standardsRules } from "./standards.js";
6
+ import { apiForExisting, apiRules } from "./api.js";
6
7
  const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
7
8
  // Beta: mapped by us from our own reading of the public texts.
8
9
  const DRAFT = { mappedBy: "beta", reviewedAt: "pending" };
@@ -12,7 +13,9 @@ const LOG_CALL = /\b(console\.(log|info|warn|error|debug)|logger\.\w+|log\.(info
12
13
  // exponentially on text such as an array of regular expressions (found when statements were joined).
13
14
  const codeOnly = (l) => l.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
14
15
  // Helpers that hide the raw value before it is logged.
15
- const MASKED = /\b\w*(mask|hash|pseudonym|redact|anonymi[sz]e|obfuscate|scrub)\w*\s*\(/i;
16
+ // Certificate or host-name checks switched off in Java, Kotlin, Dart and Python.
17
+ const NATIVE_TLS_OFF = /\bALLOW_ALL_HOSTNAME_VERIFIER\b|\b(setHostnameVerifier|hostnameVerifier)\s*[({]\s*\{?\s*\(?\s*\w+\s*,\s*\w+\s*\)?\s*->\s*true\b|\bHostnameVerifier\s*\{\s*\w+\s*,\s*\w+\s*->\s*true\s*\}|\bbadCertificateCallback\s*=\s*\([^)]*\)\s*=>\s*true|\bonReceivedSslError\b[^\n]*\.proceed\(\)|\b_create_unverified_context\(/;
18
+ export const MASKED = /\b\w*(mask|hash|pseudonym|redact|anonymi[sz]e|obfuscate|scrub)\w*\s*\(/i;
16
19
  const PII = /\b(e-?mail|phone|ssn|social_?security|passport|date_?of_?birth|dob|password|passwd|credit_?card|card_?number|iban)\b/i;
17
20
  // The arguments of the first log call on a line, up to its matching ")". Other code on the same line is ignored.
18
21
  function logArgs(l) {
@@ -48,7 +51,7 @@ const KEY_FORMATS = new RegExp([
48
51
  "-----BEGIN (RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----", "-----BEGIN PGP PRIVATE KEY BLOCK-----",
49
52
  ].join("|"));
50
53
  // Example values from provider docs (AKIAIOSFODNN7EXAMPLE and the like) and obvious fill-ins.
51
- const DOC_EXAMPLE = /EXAMPLE|X{6,}|x{6,}|0{12,}|1234567890abcdef/;
54
+ const DOC_EXAMPLE = /EXAMPLE|X{6,}|x{6,}|0{12,}|1234567890abcdef|abc123/;
52
55
  /** Shannon entropy in bits per character. Real keys are random (about 4 and up); aaaa... or xxxx... is near 0. Pure. */
53
56
  export function entropy(s) {
54
57
  const n = {};
@@ -58,6 +61,15 @@ export function entropy(s) {
58
61
  }
59
62
  // A PEM header with no key body after it: in a comment, or text a program builds a key around at runtime (field-test review).
60
63
  const PEM_NO_BODY = /^\s*(#|\/\/|\*|<!--|--\s)|PRIVATE KEY( BLOCK)?-----(\\n)?["'`]\s*(\+|\.join|,|\))/;
64
+ // A key written inside one string that ends on the same line, with a body too short or too regular to be a key: a redaction
65
+ // test's "CanaryLineOne", a cut-off sample. The shortest real key (Ed25519) has 64 base64 characters (0.3.14 review: 17 of 17).
66
+ const pemInlineFake = (l) => {
67
+ const after = l.slice(l.indexOf("PRIVATE KEY")).replace(/^PRIVATE KEY( BLOCK)?-----/, "");
68
+ const body = after.split("-----END")[0].replace(/\\+[nr]|[^A-Za-z0-9+/=]/g, "");
69
+ return /-----END|["'`]\s*[,;)\]}]*\s*$/.test(after) && (body.length < 64 || /abcdefghijklmnop/.test(body));
70
+ };
71
+ // A "secret" whose base64 reads as a sentence is documentation ("This is an example of a shorter Base64 string").
72
+ const readsAsText = (key) => /^(?=.* )[\x20-\x7e]{12,}$/.test(Buffer.from(key.slice(key.lastIndexOf("_") + 1), "base64").toString("latin1"));
61
73
  // More fixed-prefix secrets this audience leaks: Stripe webhook secrets, Supabase secret keys, Resend keys (review P13).
62
74
  const MORE_KEYS = /\bwhsec_[0-9A-Za-z]{24,}|\bsb_secret_[0-9A-Za-z_-]{20,}|\bre_[0-9A-Za-z]{8,}_[0-9A-Za-z]{16,}/;
63
75
  /** A Supabase (or any) JWT whose payload says role: service_role. Decoded exactly, so near-zero false alarms. Pure. */
@@ -102,6 +114,9 @@ export const rules = [
102
114
  // A value passed through a masking or hashing helper first (maskEmail(), pseudonym(), hash()) is not the raw value:
103
115
  // every false alarm on 56 new repos in the 0.3.9 review was masked this way (12 of 12).
104
116
  test: (l) => { const a = logArgs(l); return a !== null && !l.includes("::add-mask::") && PII.test(codeOnly(a)) && !MASKED.test(a); },
117
+ // A command-line tool prints to the terminal of the person running it, not to a log store: "Logged in as <email>"
118
+ // after a login is the point of the command (5 of the 12 false alarms still shown in 0.3.14; no real one was in a CLI).
119
+ unlessPath: /(^|\/)cli\/|(^|\/)(packages|apps)\/[^/]*cli[^/]*\//i,
105
120
  ...DRAFT,
106
121
  },
107
122
  {
@@ -126,14 +141,14 @@ export const rules = [
126
141
  const pem = !!m && /-----BEGIN/.test(m[0]);
127
142
  // The part after a fixed prefix must look random: ghp_aaaaaaaa... is a fill-in, not a token.
128
143
  const tooRegular = !!m && !pem && entropy(m[0].replace(/^[A-Za-z]+[_-]+(?:[a-z]+[_-]+)?/, "")) < 3;
129
- if (pem && PEM_NO_BODY.test(l))
144
+ if (pem && (PEM_NO_BODY.test(l) || pemInlineFake(l)))
130
145
  return serviceRoleJwt(l) || dbUrlWithPassword(l);
131
- return (!!m && !tooRegular && !DOC_EXAMPLE.test(m[0]) && !/your[-_]|fake|dummy|placeholder|changeme|sample/.test(m[0]) /* lowercase words: real keys are random */
146
+ return (!!m && !tooRegular && !DOC_EXAMPLE.test(m[0]) && (pem || !readsAsText(m[0])) && !/your[-_]|fake|dummy|placeholder|changeme|sample/.test(m[0]) /* lowercase words: real keys are random */
132
147
  && !/PRIVATE KEY( BLOCK)?-----(["'`]|\.\.\.|\\n\s*\.\.\.|\s+[a-zA-Z])/.test(l)) || serviceRoleJwt(l) || dbUrlWithPassword(l);
133
148
  },
134
149
  // Translation files mention "API key" and "secret" in every language, never a real key. Type definition files
135
150
  // carry documentation examples, and secret-scanner configs list known test keys on purpose (0.3.9 review).
136
- unlessPath: /(^|\/)(locales?|i18n|translations?|lang)\/|\.d\.ts$|(^|\/)(\.gitleaks\.toml|\.secrets\.baseline|\.trufflehog\.ya?ml)$/i,
151
+ unlessPath: /(^|\/)(locales?|i18n|translations?|lang)\/|\.d\.ts$|(^|\/)(\.gitleaks\.toml|\.gitleaksignore|\.secrets\.baseline|\.trufflehog\.ya?ml)$/i,
137
152
  ...DRAFT,
138
153
  },
139
154
  {
@@ -147,7 +162,7 @@ export const rules = [
147
162
  note: "Marked Partial: the call may carry no sensitive data. Confirm, then switch to HTTPS anyway.",
148
163
  extensions: CODE,
149
164
  // Loopback, private ranges and single-label service names (http://redis:6379) stay on the machine or network (field test).
150
- test: (l) => /\b(fetch|axios\.\w+|requests\.\w+|http\.(get|request))\s*\(\s*["'`]http:\/\/(?!localhost|127\.|0\.0\.0\.0|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[::1\]|host\.docker\.internal)[\w-]+\.[\w.-]+/.test(l),
165
+ test: (l) => /\b(fetch|axios\.\w+|requests\.\w+|http\.(get|request))\s*\(\s*["'`]http:\/\/(?!localhost|127\.|0\.0\.0\.0|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[::1\]|host\.docker\.internal|[\w.-]+\.(test|example|invalid|localhost)(?![\w.-]))[\w-]+\.[\w.-]+/.test(l),
151
166
  ...DRAFT,
152
167
  },
153
168
  {
@@ -162,7 +177,9 @@ export const rules = [
162
177
  extensions: CODE,
163
178
  // Also a bare track("event", { ... }), the way @vercel/analytics and similar SDKs are imported and called.
164
179
  test: (l) => (/\b(posthog|analytics|mixpanel|amplitude|segment|heap|gtag|ga|intercom|hotjar|sentry)\.(identify|track|capture|people\.set|setUser|setUserProperties|register)\s*\(/i.test(l)
165
- || /(^|[^.\w])track\s*\(\s*["'`][^"'`]+["'`]\s*,\s*\{/.test(l)) && PII.test(l),
180
+ || /(^|[^.\w])track\s*\(\s*["'`][^"'`]+["'`]\s*,\s*\{/.test(l)) && PII.test(l.replace(/:\s*["'][\w -]*["']/g, ": 0")),
181
+ // Sent only inside a branch that checks the person opted in (0.3.14 review).
182
+ unlessNear: /\bif\b.*\b(opted_?[iI]n|has_?[cC]onsent|consent(Given|ed)?)\b/,
166
183
  ...DRAFT,
167
184
  },
168
185
  {
@@ -208,8 +225,11 @@ export const rules = [
208
225
  ],
209
226
  fix: "Remove the override and trust a proper certificate. For self-signed certs in tests, scope it to the test only.",
210
227
  note: "With checks off, anyone on the network path can read or change the traffic.",
211
- extensions: [...CODE, ".env"],
212
- test: (l) => /rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*[=:]\s*["']?0|\b(requests|httpx|session|client|Client|AsyncClient|urlopen)\b.*\bverify\s*=\s*False|InsecureSkipVerify\s*:\s*true|verify_mode\s*=\s*ssl\.CERT_NONE|cert_reqs\s*=\s*ssl\.CERT_NONE/.test(l), // naming CERT_NONE in a settings map isn't switching it on
228
+ // Scripts and Dockerfiles switch the check off too: curl -k, curl --insecure, wget --no-check-certificate.
229
+ extensions: [...CODE, ".env", ".sh", ".bash", "", ".java", ".kt", ".swift", ".go", ".dart"],
230
+ test: (l) => (/\bcurl\b[^|;&\n]*\s(-[sSfLIvO#]*k[sSfLIvO#]*|--insecure)(\s|$)|\bwget\b[^|;&\n]*--no-check-certificate\b/.test(l) && !/^\s*#|localhost|127\.0\.0\.1/.test(l)) || NATIVE_TLS_OFF.test(l) || /rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*[=:]\s*["']?0|\b(requests|httpx|session|client|Client|AsyncClient|urlopen)\b.*\bverify\s*=\s*False|InsecureSkipVerify\s*:\s*true|verify_mode\s*=\s*ssl\.CERT_NONE|cert_reqs\s*=\s*ssl\.CERT_NONE/.test(l), // naming CERT_NONE in a settings map isn't switching it on
231
+ // A host-name check switched off on its own. Next to CERT_NONE the neighbouring line already reports it (review: 8 of 8 were doubles).
232
+ fileTest: (lines) => lines.flatMap((l, i) => (/\bcheck_hostname\s*=\s*False\b/.test(l) && !/CERT_NONE/.test([lines[i - 1], lines[i + 1], lines[i + 2]].join(" ")) ? [i + 1] : [])),
213
233
  // Only the switches with one safe opposite; env vars and ssl modes need a person.
214
234
  patch: (l) => l.replace(/rejectUnauthorized(\s*):(\s*)false/, "rejectUnauthorized$1:$2true").replace(/\bverify(\s*)=(\s*)False\b/, "verify$1=$2True").replace(/InsecureSkipVerify(\s*):(\s*)true/, "InsecureSkipVerify$1:$2false"),
215
235
  ...DRAFT,
@@ -261,6 +281,8 @@ export const rules = [
261
281
  fileTest: (lines) => lines.flatMap((l, i) => {
262
282
  if (!/Access-Control-Allow-Origin["']?\s*[,:]\s*(["']\*["']|[\w.]*(req|request)\.headers?(\.get\(|\[|\.)\s*["']?origin)|origin\s*:\s*(["']\*["']|true\b|[\w.]*(req|request)\.headers?\.origin)|CORS_ALLOW_ALL_ORIGINS\s*=\s*True|CORS_ORIGIN_ALLOW_ALL\s*=\s*True|allow_origins\s*=\s*\[\s*["']\*["']|allow_origin_regex\s*=\s*["']\.\*/.test(l))
263
283
  return [];
284
+ if (/credentials["']?\s*[:=]\s*["']?false|allow_credentials\s*=\s*False|CORS_ALLOW_CREDENTIALS\s*=\s*False/i.test(lines.slice(Math.max(0, i - 3), i + 9).join("\n")))
285
+ return [];
264
286
  const near = lines.slice(Math.max(0, i - 12), i + 13).join("\n");
265
287
  return /credentials["']?\s*[:=,]\s*["']?true|Allow-Credentials["']?\s*[,:]\s*["']?true|CORS_ALLOW_CREDENTIALS\s*=\s*True|allow_credentials\s*=\s*True|supports_credentials\s*=\s*True/i.test(near) ? [i + 1] : [];
266
288
  }),
@@ -278,6 +300,9 @@ export const rules = [
278
300
  // A bare `secure: false` is usually a client, proxy or database option: it counts only near a cookie being set
279
301
  // (0.3.9 labels: 9 of 14 false alarms had no cookie in sight). CSRF cookies are meant to be readable by scripts.
280
302
  fileTest: (lines) => lines.flatMap((l, i) => {
303
+ // A session cookie set with no options at all gets neither flag.
304
+ if (/\bres\.cookie\(\s*["'`][\w.-]*(session|sess|sid|token|auth|jwt)[\w.-]*["'`]\s*,\s*[^,()]+\)/i.test(l) && !/csrf|xsrf/i.test(l))
305
+ return [i + 1];
281
306
  if (!/\b(httpOnly|secure)\s*:\s*false\b|SESSION_COOKIE_(SECURE|HTTPONLY)\s*=\s*False/.test(l))
282
307
  return [];
283
308
  const near = lines.slice(Math.max(0, i - 6), i + 4).join("\n");
@@ -316,6 +341,10 @@ const AI_CALL = new RegExp([
316
341
  /\bnew\s+(ToolLoopAgent|Experimental_Agent)\s*\(/.source,
317
342
  /\b(model|clf|classifier|pipeline)\.(predict|predict_proba|invoke|generate)\s*\(/.source,
318
343
  /\b(chain|llm|chatModel|agent|runnable)\w*\.(invoke|stream|batch)\s*\(/.source,
344
+ // Other common shapes, each in the SDK's own form so an app's own run() or chat() helper doesn't count: LiteLLM,
345
+ // Ollama, the Python Gemini SDK, Mistral, Bedrock, and a generator component run on its own.
346
+ /\blitellm\.a?completion\s*\(|\bollama\.(chat|generate)\s*\(|\.generate_content(_stream|_async)?\s*\(|\.chat\.complete(_async)?\s*\(/.source,
347
+ /\.invoke_model(_with_response_stream)?\s*\(|\bbedrock\w*\.converse(_stream)?\s*\(|\b(chat_)?generator\.run\s*\(/.source,
319
348
  // A provider URL counts only inside a request call, not where it's stored in a constant.
320
349
  /\b(fetch|axios(\.\w+)?|requests\.\w+|httpx\.\w+|ky(\.\w+)?)\s*\(\s*[`"'][^`"']*(api\.openai\.com\/v1\/(chat|responses|completions|images|audio)|api\.anthropic\.com\/v1\/messages|generativelanguage\.googleapis\.com|openrouter\.ai\/api|api\.groq\.com|api\.mistral\.ai|api\.deepseek\.com)/.source,
321
350
  ].join("|"), "i");
@@ -348,7 +377,10 @@ rules.push({
348
377
  extensions: CODE,
349
378
  // A model's output and a decision word on the same line, e.g. status = model.predict(x) > 0.5 ? "approved" : "rejected".
350
379
  // score() and invoke() are too generic: a music score, a memory ranking (field test).
351
- test: (l) => /\b(predict|predict_proba|classify|generateText|generateObject)\w*\s*\(|\.chat\.completions\.create\s*\(/.test(l) && DECISION.test(l),
380
+ test: (l) => /\b(predict|predict_proba|classify|generateText|generateObject)\w*\s*\(|\.chat\.completions\.create\s*\(/.test(l) && DECISION.test(l)
381
+ // A function being defined decides nothing yet, and allow/deny for a tool, a permission or access is an agent's
382
+ // permission system, not a decision about a person (0.3.14 review: 0 of 4 shown findings were about people).
383
+ && !/^\s*(export\s+)?(async\s+)?(def|function)\s/.test(l) && !/\b(tool|permissions?|access)\b/.test(l),
352
384
  ...DRAFT,
353
385
  }, {
354
386
  id: "ai.call-not-logged",
@@ -417,6 +449,10 @@ rules.push(...standardsRules);
417
449
  // After the push, so the new LLM rules also get their CWE tags.
418
450
  for (const r of rules)
419
451
  r.controls.push(...(standardsForExisting[r.id] ?? []));
452
+ // OWASP API Security Top 10: one rule of its own, then tags on the rules above.
453
+ rules.push(...apiRules);
454
+ for (const r of rules)
455
+ r.controls.push(...(apiForExisting[r.id] ?? []));
420
456
  // Measured on 270 findings reviewed one by one from 139 public repositories (0.3.9). These rules were real in fewer than
421
457
  // half of their sampled findings, so they are held back unless --all (show: all) is set, and the report says how many.
422
458
  // A rule moves back to high confidence when a fresh labelled sample shows it is real in most findings.
@@ -3,6 +3,35 @@ import type { Rule } from "../types.js";
3
3
  export declare function wsNoOrigin(lines: string[]): number[];
4
4
  /** Lines matching re in a file that registers MCP tools; nothing in other files. Pure. */
5
5
  export declare function inMcpServer(lines: string[], re: RegExp): number[];
6
+ /** A skill line that sends the agent to a page on the internet for its next instructions. Pure. */
7
+ export declare const followsRemote: (l: string) => boolean;
8
+ /** A skill line that has the agent change its own standing instructions or settings. Pure. */
9
+ export declare const writesMemory: (l: string) => boolean;
10
+ /** MCP config: a server run from a version that can change after you approved it (Partial), or reached over plain HTTP (Gap). Pure.
11
+ * shortcut: reads npx-style args only ("-y", "pkg"); add uvx and docker image tags when a field test shows them. */
12
+ export declare function mcpConfigUnsafe(lines: string[]): Array<{
13
+ line: number;
14
+ status: "gap" | "partial";
15
+ }>;
16
+ /** Key sizes and work factors below what current guidance accepts. Pure. */
17
+ export declare function weakCryptoParameter(l: string): boolean | "partial";
18
+ /** Android release build that can be debugged: the manifest flag, or `debuggable true` inside the release block of build.gradle. Pure. */
19
+ export declare function debuggableBuild(lines: string[]): number[];
20
+ /** A line that declares a stored field with one of these names: SQL column, Prisma, Mongoose, Sequelize, TypeORM, Django,
21
+ * SQLAlchemy. A TypeScript type (`cvv: string`) describes a form value, not storage, so it doesn't count. Pure. */
22
+ export declare function storedField(names: string): (l: string) => boolean;
23
+ /** A consent or marketing checkbox that starts ticked, or its state that starts as true. Pure. */
24
+ export declare function consentPreticked(lines: string[]): number[];
25
+ /** A firewall rule that lets the whole internet reach an admin or database port. Reads the block around the open range:
26
+ * inbound only, and only when the ports are written there. Pure.
27
+ * shortcut: reads up to 10 lines either side of the range, not the parsed block; parse HCL if rules get longer. */
28
+ export declare function networkOpen(lines: string[]): number[];
29
+ /** A policy statement that allows every action on every resource. A Deny statement with the same wildcards is a guard. Pure. */
30
+ export declare function iamAllowAll(lines: string[]): number[];
31
+ /** Dockerfile whose last stage never switches away from root: the last FROM line, or its `USER root` line. Pure. */
32
+ export declare function dockerRunsAsRoot(lines: string[]): number[];
33
+ /** FROM lines with no tag or the `latest` tag. A stage name, a digest, a build argument and `scratch` are not images to pin. Pure. */
34
+ export declare function dockerImageUnpinned(lines: string[]): number[];
6
35
  export declare const moreRules: Rule[];
7
36
  /** The service password variable on this line when it's set to a well-known default, else null. Pure. */
8
37
  export declare function defaultPasswordKey(l: string): string | null;