@lintsure/core 0.2.0 → 0.3.1
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/dist/src/assessment.js +1 -1
- package/dist/src/datamap.d.ts +33 -0
- package/dist/src/datamap.js +169 -0
- package/dist/src/guidance.js +1 -1
- package/dist/src/index.d.ts +5 -1
- package/dist/src/index.js +73 -6
- package/dist/src/knowledge/index.js +2 -1
- package/dist/src/knowledge/owasp-top10.d.ts +2 -0
- package/dist/src/knowledge/owasp-top10.js +93 -0
- package/dist/src/rules/index.d.ts +4 -0
- package/dist/src/rules/index.js +34 -5
- package/dist/src/rules/owasp.d.ts +4 -0
- package/dist/src/rules/owasp.js +192 -0
- package/dist/src/types.d.ts +9 -1
- package/package.json +1 -1
package/dist/src/assessment.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { DISCLAIMER, NOT_A_VERDICT, nextSteps } from "./index.js";
|
|
5
5
|
import { knowledge } from "./knowledge/index.js";
|
|
6
6
|
const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
7
|
-
const NAME = { "eu-ai-act": "EU AI Act", gdpr: "GDPR", soc2: "SOC 2", "iso-27001": "ISO/IEC 27001" };
|
|
7
|
+
const NAME = { "eu-ai-act": "EU AI Act", gdpr: "GDPR", soc2: "SOC 2", "iso-27001": "ISO/IEC 27001", "owasp-top10": "OWASP Top 10:2025" };
|
|
8
8
|
const STATUS = { gap: "Gap", partial: "Partial", met: "Met", outside: "Outside code" };
|
|
9
9
|
const SEV = ["high", "medium", "low"];
|
|
10
10
|
const SKIPPED = "node_modules, .git, dist, build, out, .output, .next, .nuxt, .svelte-kit, .astro, .vercel, .netlify, .wrangler, .turbo, .cache, venv, .venv, __pycache__, coverage";
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Personal data fields, by the names code usually gives them. Order matters: first match wins. */
|
|
2
|
+
export declare const FIELDS: [string, RegExp][];
|
|
3
|
+
/** Destinations, grouped so the map stays readable. First match wins. */
|
|
4
|
+
export declare const DESTINATIONS: {
|
|
5
|
+
group: string;
|
|
6
|
+
name: string;
|
|
7
|
+
test: RegExp;
|
|
8
|
+
}[];
|
|
9
|
+
export interface DataFlow {
|
|
10
|
+
field: string;
|
|
11
|
+
group: string;
|
|
12
|
+
destination: string;
|
|
13
|
+
file: string;
|
|
14
|
+
line: number;
|
|
15
|
+
}
|
|
16
|
+
export interface DataMap {
|
|
17
|
+
filesRead: number;
|
|
18
|
+
flows: DataFlow[];
|
|
19
|
+
/** Fields seen anywhere in code, even when no destination was found on the same line. */
|
|
20
|
+
fieldsSeen: string[];
|
|
21
|
+
}
|
|
22
|
+
/** The text of a call that starts on lines[i]: up to the closing bracket, at most 15 lines. */
|
|
23
|
+
export declare function callSpan(lines: string[], i: number): string;
|
|
24
|
+
/** Pure: the flows in one call (the line where a destination starts, plus the rest of that call). */
|
|
25
|
+
export declare function flowsInLine(text: string, span?: string): {
|
|
26
|
+
field: string;
|
|
27
|
+
group: string;
|
|
28
|
+
destination: string;
|
|
29
|
+
}[];
|
|
30
|
+
export declare function buildDataMap(root: string): Promise<DataMap>;
|
|
31
|
+
export declare function toDataMapMarkdown(m: DataMap): string;
|
|
32
|
+
/** A self-contained HTML page: fields on the left, destinations on the right, a line for each flow. */
|
|
33
|
+
export declare function toDataMapHtml(m: DataMap, project: string): string;
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// Data map: where personal data goes in your code. For each line that mentions a personal data field
|
|
2
|
+
// and a destination (logs, analytics, a database, an email or payment provider, an AI model...),
|
|
3
|
+
// it records an edge: field → destination, with the file and line. Runs locally, never sends code.
|
|
4
|
+
// It reads each call up to its closing bracket: data passed through variables or helpers in other files is missed.
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { relative, sep, extname } from "node:path";
|
|
7
|
+
import { listFiles, readConfig } from "./index.js";
|
|
8
|
+
const CODE = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"]);
|
|
9
|
+
/** Personal data fields, by the names code usually gives them. Order matters: first match wins. */
|
|
10
|
+
export const FIELDS = [
|
|
11
|
+
["Email", /\b\w*e-?mail\w*\b/i],
|
|
12
|
+
["Phone", /\b\w*(phone|mobile|msisdn)\w*\b/i],
|
|
13
|
+
["Password", /\b\w*(password|passwd)\w*\b/i],
|
|
14
|
+
["Full name", /\b(full_?name|first_?name|last_?name|given_?name|family_?name|display_?name|username|user_?name)\b/i],
|
|
15
|
+
["Address", /\b(street|address_?line\d?|postcode|post_?code|zip_?code|billing_?address|shipping_?address|home_?address)\b/i],
|
|
16
|
+
["Date of birth", /\b(dob|date_?of_?birth|birth_?date|birthday)\b/i],
|
|
17
|
+
["Government ID", /\b(ssn|social_?security|passport\w*|national_?id|tax_?id|pesel|nin)\b/i],
|
|
18
|
+
["Payment card", /\b(card_?number|credit_?card|cc_?number|cvv|cvc|iban)\b/i],
|
|
19
|
+
["IP address", /\b(ip_?address|remote_?addr|client_?ip|x-forwarded-for|req\.ip)\b/i],
|
|
20
|
+
["Location", /\b(latitude|longitude|geo_?location|gps)\b/i],
|
|
21
|
+
["Health data", /\b(diagnosis|medical\w*|health_?\w+|prescription|blood_?type|mrn)\b/i],
|
|
22
|
+
];
|
|
23
|
+
/** Destinations, grouped so the map stays readable. First match wins. */
|
|
24
|
+
export const DESTINATIONS = [
|
|
25
|
+
{ group: "Logs", name: "Application logs", test: /\b(console\.(log|info|warn|error|debug)|logger\.\w+|log\.(info|warn|error|debug)|logging\.\w+)\s*\(/ },
|
|
26
|
+
{ group: "Analytics", name: "PostHog", test: /\bposthog\.\w+\(/i },
|
|
27
|
+
{ group: "Analytics", name: "Segment", test: /\b(analytics|segment)\.(identify|track|page)\(/ },
|
|
28
|
+
{ group: "Analytics", name: "Mixpanel", test: /\bmixpanel\.\w+/i },
|
|
29
|
+
{ group: "Analytics", name: "Amplitude", test: /\bamplitude\.\w+/i },
|
|
30
|
+
{ group: "Analytics", name: "Google Analytics", test: /\b(gtag|ga)\(/ },
|
|
31
|
+
{ group: "Analytics", name: "Intercom", test: /\bIntercom\(|\bintercom\.\w+/ },
|
|
32
|
+
{ group: "Error tracking", name: "Sentry", test: /\bSentry\.(setUser|captureException|captureMessage|setContext)\(/ },
|
|
33
|
+
{ group: "AI model", name: "OpenAI", test: /\bopenai\.(chat|responses|completions|embeddings)\b/i },
|
|
34
|
+
{ group: "AI model", name: "Anthropic", test: /\banthropic\.messages\b|\bclient\.messages\.create\(/i },
|
|
35
|
+
{ group: "AI model", name: "AI model", test: /\b(generateText|streamText|generateObject)\(/ },
|
|
36
|
+
{ group: "Email", name: "Resend", test: /\bresend\.emails\.send\(/i },
|
|
37
|
+
{ group: "Email", name: "SendGrid", test: /\bsgMail\.send\(|\bsendgrid\b/i },
|
|
38
|
+
{ group: "Email", name: "Postmark", test: /\bpostmark\b/i },
|
|
39
|
+
{ group: "Email", name: "Email (SMTP)", test: /\b(transporter|nodemailer)\.sendMail\(|\bsend_mail\(/ },
|
|
40
|
+
{ group: "Payments", name: "Stripe", test: /\bstripe\.(customers|checkout|paymentIntents|subscriptions|invoices)\b/i },
|
|
41
|
+
{ group: "Storage", name: "File storage", test: /\b(s3|r2|bucket|storage)\.(upload|putObject|put|from)\(|\bPutObjectCommand\b/i },
|
|
42
|
+
{ group: "Database", name: "Database", test: /\b(prisma\.\w+\.(create|update|upsert)|\.insert(One|Many)?\(|\.create\(|\.save\(|INSERT INTO|UPDATE \w+ SET|db\.(query|execute)\(|supabase\.from\()/i },
|
|
43
|
+
{ group: "Browser storage", name: "Browser storage", test: /\b(localStorage|sessionStorage)\.setItem\(|document\.cookie\s*=/ },
|
|
44
|
+
{ group: "Outside API", name: "Outside API", test: /\b(fetch|axios(\.(post|put|patch))?|requests\.(post|put|patch)|httpx\.(post|put))\s*\(/ },
|
|
45
|
+
];
|
|
46
|
+
/** Known services, named from the URL an outside call goes to. */
|
|
47
|
+
const HOSTS = [
|
|
48
|
+
[/api\.resend\.com/, "Email", "Resend"], [/api\.sendgrid\.com/, "Email", "SendGrid"], [/api\.postmarkapp\.com/, "Email", "Postmark"],
|
|
49
|
+
[/api\.mailgun\.net/, "Email", "Mailgun"], [/api\.stripe\.com/, "Payments", "Stripe"], [/api\.openai\.com/, "AI model", "OpenAI"],
|
|
50
|
+
[/api\.anthropic\.com/, "AI model", "Anthropic"], [/hooks\.slack\.com|slack\.com\/api/, "Messaging", "Slack"],
|
|
51
|
+
[/api\.hubapi\.com/, "CRM", "HubSpot"], [/api\.airtable\.com/, "Database", "Airtable"], [/googleapis\.com/, "Outside API", "Google APIs"],
|
|
52
|
+
];
|
|
53
|
+
/** Drops plain text inside quotes (keeping template ${...} parts), so "Enter your email" isn't counted. */
|
|
54
|
+
const codeOnly = (l) => l.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
|
|
55
|
+
/** The text of a call that starts on lines[i]: up to the closing bracket, at most 15 lines. */
|
|
56
|
+
export function callSpan(lines, i) {
|
|
57
|
+
let depth = 0, out = "";
|
|
58
|
+
for (let j = i; j < Math.min(lines.length, i + 15); j++) {
|
|
59
|
+
out += lines[j] + "\n";
|
|
60
|
+
for (const ch of codeOnly(lines[j])) {
|
|
61
|
+
if (ch === "(" || ch === "{" || ch === "[")
|
|
62
|
+
depth++;
|
|
63
|
+
else if (ch === ")" || ch === "}" || ch === "]")
|
|
64
|
+
depth--;
|
|
65
|
+
}
|
|
66
|
+
if (depth <= 0 && j > i - 1)
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
/** Pure: the flows in one call (the line where a destination starts, plus the rest of that call). */
|
|
72
|
+
export function flowsInLine(text, span = text) {
|
|
73
|
+
const dest = DESTINATIONS.find((d) => d.test.test(text));
|
|
74
|
+
if (!dest)
|
|
75
|
+
return [];
|
|
76
|
+
const host = dest.name === "Outside API" ? HOSTS.find(([re]) => re.test(span)) : undefined;
|
|
77
|
+
const named = host ? { group: host[1], name: host[2] } : { group: dest.group, name: dest.name };
|
|
78
|
+
const code = codeOnly(span);
|
|
79
|
+
return FIELDS.filter(([, re]) => re.test(code)).map(([field]) => ({ field, group: named.group, destination: named.name }));
|
|
80
|
+
}
|
|
81
|
+
export async function buildDataMap(root) {
|
|
82
|
+
const { ignore } = await readConfig(root);
|
|
83
|
+
const flows = [];
|
|
84
|
+
const seen = new Set();
|
|
85
|
+
let filesRead = 0;
|
|
86
|
+
for (const abs of await listFiles(root, ignore)) {
|
|
87
|
+
if (!CODE.has(extname(abs)))
|
|
88
|
+
continue;
|
|
89
|
+
const buf = await readFile(abs);
|
|
90
|
+
if (buf.length > 1_000_000 || buf.includes(0))
|
|
91
|
+
continue;
|
|
92
|
+
const lines = buf.toString("utf8").split(/\r?\n/);
|
|
93
|
+
if (lines.some((l) => l.length > 1000))
|
|
94
|
+
continue; // minified or generated
|
|
95
|
+
filesRead++;
|
|
96
|
+
const file = relative(root, abs).split(sep).join("/");
|
|
97
|
+
lines.forEach((text, i) => {
|
|
98
|
+
const code = codeOnly(text);
|
|
99
|
+
for (const [name, re] of FIELDS)
|
|
100
|
+
if (re.test(code))
|
|
101
|
+
seen.add(name);
|
|
102
|
+
if (DESTINATIONS.some((d) => d.test.test(text)))
|
|
103
|
+
for (const f of flowsInLine(text, callSpan(lines, i)))
|
|
104
|
+
flows.push({ ...f, file, line: i + 1 });
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
return { filesRead, flows, fieldsSeen: FIELDS.map(([n]) => n).filter((n) => seen.has(n)) };
|
|
108
|
+
}
|
|
109
|
+
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
110
|
+
const NOTE = "This map reads code call by call. It shows where a personal data field appears inside a call to a destination. Data passed through variables, helpers or other files may be missing, and some lines may be listed that don't send personal data. Check each one. It is a starting point for your record of processing, not the record itself.";
|
|
111
|
+
export function toDataMapMarkdown(m) {
|
|
112
|
+
const byDest = new Map();
|
|
113
|
+
for (const f of m.flows)
|
|
114
|
+
byDest.set(`${f.group} · ${f.destination}`, [...(byDest.get(`${f.group} · ${f.destination}`) ?? []), f]);
|
|
115
|
+
return [
|
|
116
|
+
"# Lintsure data map", "",
|
|
117
|
+
`${m.flows.length} place${m.flows.length === 1 ? "" : "s"} where personal data reaches a destination, in ${m.filesRead} files read.`, "",
|
|
118
|
+
`> ${NOTE}`, "",
|
|
119
|
+
...[...byDest].flatMap(([d, fl]) => [`## ${d}`, "", ...fl.map((f) => `- **${f.field}** · \`${f.file}:${f.line}\``), ""]),
|
|
120
|
+
`Personal data fields seen in code: ${m.fieldsSeen.join(", ") || "none"}.`, "",
|
|
121
|
+
].join("\n");
|
|
122
|
+
}
|
|
123
|
+
/** A self-contained HTML page: fields on the left, destinations on the right, a line for each flow. */
|
|
124
|
+
export function toDataMapHtml(m, project) {
|
|
125
|
+
const fields = [...new Set(m.flows.map((f) => f.field))];
|
|
126
|
+
const dests = [...new Set(m.flows.map((f) => `${f.group}|${f.destination}`))];
|
|
127
|
+
const rowH = 54, top = 60, h = Math.max(fields.length, dests.length) * rowH + top + 30, w = 900;
|
|
128
|
+
const fy = (i) => top + i * rowH + (Math.max(0, dests.length - fields.length) * rowH) / 2;
|
|
129
|
+
const dy = (i) => top + i * rowH + (Math.max(0, fields.length - dests.length) * rowH) / 2;
|
|
130
|
+
const pairs = new Map();
|
|
131
|
+
for (const f of m.flows) {
|
|
132
|
+
const k = `${f.field}→${f.group}|${f.destination}`;
|
|
133
|
+
pairs.set(k, [...(pairs.get(k) ?? []), f]);
|
|
134
|
+
}
|
|
135
|
+
const links = [...pairs].map(([k, fl]) => {
|
|
136
|
+
const [field, dest] = k.split("→");
|
|
137
|
+
const y1 = fy(fields.indexOf(field)) + 18, y2 = dy(dests.indexOf(dest)) + 18;
|
|
138
|
+
return `<path d="M260 ${y1} C 450 ${y1}, 450 ${y2}, 640 ${y2}" class="link" style="stroke-width:${Math.min(8, 1.5 + fl.length)}"><title>${esc(field)} → ${esc(dest.split("|")[1])}: ${fl.length}</title></path>`;
|
|
139
|
+
}).join("");
|
|
140
|
+
const box = (x, y, label, sub, cls) => `<g class="${cls}"><rect x="${x}" y="${y}" width="240" height="36" rx="9"/><text x="${x + 14}" y="${y + 23}">${esc(label)}</text>${sub ? `<text x="${x + 226}" y="${y + 23}" text-anchor="end" class="sub">${esc(sub)}</text>` : ""}</g>`;
|
|
141
|
+
const count = (pred) => String(m.flows.filter(pred).length);
|
|
142
|
+
const svg = `<svg viewBox="0 0 ${w} ${h}" width="100%" role="img" aria-label="Data map">
|
|
143
|
+
<text x="20" y="34" class="head">Personal data</text><text x="880" y="34" class="head" text-anchor="end">Where it goes</text>
|
|
144
|
+
${links}
|
|
145
|
+
${fields.map((f, i) => box(20, fy(i), f, count((x) => x.field === f), "field")).join("")}
|
|
146
|
+
${dests.map((d, i) => { const [g, n] = d.split("|"); return box(640, dy(i), n, g === n ? "" : g, "dest"); }).join("")}
|
|
147
|
+
</svg>`;
|
|
148
|
+
const rows = m.flows.map((f) => `<tr><td>${esc(f.field)}</td><td>${esc(f.destination)} <span class="g">${esc(f.group)}</span></td><td><code>${esc(f.file)}:${f.line}</code></td></tr>`).join("");
|
|
149
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
150
|
+
<title>Lintsure data map · ${esc(project)}</title>
|
|
151
|
+
<style>
|
|
152
|
+
:root{--ink:#141413;--muted:#5E5D59;--faint:#8A8984;--line:#E4E2DD;--canvas:#FBFBF9;--accent:#0B6E4F}
|
|
153
|
+
body{margin:0;background:var(--canvas);color:var(--ink);font:15px/1.55 -apple-system,"Segoe UI",Helvetica,Arial,sans-serif}
|
|
154
|
+
main{max-width:980px;margin:0 auto;padding:48px 24px 80px}h1{font-size:34px;letter-spacing:-.03em;margin:0}
|
|
155
|
+
.lead{color:var(--muted);margin:8px 0 24px}.card{background:#fff;border:1px solid var(--line);border-radius:16px;padding:16px;margin:20px 0}
|
|
156
|
+
svg text{font:14px -apple-system,"Segoe UI",Helvetica,Arial,sans-serif;fill:var(--ink)}svg .head{font-size:12px;font-weight:600;letter-spacing:.06em;fill:var(--faint);text-transform:uppercase}
|
|
157
|
+
.field rect{fill:#fff;stroke:var(--ink)}.dest rect{fill:#F5F4F1;stroke:var(--line)}svg .sub{fill:var(--faint);font-size:12px}
|
|
158
|
+
.link{fill:none;stroke:var(--accent);opacity:.35}.link:hover{opacity:.9}
|
|
159
|
+
table{width:100%;border-collapse:collapse;font-size:14px}td,th{border-bottom:1px solid var(--line);padding:8px 6px;text-align:left}th{font-size:12px;color:var(--faint);text-transform:uppercase;letter-spacing:.05em}
|
|
160
|
+
code{font:13px ui-monospace,Menlo,Consolas,monospace}.g{color:var(--faint);font-size:12px}.note{font-size:13px;color:var(--muted);border-left:2px solid var(--line);padding-left:12px}
|
|
161
|
+
</style></head><body><main>
|
|
162
|
+
<h1>Where personal data goes</h1>
|
|
163
|
+
<p class="lead">${esc(project)} · ${m.flows.length} place${m.flows.length === 1 ? "" : "s"} where personal data reaches a destination, in ${m.filesRead} files read.</p>
|
|
164
|
+
${m.flows.length ? `<div class="card">${svg}</div>` : `<p>No flows found by the current patterns. That doesn't mean there are none.</p>`}
|
|
165
|
+
<p class="note">${esc(NOTE)}</p>
|
|
166
|
+
${m.flows.length ? `<h2>Every flow</h2><table><tr><th>Field</th><th>Destination</th><th>Where</th></tr>${rows}</table>` : ""}
|
|
167
|
+
<p class="note">Made by Lintsure, an open-source readiness tool. It runs on your machine and never sends your code anywhere. Not legal advice.</p>
|
|
168
|
+
</main></body></html>`;
|
|
169
|
+
}
|
package/dist/src/guidance.js
CHANGED
|
@@ -5,7 +5,7 @@ export const APPROVAL_RULES = `Before you do anything (edit, create or delete a
|
|
|
5
5
|
3. Where, exactly: the file and line, or the document and section.
|
|
6
6
|
4. The benefit to the user if they approve it.
|
|
7
7
|
Then ask the user to approve that one proposal and wait. Only a clear yes is approval. Silence, "maybe" or a question is not. Do only what was approved, then show what changed. One proposal at a time.`;
|
|
8
|
-
const NAMES = { "eu-ai-act": "EU AI Act", gdpr: "GDPR", soc2: "SOC 2", "iso-27001": "ISO 27001" };
|
|
8
|
+
const NAMES = { "eu-ai-act": "EU AI Act", gdpr: "GDPR", soc2: "SOC 2", "iso-27001": "ISO 27001", "owasp-top10": "OWASP Top 10" };
|
|
9
9
|
const refs = (cs) => cs.map((c) => `${NAMES[c.framework]} ${c.id}`).join(", ");
|
|
10
10
|
/** Lays a finding out as a proposal a person can approve or decline. */
|
|
11
11
|
export function proposalFor(f) {
|
package/dist/src/index.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export { rules };
|
|
|
11
11
|
export * from "./guidance.js";
|
|
12
12
|
export { toAssessmentHtml } from "./assessment.js";
|
|
13
13
|
export * from "./knowledge/index.js";
|
|
14
|
-
export declare const RULES_VERSION = "0.
|
|
14
|
+
export declare const RULES_VERSION = "0.3.1";
|
|
15
15
|
/** Shown with every result, in every interface. Lintsure prepares; people decide. */
|
|
16
16
|
export declare const DISCLAIMER: string;
|
|
17
17
|
/** What a report must never be read as. Used in the report and by the MCP server. */
|
|
@@ -33,5 +33,9 @@ export declare function readConfig(root: string): Promise<{
|
|
|
33
33
|
export declare const SKIP_DIRS: string[];
|
|
34
34
|
/** Scout: list files to check, sorted so output order never depends on the file system. */
|
|
35
35
|
export declare function listFiles(root: string, ignore?: string[]): Promise<string[]>;
|
|
36
|
+
/** The JSON object key that opens the block a line sits in, e.g. "peerDependencies". Pure. */
|
|
37
|
+
export declare function enclosingKey(lines: string[], i: number): string;
|
|
38
|
+
/** Marks lines that are only a comment or sit inside a block comment or Python docstring. Pure. */
|
|
39
|
+
export declare function commentLines(lines: string[], ext: string): boolean[];
|
|
36
40
|
export declare function scan(root: string, frameworks?: FrameworkId[], opts?: RecordOptions): Promise<Report>;
|
|
37
41
|
export declare function toMarkdown(r: Report): string;
|
package/dist/src/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Scout (file walk) + Checker (rules) + Auditor (dedupe, sort) + Officer (outside code).
|
|
2
2
|
// No network calls anywhere in this package: a test enforces it.
|
|
3
3
|
import { readdir, readFile } from "node:fs/promises";
|
|
4
|
-
import { extname, join, relative, sep } from "node:path";
|
|
4
|
+
import { basename, extname, join, relative, sep } from "node:path";
|
|
5
5
|
import { outsideFor } from "./knowledge/index.js";
|
|
6
6
|
import { rules } from "./rules/index.js";
|
|
7
7
|
import { proposalFor } from "./guidance.js";
|
|
@@ -17,7 +17,7 @@ export { rules };
|
|
|
17
17
|
export * from "./guidance.js";
|
|
18
18
|
export { toAssessmentHtml } from "./assessment.js";
|
|
19
19
|
export * from "./knowledge/index.js";
|
|
20
|
-
export const RULES_VERSION = "0.
|
|
20
|
+
export const RULES_VERSION = "0.3.1";
|
|
21
21
|
/** Shown with every result, in every interface. Lintsure prepares; people decide. */
|
|
22
22
|
export const DISCLAIMER = "Lintsure is a readiness tool, not an audit, a certification or legal advice. " +
|
|
23
23
|
"Its rules reflect our reading of the publicly available text of each framework, and they check code only. " +
|
|
@@ -40,7 +40,7 @@ export function nextSteps(r) {
|
|
|
40
40
|
"Ask a qualified compliance professional to review the results before you rely on them.",
|
|
41
41
|
].filter(Boolean);
|
|
42
42
|
}
|
|
43
|
-
export const ALL_FRAMEWORKS = ["gdpr", "soc2", "iso-27001", "eu-ai-act"];
|
|
43
|
+
export const ALL_FRAMEWORKS = ["gdpr", "soc2", "iso-27001", "eu-ai-act", "owasp-top10"];
|
|
44
44
|
/** Reads the frameworks list from lintsure.config.yaml in the repo root, if there is one.
|
|
45
45
|
* Only the simple list form is supported:
|
|
46
46
|
* frameworks:
|
|
@@ -112,6 +112,53 @@ export async function listFiles(root, ignore = []) {
|
|
|
112
112
|
await walk(root);
|
|
113
113
|
return out.sort();
|
|
114
114
|
}
|
|
115
|
+
const TEST_PATH = /(^|\/)(tests?|__tests__|__mocks__|spec|fixtures?|e2e)\/|\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.(py|go)$/i;
|
|
116
|
+
const SECRET_RULES = new Set(["secret.in-source", "config.default-secret-key", "auth.hardcoded-password"]);
|
|
117
|
+
// Lines a person already reviewed and marked for a linter or security scanner.
|
|
118
|
+
const REVIEWED = /#\s*(noqa|nosec)\b|\/\/\s*NOSONAR\b|lintsure-ignore/;
|
|
119
|
+
const PLACEHOLDER = /test|fake|dummy|example|sample|placeholder|sanitized|mock|xxx|changeme|localhost|["'](password|pass|secret|elastic|admin)["']/i;
|
|
120
|
+
/** The JSON object key that opens the block a line sits in, e.g. "peerDependencies". Pure. */
|
|
121
|
+
export function enclosingKey(lines, i) {
|
|
122
|
+
let depth = 0;
|
|
123
|
+
for (let j = i - 1; j >= 0; j--) {
|
|
124
|
+
const l = lines[j];
|
|
125
|
+
depth += (l.match(/\}/g) ?? []).length - (l.match(/\{/g) ?? []).length;
|
|
126
|
+
if (depth < 0)
|
|
127
|
+
return l.match(/"([^"]+)"\s*:\s*\{/)?.[1] ?? "";
|
|
128
|
+
}
|
|
129
|
+
return "";
|
|
130
|
+
}
|
|
131
|
+
const HASH_COMMENTS = new Set([".py", ".rb", ".sh", ".yml", ".yaml", ".toml", ".env"]);
|
|
132
|
+
/** Marks lines that are only a comment or sit inside a block comment or Python docstring. Pure. */
|
|
133
|
+
export function commentLines(lines, ext) {
|
|
134
|
+
const hash = HASH_COMMENTS.has(ext), py = ext === ".py";
|
|
135
|
+
let block = false, doc = false;
|
|
136
|
+
return lines.map((raw) => {
|
|
137
|
+
const t = raw.trim();
|
|
138
|
+
if (block) {
|
|
139
|
+
if (t.includes("*/"))
|
|
140
|
+
block = false;
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
if (doc) {
|
|
144
|
+
if (/"""|'''/.test(t))
|
|
145
|
+
doc = false;
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
if (py && /^[rbuf]*("""|''')/i.test(t)) {
|
|
149
|
+
const q = t.match(/"""|'''/)[0];
|
|
150
|
+
if (t.split(q).length - 1 === 1)
|
|
151
|
+
doc = true;
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
if (t.startsWith("/*")) {
|
|
155
|
+
if (!t.includes("*/"))
|
|
156
|
+
block = true;
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
return t.startsWith("//") || t.startsWith("*") || t.startsWith("<!--") || (hash && t.startsWith("#"));
|
|
160
|
+
});
|
|
161
|
+
}
|
|
115
162
|
export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
116
163
|
const active = rules.filter((r) => r.controls.some((c) => frameworks.includes(c.framework)));
|
|
117
164
|
const findings = [];
|
|
@@ -120,7 +167,8 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
120
167
|
const { ignore } = await readConfig(root);
|
|
121
168
|
for (const abs of await listFiles(root, ignore)) {
|
|
122
169
|
const ext = extname(abs) || (abs.endsWith(".env") ? ".env" : "");
|
|
123
|
-
const
|
|
170
|
+
const name = basename(abs);
|
|
171
|
+
const relevant = active.filter((r) => r.extensions.includes(ext) && (!r.fileName || r.fileName.test(name)));
|
|
124
172
|
if (!relevant.length)
|
|
125
173
|
continue;
|
|
126
174
|
const buf = await readFile(abs);
|
|
@@ -142,10 +190,29 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
142
190
|
fingerprint: fingerprint(r.id, file, lines[line - 1] ?? ""),
|
|
143
191
|
});
|
|
144
192
|
};
|
|
193
|
+
// Tests and fixtures are full of fake tokens and planted examples: only secret rules look at them.
|
|
194
|
+
const inTests = TEST_PATH.test(file);
|
|
195
|
+
const comment = commentLines(lines, ext);
|
|
145
196
|
for (const r of relevant) {
|
|
197
|
+
if (inTests && !SECRET_RULES.has(r.id))
|
|
198
|
+
continue;
|
|
199
|
+
// Comments describe code, they don't run. A real secret pasted into a comment still counts.
|
|
200
|
+
const skip = SECRET_RULES.has(r.id) ? null : comment;
|
|
146
201
|
if (r.test)
|
|
147
|
-
lines.forEach((text, i) => {
|
|
148
|
-
|
|
202
|
+
lines.forEach((text, i) => {
|
|
203
|
+
if (skip?.[i])
|
|
204
|
+
return;
|
|
205
|
+
const hit = r.test(text);
|
|
206
|
+
if (!hit || (r.unlessNear && lines.slice(Math.max(0, i - 8), i + 4).some((l) => r.unlessNear.test(l))))
|
|
207
|
+
return;
|
|
208
|
+
if (r.unlessInKey && r.unlessInKey.test(enclosingKey(lines, i)))
|
|
209
|
+
return;
|
|
210
|
+
if (inTests && PLACEHOLDER.test(text))
|
|
211
|
+
return; // password="test_password", token="xoxb-test-..."
|
|
212
|
+
if (REVIEWED.test(text))
|
|
213
|
+
return; // someone already looked at this line and marked it
|
|
214
|
+
add(r, i + 1, hit === "partial" ? "partial" : r.status);
|
|
215
|
+
});
|
|
149
216
|
if (r.fileTest)
|
|
150
217
|
for (const n of r.fileTest(lines))
|
|
151
218
|
add(r, n);
|
|
@@ -2,8 +2,9 @@ import { euAiAct } from "./eu-ai-act.js";
|
|
|
2
2
|
import { gdpr } from "./gdpr.js";
|
|
3
3
|
import { iso27001 } from "./iso-27001.js";
|
|
4
4
|
import { soc2 } from "./soc2.js";
|
|
5
|
+
import { owaspTop10 } from "./owasp-top10.js";
|
|
5
6
|
export * from "./types.js";
|
|
6
|
-
export const knowledge = [euAiAct, gdpr, soc2, iso27001];
|
|
7
|
+
export const knowledge = [euAiAct, gdpr, soc2, iso27001, owaspTop10];
|
|
7
8
|
export const getKnowledge = (id) => knowledge.find((k) => k.id === id);
|
|
8
9
|
/** Classifier: suggest frameworks with a reason. The user confirms; nothing is auto-applied. */
|
|
9
10
|
export function classify(p) {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Own-words summary of the OWASP Top 10:2025. The OWASP text is licensed CC BY-SA 4.0: we reference
|
|
2
|
+
// category ids, names and CWE numbers only, and describe each category in our own words.
|
|
3
|
+
// Not affiliated with or endorsed by the OWASP Foundation. OWASP is a trademark of the OWASP Foundation.
|
|
4
|
+
export const owaspTop10 = {
|
|
5
|
+
id: "owasp-top10",
|
|
6
|
+
name: "OWASP Top 10:2025",
|
|
7
|
+
kind: "standard",
|
|
8
|
+
summary: "The OWASP Top 10 is a widely used awareness list of the ten most serious kinds of web application security risk, built from real test data and a community survey. It isn't a law or a certification, but customers, security questionnaires and many other standards point to it. The 2025 edition adds software supply chain failures and the mishandling of errors.",
|
|
9
|
+
whoItAppliesTo: "Any team building a web application or API. It's voluntary, but often expected by business customers and referenced in security reviews.",
|
|
10
|
+
applies(p) {
|
|
11
|
+
if (p.b2bCustomers)
|
|
12
|
+
return "Business customers and security questionnaires often ask how you handle the OWASP Top 10.";
|
|
13
|
+
if (p.personalData)
|
|
14
|
+
return "You handle personal data in a web app, so the common web security risks apply.";
|
|
15
|
+
return null;
|
|
16
|
+
},
|
|
17
|
+
obligations: [
|
|
18
|
+
{ ref: "A01:2025", title: "Broken Access Control", inCode: "partly",
|
|
19
|
+
rules: ["path.user-input", "redirect.open", "ssrf.user-url", "csrf.disabled", "fs.world-writable", "cors.any-origin", "cookie.trusted-role"],
|
|
20
|
+
plain: "People must only reach the data and actions meant for them. This covers file paths, redirects, requests your server makes on a user's behalf (SSRF), forged requests from other sites, and permissions kept where users can change them.",
|
|
21
|
+
evidence: "A list of roles and what each may do, and tests showing one user can't read or change another user's data." },
|
|
22
|
+
{ ref: "A01:2025 (ownership checks)", title: "Every record is checked against the signed-in user", inCode: "no",
|
|
23
|
+
plain: "Whether each endpoint checks that the record belongs to the person asking (often called IDOR). A line-by-line code check can't tell; it needs design review and testing with two accounts.",
|
|
24
|
+
evidence: "Access control tests per role, or a penetration test report." },
|
|
25
|
+
{ ref: "A02:2025", title: "Security Misconfiguration", inCode: "partly",
|
|
26
|
+
rules: ["config.debug-on", "config.allowed-hosts-any", "config.default-secret-key", "xml.external-entities", "cors.any-origin", "session.cookie-insecure", "error.stack-to-client"],
|
|
27
|
+
plain: "Safe settings by default: debug off, real host names, strong secret keys, cookies marked secure, XML parsers that don't load outside files, and errors that don't reveal internals.",
|
|
28
|
+
evidence: "Production configuration and a hardening checklist." },
|
|
29
|
+
{ ref: "A02:2025 (deployed settings)", title: "Server, cloud and header configuration in production", inCode: "no",
|
|
30
|
+
plain: "What is actually running: server and cloud settings, open ports, default accounts, security headers on real responses. These need a scan of the deployed system.",
|
|
31
|
+
evidence: "Infrastructure configuration, a header scan and a cloud configuration review." },
|
|
32
|
+
{ ref: "A03:2025", title: "Software Supply Chain Failures", inCode: "partly",
|
|
33
|
+
rules: ["deps.unpinned-version", "deps.install-script", "ci.action-unpinned", "ci.prt-checkout-head"],
|
|
34
|
+
plain: "The code you didn't write: dependencies, build tools and CI. Versions should be pinned, install scripts shouldn't fetch code, CI actions should be pinned, and untrusted pull requests must not run with your secrets.",
|
|
35
|
+
evidence: "Lockfiles, CI workflow files and the dependency update process." },
|
|
36
|
+
{ ref: "A03:2025 (known vulnerabilities)", title: "Dependencies with known vulnerabilities", inCode: "no",
|
|
37
|
+
plain: "Whether any dependency version has a published vulnerability, and whether it's maintained. This needs vulnerability advisory data, which Lintsure doesn't download, so use a dependency scanner alongside it.",
|
|
38
|
+
evidence: "Dependency scanner results (for example npm audit, OSV-Scanner or Dependabot) and how alerts are handled." },
|
|
39
|
+
{ ref: "A04:2025", title: "Cryptographic Failures", inCode: "yes",
|
|
40
|
+
rules: ["crypto.weak-password-hash", "crypto.weak-random-token", "crypto.weak-cipher", "jwt.unverified", "transport.plain-http", "transport.tls-verify-off", "secret.in-source"],
|
|
41
|
+
plain: "Protect data with sound cryptography: HTTPS everywhere, certificate checks on, strong password hashing, modern ciphers, unpredictable tokens, signed tokens that are verified, and no keys in code.",
|
|
42
|
+
evidence: "Where data is encrypted in transit and at rest, and how keys are stored and rotated." },
|
|
43
|
+
{ ref: "A04:2025 (key management)", title: "Key management and encryption at rest", inCode: "no",
|
|
44
|
+
plain: "How encryption keys are created, stored, rotated and retired, and whether databases and backups are encrypted. These live in your infrastructure, not your code.",
|
|
45
|
+
evidence: "Key management procedure and storage encryption settings." },
|
|
46
|
+
{ ref: "A05:2025", title: "Injection", inCode: "yes",
|
|
47
|
+
rules: ["sql.string-built", "cmd.shell-built", "code.eval", "xss.raw-html", "template.user-string", "nosql.operator-input"],
|
|
48
|
+
plain: "Keep data and code apart, so input can't become part of a SQL query, a shell command, a template, HTML on the page or code that gets run.",
|
|
49
|
+
evidence: "Use of parameterised queries, output escaping, and code review practice." },
|
|
50
|
+
{ ref: "A06:2025", title: "Insecure Design", inCode: "partly",
|
|
51
|
+
rules: ["upload.unrestricted", "mass-assignment", "pii.in-url"],
|
|
52
|
+
plain: "Security planned in from the start: limits on uploads, only the fields users may change, sensitive data kept out of URLs. Most of this category is about design, not individual lines.",
|
|
53
|
+
evidence: "Design notes for sensitive features." },
|
|
54
|
+
{ ref: "A06:2025 (threat modelling)", title: "Threat modelling and abuse cases", inCode: "no",
|
|
55
|
+
plain: "Thinking through how a feature could be misused before building it: rate limits, business rule abuse, trust boundaries. Code checks can't show whether this happened.",
|
|
56
|
+
evidence: "Threat models or security design reviews for key features." },
|
|
57
|
+
{ ref: "A07:2025", title: "Authentication Failures", inCode: "partly",
|
|
58
|
+
rules: ["auth.hardcoded-password", "jwt.no-expiry", "jwt.unverified", "config.default-secret-key", "session.cookie-insecure", "secret.in-source", "transport.tls-verify-off"],
|
|
59
|
+
plain: "Logins and sessions that hold up: no passwords in code, strong secrets, tokens that expire and are verified, and session cookies protected from scripts and plain HTTP.",
|
|
60
|
+
evidence: "Login, session and token settings." },
|
|
61
|
+
{ ref: "A07:2025 (login protections)", title: "Brute-force protection, MFA and account recovery", inCode: "no",
|
|
62
|
+
plain: "Rate limiting and lockout on login, multi-factor authentication, and safe password reset flows. These need testing against the running app.",
|
|
63
|
+
evidence: "Login rate limit settings, MFA options, and password reset flow tests." },
|
|
64
|
+
{ ref: "A08:2025", title: "Software or Data Integrity Failures", inCode: "partly",
|
|
65
|
+
rules: ["deserialize.unsafe", "html.script-no-sri", "mass-assignment", "cookie.trusted-role", "ci.prt-checkout-head"],
|
|
66
|
+
plain: "Don't trust code or data you haven't checked: no unsafe deserialisation, integrity checks on third-party scripts, and no trust in values users can change.",
|
|
67
|
+
evidence: "How third-party scripts are loaded and how incoming data is parsed." },
|
|
68
|
+
{ ref: "A08:2025 (signed releases)", title: "Signed builds and updates", inCode: "no",
|
|
69
|
+
plain: "Whether builds, packages and updates are signed and verified from source to release.",
|
|
70
|
+
evidence: "Build signing and release verification steps." },
|
|
71
|
+
{ ref: "A09:2025", title: "Security Logging and Alerting Failures", inCode: "partly",
|
|
72
|
+
rules: ["log.secret", "log.injection", "pii.logged", "ai.call-not-logged"],
|
|
73
|
+
plain: "Logs that help instead of hurt: no secrets or personal data in them, no way to forge entries, and records of important events.",
|
|
74
|
+
evidence: "What is logged for logins, permission changes and admin actions." },
|
|
75
|
+
{ ref: "A09:2025 (alerting)", title: "Monitoring, alerting and incident response", inCode: "no",
|
|
76
|
+
plain: "Whether anyone is alerted when something suspicious happens, how long logs are kept, and how incidents are handled.",
|
|
77
|
+
evidence: "Alert rules, log retention settings and the incident response plan." },
|
|
78
|
+
{ ref: "A10:2025", title: "Mishandling of Exceptional Conditions", inCode: "partly",
|
|
79
|
+
rules: ["error.empty-catch", "error.stack-to-client", "config.debug-on"],
|
|
80
|
+
plain: "Errors handled on purpose: none silently ignored, none shown to users in detail, and failures that leave the system closed rather than open.",
|
|
81
|
+
evidence: "Error handling conventions and how failures are reported." },
|
|
82
|
+
{ ref: "A10:2025 (behaviour under failure)", title: "Safe behaviour when things fail", inCode: "no",
|
|
83
|
+
plain: "How the app behaves when a database, payment provider or other dependency is slow or down, and whether access checks fail closed. This needs testing under failure.",
|
|
84
|
+
evidence: "Failure and timeout tests." },
|
|
85
|
+
],
|
|
86
|
+
watchOut: [
|
|
87
|
+
"The Top 10 is an awareness list, not a complete standard. For detailed testing, OWASP publishes the Application Security Verification Standard (ASVS) and the Web Security Testing Guide (WSTG).",
|
|
88
|
+
"Many risks need a running app to test: access between users, login protections and deployed configuration. Code checks cover only part of each category.",
|
|
89
|
+
"Lintsure reads one line or one file at a time. Data passed through helpers in other files won't be followed, so some problems will be missed.",
|
|
90
|
+
"Saying an app is 'OWASP compliant' isn't meaningful. Describe what was checked and what wasn't.",
|
|
91
|
+
],
|
|
92
|
+
checkedOn: "2026-11-09",
|
|
93
|
+
};
|
|
@@ -1,2 +1,6 @@
|
|
|
1
1
|
import type { Rule } from "../types.js";
|
|
2
2
|
export declare const rules: Rule[];
|
|
3
|
+
/** The first AI call in a file with no log or save between 10 lines above and 30 below (one finding per file). Pure. */
|
|
4
|
+
export declare const unloggedAiCalls: (lines: string[]) => number[];
|
|
5
|
+
/** AI calls in a file that names an image, voice or video model. Pure. */
|
|
6
|
+
export declare const mediaModelCalls: (lines: string[]) => number[];
|
package/dist/src/rules/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { owaspForExisting, owaspRules } from "./owasp.js";
|
|
1
2
|
const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
|
|
2
3
|
// Beta: mapped by us, awaiting review by a qualified compliance professional.
|
|
3
4
|
const DRAFT = { mappedBy: "beta", reviewedAt: "pending" };
|
|
@@ -126,7 +127,7 @@ export const rules = [
|
|
|
126
127
|
fix: "Remove the override and trust a proper certificate. For self-signed certs in tests, scope it to the test only.",
|
|
127
128
|
note: "With checks off, anyone on the network path can read or change the traffic.",
|
|
128
129
|
extensions: [...CODE, ".env"],
|
|
129
|
-
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|CERT_NONE/.test(l),
|
|
130
|
+
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
|
|
130
131
|
...DRAFT,
|
|
131
132
|
},
|
|
132
133
|
{
|
|
@@ -198,7 +199,29 @@ export const rules = [
|
|
|
198
199
|
// --- EU AI Act -------------------------------------------------------------
|
|
199
200
|
// Code can show *signals* for the AI Act, not the legal risk tier itself. These rules
|
|
200
201
|
// flag what an auditor would ask about; the Classifier and the user decide the tier.
|
|
201
|
-
|
|
202
|
+
// How apps call models in practice (field test, 18 repos): SDK clients under any name, Gemini's generateContent,
|
|
203
|
+
// the Vercel AI SDK, LangChain chains, and plain fetch calls to the provider's API. supabase.functions.invoke is not AI.
|
|
204
|
+
const AI_CALL = new RegExp([
|
|
205
|
+
/\b(openai|anthropic|client)\.(chat\.completions|responses|messages|completions)\.create\s*\(/.source,
|
|
206
|
+
/\b\w+\.chat\.completions\.create\s*\(/.source,
|
|
207
|
+
/\.generateContent(Stream)?\s*\(/.source,
|
|
208
|
+
/\b(generateText|streamText|generateObject|streamObject)\s*\(/.source,
|
|
209
|
+
/\b(model|clf|classifier|pipeline)\.(predict|predict_proba|invoke|generate)\s*\(/.source,
|
|
210
|
+
/\b(chain|llm|chatModel|agent|runnable)\w*\.(invoke|stream|batch)\s*\(/.source,
|
|
211
|
+
// A provider URL counts only inside a request call, not where it's stored in a constant.
|
|
212
|
+
/\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,
|
|
213
|
+
].join("|"), "i");
|
|
214
|
+
const NOT_AI = /\bfunctions\.invoke\s*\(/;
|
|
215
|
+
const isAiCall = (l) => AI_CALL.test(l) && !NOT_AI.test(l);
|
|
216
|
+
/** The first AI call in a file with no log or save between 10 lines above and 30 below (one finding per file). Pure. */
|
|
217
|
+
export const unloggedAiCalls = (lines) => {
|
|
218
|
+
const i = lines.findIndex((l, i) => isAiCall(l) && !lines.slice(Math.max(0, i - 10), i + 31).some((x) => LOGGED.test(x)));
|
|
219
|
+
return i < 0 ? [] : [i + 1];
|
|
220
|
+
};
|
|
221
|
+
// Image, voice and video models. "flux" alone is left out: Deepgram uses it for speech-to-text.
|
|
222
|
+
const MEDIA_MODEL = /["'`](dall-e-\d|gpt-image-[\w.]+|imagen-[\w.-]+|gemini-[\w.-]*-image[\w.-]*|tts-1[\w-]*|gpt-4o[\w-]*-tts|veo-[\w.-]+|sora-[\w.-]+|eleven_[\w]+|black-forest-labs\/flux[\w./-]*|stable-diffusion[\w./-]*)["'`]/i;
|
|
223
|
+
/** AI calls in a file that names an image, voice or video model. Pure. */
|
|
224
|
+
export const mediaModelCalls = (lines) => lines.some((l) => MEDIA_MODEL.test(l)) ? lines.flatMap((l, i) => (isAiCall(l) ? [i + 1] : [])) : [];
|
|
202
225
|
const DECISION = /\b(approv|reject|deny|denied|declin|eligib|hire|hiring|shortlist|credit|loan|underwrit|admit|admission|ban|suspend)\w*/i;
|
|
203
226
|
const LOGGED = /\b(logger|log|logging|audit|auditLog|console)\.\w+\s*\(|\binsert\w*\s*\(|\.save\s*\(/;
|
|
204
227
|
rules.push({
|
|
@@ -217,16 +240,16 @@ rules.push({
|
|
|
217
240
|
...DRAFT,
|
|
218
241
|
}, {
|
|
219
242
|
id: "ai.call-not-logged",
|
|
220
|
-
title: "AI call with no record kept
|
|
243
|
+
title: "AI call with no record kept near it",
|
|
221
244
|
status: "partial", severity: "medium",
|
|
222
245
|
controls: [
|
|
223
246
|
{ framework: "eu-ai-act", id: "Art. 12", title: "Record-keeping" },
|
|
224
247
|
{ framework: "soc2", id: "CC7.2", title: "Monitoring of system components" },
|
|
225
248
|
],
|
|
226
249
|
fix: "Log each AI call: time, model and version, input reference and output, without raw personal data.",
|
|
227
|
-
note: "High-risk systems must keep logs that let you trace what the AI did. Marked Partial: logging may happen in another file.",
|
|
250
|
+
note: "High-risk systems must keep logs that let you trace what the AI did. Marked Partial: logging may happen in a wrapper or another file.",
|
|
228
251
|
extensions: CODE,
|
|
229
|
-
fileTest:
|
|
252
|
+
fileTest: unloggedAiCalls,
|
|
230
253
|
...DRAFT,
|
|
231
254
|
}, {
|
|
232
255
|
id: "ai.hides-being-ai",
|
|
@@ -247,6 +270,8 @@ rules.push({
|
|
|
247
270
|
note: "Marked Partial: you may already add marking after this call. Confirm it does.",
|
|
248
271
|
extensions: CODE,
|
|
249
272
|
test: (l) => /\bimages\.(generate|edit)\s*\(|\baudio\.speech\.create\s*\(|\b(textToSpeech|text_to_speech|generateImage|generate_image|generateVideo|generate_video)\s*\(|\b(StableDiffusion\w*|DiffusionPipeline)\b/.test(l),
|
|
273
|
+
// Also: a generic AI call (e.g. generateContent) in a file that names an image, voice or video model.
|
|
274
|
+
fileTest: mediaModelCalls,
|
|
250
275
|
...DRAFT,
|
|
251
276
|
}, {
|
|
252
277
|
id: "ai.emotion-or-biometric",
|
|
@@ -263,3 +288,7 @@ rules.push({
|
|
|
263
288
|
test: (l) => /\b(detect|recogni[sz]e|analy[sz]e|infer|predict)\w*_?(emotion|sentiment_from_face|facial_expression)|\bemotion(s)?\s*[:=]\s*\w*\.(detect|analy)|\bDeepFace\.analyze\s*\(|\bdetect_faces?\b.*\bemotion|\b(face_recognition|FaceAttributes|DetectFaces)\b/i.test(l),
|
|
264
289
|
...DRAFT,
|
|
265
290
|
});
|
|
291
|
+
// OWASP Top 10:2025: map the rules above, then add the OWASP rules.
|
|
292
|
+
for (const r of rules)
|
|
293
|
+
r.controls.push(...(owaspForExisting[r.id] ?? []));
|
|
294
|
+
rules.push(...owaspRules);
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
|
|
2
|
+
const MARKUP = [...CODE, ".html", ".vue", ".svelte", ".astro", ".jinja", ".j2"];
|
|
3
|
+
const YAML = [".yml", ".yaml"];
|
|
4
|
+
const DRAFT = { mappedBy: "beta", reviewedAt: "pending" };
|
|
5
|
+
const A = (n, title) => ({ framework: "owasp-top10", id: `A${n}:2025`, title });
|
|
6
|
+
const A01 = A("01", "Broken Access Control"), A02 = A("02", "Security Misconfiguration"), A03 = A("03", "Software Supply Chain Failures"), A04 = A("04", "Cryptographic Failures"), A05 = A("05", "Injection"), A06 = A("06", "Insecure Design"), A07 = A("07", "Authentication Failures"), A08 = A("08", "Software or Data Integrity Failures"), A09 = A("09", "Security Logging and Alerting Failures"), A10 = A("10", "Mishandling of Exceptional Conditions");
|
|
7
|
+
// Request data on the same line. Without it a match is Partial: the value may be safe text from your own code.
|
|
8
|
+
const USER_INPUT = /\b(req\.(body|query|params|headers|cookies)|request\.(args|form|json|data|GET|POST|query_params|files)|ctx\.(query|request)|event\.(body|queryStringParameters)|searchParams\.get)\b/;
|
|
9
|
+
const byInput = (l) => (USER_INPUT.test(l) ? true : "partial");
|
|
10
|
+
const LOG_CALL = /\b(console\.(log|info|warn|error|debug)|logger\.\w+|log\.(info|warn|error|debug)|logging\.\w+)\s*\(/;
|
|
11
|
+
function logArgs(l) {
|
|
12
|
+
const m = LOG_CALL.exec(l);
|
|
13
|
+
if (!m)
|
|
14
|
+
return null;
|
|
15
|
+
let depth = 0;
|
|
16
|
+
const i = m.index + m[0].length - 1;
|
|
17
|
+
for (let j = i; j < l.length; j++) {
|
|
18
|
+
if (l[j] === "(")
|
|
19
|
+
depth++;
|
|
20
|
+
else if (l[j] === ")" && --depth === 0)
|
|
21
|
+
return l.slice(i + 1, j);
|
|
22
|
+
}
|
|
23
|
+
return l.slice(i + 1);
|
|
24
|
+
}
|
|
25
|
+
const stripStrings = (l) => l.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
|
|
26
|
+
const rule = (r) => ({ ...r, ...DRAFT });
|
|
27
|
+
export const owaspRules = [
|
|
28
|
+
// A01 Broken Access Control
|
|
29
|
+
rule({ id: "path.user-input", title: "File path built from request data", status: "gap", severity: "high", controls: [A01],
|
|
30
|
+
fix: "Don't pass request values into file paths. Map the request to a known file name, or use path.basename and check the result stays inside the allowed folder.",
|
|
31
|
+
note: "A path like ../../etc/passwd lets someone read or overwrite files outside the folder you meant (path traversal, CWE-22).", extensions: CODE,
|
|
32
|
+
test: (l) => /\b(fs\.(readFile|readFileSync|createReadStream|writeFile|writeFileSync|unlink|unlinkSync)|res\.(sendFile|download)|send_file|send_from_directory|open)\s*\(/.test(l) && USER_INPUT.test(l) }),
|
|
33
|
+
rule({ id: "redirect.open", title: "Redirect to a URL taken from the request", status: "gap", severity: "medium", controls: [A01],
|
|
34
|
+
fix: "Redirect only to paths on your own site, or check the target against a list of allowed hosts.",
|
|
35
|
+
note: "Attackers send people a link to your site that bounces them to a phishing page (open redirect, CWE-601).", extensions: CODE,
|
|
36
|
+
test: (l) => /\b(res\.redirect|redirect|HttpResponseRedirect|RedirectResponse)\s*\(\s*(req\.(query|body|params)|request\.(args|GET|query_params|form))/.test(l) }),
|
|
37
|
+
rule({ id: "ssrf.user-url", title: "Server fetches a URL taken from the request", status: "gap", severity: "high", controls: [A01],
|
|
38
|
+
fix: "Don't let users choose the full URL your server calls. Allow only known hosts, and block internal addresses such as 169.254.169.254 and localhost.",
|
|
39
|
+
note: "Your server can be made to call internal services or cloud metadata on an attacker's behalf (server-side request forgery, CWE-918).", extensions: CODE,
|
|
40
|
+
test: (l) => /\b(fetch|axios(\.(get|post|request))?|got|requests\.(get|post|request)|httpx\.(get|post)|urlopen)\s*\(\s*(req\.(body|query|params)|request\.(args|json|form|GET|data))/.test(l) }),
|
|
41
|
+
rule({ id: "csrf.disabled", title: "CSRF protection switched off", status: "partial", severity: "medium", controls: [A01],
|
|
42
|
+
fix: "Keep CSRF protection on for routes that use cookies. Turning it off is only safe for APIs that authenticate with a token header, not cookies.",
|
|
43
|
+
note: "Another site can make a logged-in user's browser submit forms to your app (cross-site request forgery, CWE-352).", extensions: CODE,
|
|
44
|
+
test: (l) => /@csrf_exempt\b|WTF_CSRF_ENABLED\s*=\s*False|\bcsrf\s*:\s*false\b|csrf_protect\s*=\s*False/.test(l) }),
|
|
45
|
+
rule({ id: "fs.world-writable", title: "File made readable and writable by everyone", status: "gap", severity: "medium", controls: [A01],
|
|
46
|
+
fix: "Use the narrowest permissions that work, for example 0o600 for secrets and 0o644 or 0o755 for public files.",
|
|
47
|
+
note: "Any user or process on the machine can change the file (incorrect permissions, CWE-732).", extensions: CODE,
|
|
48
|
+
test: (l) => /\bchmod(Sync)?\s*\([^)]*\b0o?777\b/.test(l) }),
|
|
49
|
+
// A02 Security Misconfiguration
|
|
50
|
+
rule({ id: "config.allowed-hosts-any", title: "Django accepts any host name", status: "gap", severity: "medium", controls: [A02],
|
|
51
|
+
fix: "List your real domains in ALLOWED_HOSTS, ideally from an environment variable per environment.",
|
|
52
|
+
note: "Any Host header is accepted, which enables host header attacks such as poisoned password reset links.", extensions: CODE,
|
|
53
|
+
test: (l) => /\bALLOWED_HOSTS\s*=\s*\[\s*["']\*["']/.test(l) }),
|
|
54
|
+
rule({ id: "config.default-secret-key", title: "Default or placeholder secret key", status: "gap", severity: "high", controls: [A02, A07],
|
|
55
|
+
fix: "Generate a long random secret per environment and load it from an environment variable or secret manager.",
|
|
56
|
+
note: "With a known secret key, attackers can forge sessions, cookies or signed tokens (CWE-1394).", extensions: [...CODE, ".env"],
|
|
57
|
+
// The value must be a quoted literal, or an env-style KEY=value line: `self.secret = secret` is a variable.
|
|
58
|
+
test: (l) => /\b(SECRET_KEY|JWT_SECRET|SESSION_SECRET|secret)\s*[:=]\s*["'](django-insecure-|changeme|change-me|secret\b|mysecret|keyboard cat|dev-secret|supersecret)/i.test(l)
|
|
59
|
+
|| /^\s*(SECRET_KEY|JWT_SECRET|SESSION_SECRET)\s*=\s*(django-insecure-|changeme|change-me|secret\b|mysecret|dev-secret|supersecret)/i.test(l) }),
|
|
60
|
+
rule({ id: "xml.external-entities", title: "XML parser may load external entities", status: "partial", severity: "high", controls: [A02],
|
|
61
|
+
fix: "Use defusedxml in Python, or turn off entity resolution and DTD loading in your parser.",
|
|
62
|
+
note: "A crafted XML file can read local files or call internal URLs (XML external entities, CWE-611).", extensions: CODE,
|
|
63
|
+
test: (l) => /resolve_entities\s*=\s*True|\bnoent\s*:\s*true|\bxml\.(etree\.ElementTree|dom\.minidom|sax)\b[^\n]*\b(parse|parseString|fromstring)\s*\(/.test(l) }),
|
|
64
|
+
// A03 Software Supply Chain Failures
|
|
65
|
+
rule({ id: "deps.unpinned-version", title: "Dependency with no version limit", status: "gap", severity: "medium", controls: [A03],
|
|
66
|
+
fix: "Pin a version or a range in package.json and commit the lockfile, so every install gets the code you tested.",
|
|
67
|
+
note: "\"*\" or \"latest\" installs whatever is published next, including a compromised release (CWE-1357).", extensions: [".json"], fileName: /^package\.json$/, unlessInKey: /^peerDependencies/, // lockfiles and peer deps use "*" on purpose
|
|
68
|
+
test: (l) => /^\s*"(@?[\w.-]+\/)?[\w.-]+"\s*:\s*"(\*|latest|x)"\s*,?\s*$/.test(l) }),
|
|
69
|
+
rule({ id: "deps.install-script", title: "Install script downloads code", status: "partial", severity: "medium", controls: [A03],
|
|
70
|
+
fix: "Avoid downloading and running code in preinstall or postinstall. Vendor the file or document a manual step.",
|
|
71
|
+
note: "Code fetched at install time isn't pinned or reviewed and runs with the installer's permissions (CWE-829).", extensions: [".json"], fileName: /^package\.json$/,
|
|
72
|
+
test: (l) => /"(pre|post)?install"\s*:\s*"[^"]*\b(curl|wget|Invoke-WebRequest)\b/.test(l) }),
|
|
73
|
+
rule({ id: "ci.action-unpinned", title: "Third-party GitHub Action not pinned to a commit", status: "partial", severity: "medium", controls: [A03],
|
|
74
|
+
fix: "Pin third-party actions to a full commit SHA, with the version as a comment, for example uses: owner/action@<40-character sha> # v2.",
|
|
75
|
+
note: "A tag like @v1 can be moved by the action's owner, or by whoever takes over their account (CWE-829).", extensions: YAML,
|
|
76
|
+
test: (l) => /^\s*-?\s*uses:\s*["']?(?!actions\/|github\/|\.\/|docker:\/\/)[\w.-]+\/[\w./-]+@(?![0-9a-f]{40}\b)[\w.-]+/.test(l) }),
|
|
77
|
+
rule({ id: "ci.prt-checkout-head", title: "pull_request_target workflow checks out untrusted code", status: "gap", severity: "high", controls: [A03, A08],
|
|
78
|
+
fix: "Use the pull_request trigger for workflows that build or run code from a pull request. If you need pull_request_target, never check out the pull request's code in it.",
|
|
79
|
+
note: "pull_request_target runs with your repository's secrets; checking out the contributor's code lets a pull request run with them (CWE-829).", extensions: YAML,
|
|
80
|
+
// A job that only runs once the PR is merged checks out code that is already on the base branch.
|
|
81
|
+
fileTest: (lines) => lines.some((l) => /\bpull_request_target\b/.test(l)) && !lines.some((l) => /pull_request\.merged\s*==\s*true/.test(l))
|
|
82
|
+
? lines.flatMap((l, i) => (/github\.event\.pull_request\.head\.(sha|ref)|refs\/pull\/.*\/(head|merge)/.test(l) ? [i + 1] : [])) : [] }),
|
|
83
|
+
// A04 Cryptographic Failures
|
|
84
|
+
rule({ id: "crypto.weak-random-token", title: "Predictable random numbers used for a secret", status: "gap", severity: "high", controls: [A04],
|
|
85
|
+
fix: "Use crypto.randomBytes or crypto.randomUUID in Node, or the secrets module in Python, for tokens, codes and IDs people shouldn't guess.",
|
|
86
|
+
note: "Math.random and Python's random module are predictable; tokens made with them can be guessed (CWE-338).", extensions: CODE,
|
|
87
|
+
test: (l) => /\bMath\.random\(\)|\brandom\.(random|randint|choice|choices|getrandbits)\(/.test(l) && /(token|secret|password|passwd|otp|nonce|session|api_?key|reset|invite|verification|code\b)/i.test(l) }),
|
|
88
|
+
rule({ id: "crypto.weak-cipher", title: "Weak or broken encryption", status: "gap", severity: "high", controls: [A04],
|
|
89
|
+
fix: "Use AES-256-GCM or ChaCha20-Poly1305 with a random nonce, through a maintained library. Replace createCipher with createCipheriv.",
|
|
90
|
+
note: "DES, RC4 and ECB mode can be broken or leak patterns in the data; createCipher derives a weak key and IV (CWE-327).", extensions: CODE,
|
|
91
|
+
test: (l) => /\bcreateCipher\s*\(|\bMODE_ECB\b|["'](des|des-ede3?|des-ede3-cbc|rc4|aes-\d{3}-ecb)["']|\b(DES3?|ARC4|Blowfish)\.new\s*\(/i.test(l) }),
|
|
92
|
+
rule({ id: "jwt.unverified", title: "JWT accepted without checking its signature", status: "gap", severity: "high", controls: [A04, A07],
|
|
93
|
+
fix: "Verify tokens with jwt.verify (Node) or jwt.decode with a key and an explicit algorithms list (Python). Never allow the 'none' algorithm.",
|
|
94
|
+
note: "Without signature checks anyone can write their own token and claim to be any user (CWE-347).", extensions: CODE,
|
|
95
|
+
test: (l) => {
|
|
96
|
+
if (/verify_signature["']?\s*:\s*False|\bverify\s*=\s*False|algorithms\s*[:=]\s*\[\s*["']none["']/i.test(l) && /jwt/i.test(l))
|
|
97
|
+
return true;
|
|
98
|
+
return /\bjwt\.decode\(\s*[\w.]+\s*\)/.test(l) ? "partial" : false; // Node jwt.decode reads a token without verifying it
|
|
99
|
+
} }),
|
|
100
|
+
// A05 Injection
|
|
101
|
+
rule({ id: "cmd.shell-built", title: "Shell command built from strings", status: "gap", severity: "high", controls: [A05],
|
|
102
|
+
fix: "Pass arguments as an array (execFile, spawn, subprocess.run([...])) instead of building a command string, and never use shell=True with outside input.",
|
|
103
|
+
note: "Characters like ; or $( ) in an inserted value run extra commands (OS command injection, CWE-78). Partial when the value may be fixed text from your own code.", extensions: CODE,
|
|
104
|
+
test: (l) => /\b(exec|execSync)\s*\(\s*(`[^`]*\$\{|["'][^"']*["']\s*\+)|\bsubprocess\.\w+\([^)]*shell\s*=\s*True|\bos\.(system|popen)\(\s*(f["']|["'][^"']*["']\s*[+%]|\w)/.test(l) ? byInput(l) : false }),
|
|
105
|
+
rule({ id: "code.eval", title: "Code run from a string", status: "gap", severity: "high", controls: [A05],
|
|
106
|
+
fix: "Avoid eval and new Function. Parse data with JSON.parse or a real parser, and map names to functions with a lookup table.",
|
|
107
|
+
note: "If any part of the string comes from outside, it runs as your code (code injection, CWE-94). Partial when the input isn't visible on the line.", extensions: CODE,
|
|
108
|
+
test: (l) => /\b(def|function|async)\s+eval\s*\(/.test(l) ? false // a method named eval is a definition, not a call
|
|
109
|
+
: /(^|[^.\w])eval\s*\(|\bnew Function\s*\(/.test(l) ? byInput(l) : false }),
|
|
110
|
+
rule({ id: "xss.raw-html", title: "HTML inserted without escaping", status: "partial", severity: "high", controls: [A05],
|
|
111
|
+
fix: "Set text with textContent, let your framework escape values, or sanitise with DOMPurify before inserting HTML.",
|
|
112
|
+
note: "If the HTML contains user input, attackers can run scripts in your users' browsers (cross-site scripting, CWE-79). Partial because fixed HTML from your own code is safe.", extensions: MARKUP,
|
|
113
|
+
test: (l) => /\.(innerHTML|outerHTML)\s*[+]?=|\bdocument\.write(ln)?\(|\bdangerouslySetInnerHTML\b|\bv-html=|\{@html\b|\|\s*safe\b|\bmark_safe\(|\bMarkup\(/.test(l) }),
|
|
114
|
+
rule({ id: "template.user-string", title: "Template built from request data", status: "gap", severity: "high", controls: [A05],
|
|
115
|
+
fix: "Render a fixed template file and pass user values as variables, never as part of the template text.",
|
|
116
|
+
note: "Template syntax in user input runs on your server (server-side template injection, CWE-94).", extensions: CODE,
|
|
117
|
+
test: (l) => /\brender_template_string\(\s*(request\.|f["'])|\bTemplate\(\s*request\./.test(l) }),
|
|
118
|
+
rule({ id: "nosql.operator-input", title: "Database query object taken straight from the request", status: "partial", severity: "high", controls: [A05],
|
|
119
|
+
fix: "Build the query from the specific fields you expect, and convert them to the expected types, so operators like $ne or $gt can't be injected.",
|
|
120
|
+
note: "A body such as {\"password\": {\"$ne\": null}} can match any record (NoSQL injection, CWE-943).", extensions: CODE,
|
|
121
|
+
test: (l) => /\.(find|findOne|updateOne|updateMany|deleteOne|deleteMany|countDocuments)\(\s*req\.(body|query)\s*\)|\$where\b/.test(l) }),
|
|
122
|
+
// A06 Insecure Design
|
|
123
|
+
rule({ id: "upload.unrestricted", title: "File upload with no type or size limit", status: "partial", severity: "medium", controls: [A06],
|
|
124
|
+
fix: "Set limits.fileSize and a fileFilter that allows only the types you need, store uploads outside the web root, and give them new names.",
|
|
125
|
+
note: "Unlimited uploads let people fill your disk or upload files that later run or are served as pages (CWE-434).", extensions: CODE,
|
|
126
|
+
test: (l) => /\bmulter\(\s*(\{[^}]*\})?\s*\)/.test(l) && !/fileFilter|limits/.test(l) }),
|
|
127
|
+
rule({ id: "mass-assignment", title: "Whole request body saved to a model", status: "partial", severity: "medium", controls: [A06, A08],
|
|
128
|
+
fix: "Copy only the fields a user may change, for example with a schema (zod, pydantic) that lists them.",
|
|
129
|
+
note: "Users can set fields you didn't expect, such as role or isAdmin (mass assignment, CWE-915).", extensions: CODE,
|
|
130
|
+
test: (l) => /\.(create|update|insert|build|insertOne|updateOne)\(\s*req\.body\s*[),]|\bObject\.assign\(\s*\w+\s*,\s*req\.body\s*\)|\(\s*\*\*request\.(json|form|data)\b/.test(l) }),
|
|
131
|
+
// A07 Authentication Failures
|
|
132
|
+
rule({ id: "auth.hardcoded-password", title: "Password written in the code", status: "partial", severity: "high", controls: [A07],
|
|
133
|
+
fix: "Load passwords from environment variables or a secret manager, and rotate any that were committed.",
|
|
134
|
+
note: "Anyone with the code has the password, and it can't be changed without a release (CWE-259, CWE-798).", extensions: CODE,
|
|
135
|
+
test: (l) => /\b(password|passwd|pwd|db_pass)\s*[:=]\s*["'][^"'\s]{4,}["']/i.test(l) && !/(example|placeholder|changeme|your[_-]|xxx|\*\*\*|<|process\.env|os\.environ|getenv|type\s*[:=]|label|autocomplete)/i.test(l) }),
|
|
136
|
+
rule({ id: "jwt.no-expiry", title: "JWT signed without an expiry", status: "partial", severity: "medium", controls: [A07],
|
|
137
|
+
fix: "Add expiresIn (Node) or an exp claim (Python), and keep access tokens short-lived.",
|
|
138
|
+
note: "A stolen token without an expiry works forever (insufficient session expiration, CWE-613). Partial because the expiry may be set in a payload built elsewhere.", extensions: CODE,
|
|
139
|
+
test: (l) => /\bjwt\.(sign|encode)\(/.test(l) && !/expiresIn|\bexp\b/.test(l), unlessNear: /expiresIn|["']exp["']|\bexp\s*[:=]/ }),
|
|
140
|
+
// A08 Software or Data Integrity Failures
|
|
141
|
+
rule({ id: "deserialize.unsafe", title: "Unsafe deserialisation", status: "gap", severity: "high", controls: [A08],
|
|
142
|
+
fix: "Use JSON for data from outside. In Python use yaml.safe_load, never pickle or marshal on untrusted data.",
|
|
143
|
+
note: "Deserialising untrusted data with these functions can run attacker code on your server (CWE-502).", extensions: CODE,
|
|
144
|
+
test: (l) => /\b(c?[Pp]ickle|dill)\.loads?\(|\byaml\.load\((?![^)]*Loader\s*=\s*(yaml\.)?C?SafeLoader)|\byaml\.unsafe_load\(|\bmarshal\.loads?\(|\bjsonpickle\.decode\(|\bshelve\.open\(|\bunserialize\(/.test(l) }),
|
|
145
|
+
rule({ id: "html.script-no-sri", title: "Third-party script loaded without an integrity check", status: "partial", severity: "medium", controls: [A08],
|
|
146
|
+
fix: "Add integrity and crossorigin attributes with the file's hash, or host the file yourself.",
|
|
147
|
+
note: "If the CDN or package is compromised, the changed script runs on your site (CWE-353, CWE-829).", extensions: MARKUP,
|
|
148
|
+
test: (l) => /<script\b[^>]*\bsrc=["']https?:\/\/(?!localhost|127\.0\.0\.1)[^"']+["'][^>]*>/i.test(l) && !/\bintegrity=/i.test(l) }),
|
|
149
|
+
rule({ id: "cookie.trusted-role", title: "Permissions read from a cookie", status: "partial", severity: "high", controls: [A08, A01],
|
|
150
|
+
fix: "Keep roles and permissions on the server, looked up from the authenticated user, not in a cookie the browser can change.",
|
|
151
|
+
note: "Users can edit their own cookies and give themselves admin rights (CWE-565).", extensions: CODE,
|
|
152
|
+
test: (l) => /\b(req\.cookies|request\.COOKIES|request\.cookies)(\.get\(\s*["']|\[\s*["']|\.)(role|isAdmin|is_admin|admin|permissions)\b/.test(l) }),
|
|
153
|
+
// A09 Security Logging and Alerting Failures
|
|
154
|
+
rule({ id: "log.secret", title: "Secret or token written to logs", status: "gap", severity: "high", controls: [A09],
|
|
155
|
+
fix: "Remove the value from the log call, or log only that it was present.",
|
|
156
|
+
note: "Logs are copied to many tools and people; a token in a log is a token anyone with log access can use (CWE-532).", extensions: CODE,
|
|
157
|
+
test: (l) => {
|
|
158
|
+
const a = logArgs(l);
|
|
159
|
+
if (a === null)
|
|
160
|
+
return false;
|
|
161
|
+
// Logging only whether a token exists (!!token) or a short prefix (token[:8], token.slice(0, 8)) is safe.
|
|
162
|
+
const safe = stripStrings(a).replace(/!!\s*[\w.?]+/g, "").replace(/[\w.?]+\s*\[\s*:\s*\d+\s*\]/g, "").replace(/[\w.?]+\.slice\(\s*0\s*,\s*\d+\s*\)/g, "");
|
|
163
|
+
return /\b(token|secret|authorization|api_?key|apiKey|bearer|access_token|refresh_token|private_?key|client_secret)\b/i.test(safe);
|
|
164
|
+
} }),
|
|
165
|
+
rule({ id: "log.injection", title: "Raw request data written to logs", status: "partial", severity: "low", controls: [A09],
|
|
166
|
+
fix: "Log specific, validated fields, and strip line breaks from user input before logging it.",
|
|
167
|
+
note: "Line breaks in user input can forge fake log entries and mislead an investigation (CWE-117).", extensions: CODE,
|
|
168
|
+
test: (l) => { const a = logArgs(l); return a !== null && /\b(req\.(body|query|params|headers)|request\.(args|form|json|data))\b(?!\.\w)/.test(a); } }),
|
|
169
|
+
// A10 Mishandling of Exceptional Conditions
|
|
170
|
+
rule({ id: "error.empty-catch", title: "Error caught and ignored", status: "gap", severity: "medium", controls: [A10],
|
|
171
|
+
fix: "Handle the error, log it, or let it propagate. If ignoring it is deliberate, say why in a comment and catch only the specific error.",
|
|
172
|
+
note: "Silent failures hide attacks and bugs, and can leave the app running in a broken or unsafe state (CWE-390).", extensions: CODE,
|
|
173
|
+
test: (l) => /\bcatch\s*(\(\s*\w*\s*\))?\s*\{\s*\}|^\s*except(\s+[\w.,() ]+)?\s*:\s*pass\b/.test(l) }),
|
|
174
|
+
rule({ id: "error.stack-to-client", title: "Error details sent to the user", status: "gap", severity: "medium", controls: [A10, A02],
|
|
175
|
+
fix: "Log the full error on the server and send users a short, generic message with a reference id.",
|
|
176
|
+
note: "Stack traces show file paths, library versions and sometimes data, which helps attackers (CWE-209).", extensions: CODE,
|
|
177
|
+
test: (l) => !LOG_CALL.test(l) && /\bres\.(status\(\d+\)\.)?(send|json|end)\(\s*(\{[^}]*)?\b(err|error|e)\.stack\b|\bres\.(status\(\d+\)\.)?send\(\s*(err|error)\s*\)|\btraceback\.format_exc\(\)/.test(l) }),
|
|
178
|
+
];
|
|
179
|
+
/** Existing rules that also relate to an OWASP Top 10:2025 category. Added to their controls at load time. */
|
|
180
|
+
export const owaspForExisting = {
|
|
181
|
+
"pii.logged": [A09],
|
|
182
|
+
"secret.in-source": [A04, A07],
|
|
183
|
+
"transport.plain-http": [A04],
|
|
184
|
+
"pii.in-url": [A06],
|
|
185
|
+
"crypto.weak-password-hash": [A04],
|
|
186
|
+
"transport.tls-verify-off": [A04, A07],
|
|
187
|
+
"sql.string-built": [A05],
|
|
188
|
+
"cors.any-origin": [A02, A01],
|
|
189
|
+
"session.cookie-insecure": [A02, A07],
|
|
190
|
+
"config.debug-on": [A02],
|
|
191
|
+
"ai.call-not-logged": [A09],
|
|
192
|
+
};
|
package/dist/src/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export type Status = "met" | "partial" | "gap" | "outside";
|
|
2
2
|
export type Severity = "high" | "medium" | "low";
|
|
3
|
-
export type FrameworkId = "gdpr" | "soc2" | "iso-27001" | "eu-ai-act";
|
|
3
|
+
export type FrameworkId = "gdpr" | "soc2" | "iso-27001" | "eu-ai-act" | "owasp-top10";
|
|
4
4
|
export interface Control {
|
|
5
5
|
framework: FrameworkId;
|
|
6
6
|
id: string;
|
|
@@ -17,6 +17,14 @@ export interface Rule {
|
|
|
17
17
|
note: string;
|
|
18
18
|
/** Files this rule reads, by extension. */
|
|
19
19
|
extensions: string[];
|
|
20
|
+
/** Optional: only files whose name matches, e.g. /^package\.json$/ so lockfiles are skipped. */
|
|
21
|
+
fileName?: RegExp;
|
|
22
|
+
/** Optional: a line hit is dropped when this appears within 8 lines above or 3 below
|
|
23
|
+
* (e.g. an exp claim set in the payload just before jwt.encode). */
|
|
24
|
+
unlessNear?: RegExp;
|
|
25
|
+
/** Optional: a hit is dropped when the nearest enclosing JSON key above it matches
|
|
26
|
+
* (e.g. "peerDependencies", where "*" is the normal range). */
|
|
27
|
+
unlessInKey?: RegExp;
|
|
20
28
|
/** Line rule: true when the line breaks the rule. Must be pure: same line, same answer. */
|
|
21
29
|
test?(line: string): boolean | "partial";
|
|
22
30
|
/** File rule, for checks that need context (e.g. "an AI call with no logging in this file").
|
package/package.json
CHANGED