@lintsure/core 0.3.0 → 0.3.2

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.
@@ -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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[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
+ }
@@ -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.3.0";
14
+ export declare const RULES_VERSION = "0.3.2";
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.3.0";
20
+ export const RULES_VERSION = "0.3.2";
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. " +
@@ -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 relevant = active.filter((r) => r.extensions.includes(ext));
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) => { const hit = r.test(text); if (hit)
148
- add(r, i + 1, hit === "partial" ? "partial" : r.status); });
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);
@@ -89,5 +89,5 @@ export const owaspTop10 = {
89
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
90
  "Saying an app is 'OWASP compliant' isn't meaningful. Describe what was checked and what wasn't.",
91
91
  ],
92
- checkedOn: "2026-11-09",
92
+ checkedOn: "2026-11-08",
93
93
  };
@@ -59,7 +59,7 @@ export const soc2 = {
59
59
  "A SOC 2 report is about your controls, not a pass or fail certificate. Exceptions are normal and get described.",
60
60
  "Type I looks at one day. Type II covers a period, often 3 to 12 months, so start collecting evidence early.",
61
61
  "Using AI in your service can bring AI-specific risks into scope. Auditors may ask how you oversee it.",
62
- "The AICPA has proposed updated criteria. Check which version your auditor uses.",
62
+ "The AICPA published a draft of updated criteria in October 2026. It is open for comment until 15 January 2027 and, if approved, would apply from engagements starting on or after 31 December 2027. The criterion numbers in Lintsure follow the current criteria. Check which version your auditor uses.",
63
63
  ],
64
- checkedOn: "2026-11-07",
64
+ checkedOn: "2026-11-09",
65
65
  };
@@ -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[];
@@ -127,7 +127,7 @@ export const rules = [
127
127
  fix: "Remove the override and trust a proper certificate. For self-signed certs in tests, scope it to the test only.",
128
128
  note: "With checks off, anyone on the network path can read or change the traffic.",
129
129
  extensions: [...CODE, ".env"],
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|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
131
131
  ...DRAFT,
132
132
  },
133
133
  {
@@ -199,7 +199,29 @@ export const rules = [
199
199
  // --- EU AI Act -------------------------------------------------------------
200
200
  // Code can show *signals* for the AI Act, not the legal risk tier itself. These rules
201
201
  // flag what an auditor would ask about; the Classifier and the user decide the tier.
202
- const AI_CALL = /\b(openai|anthropic|client)\.(chat\.completions|responses|messages|completions)\.create\s*\(|\bgenerateText\s*\(|\bstreamText\s*\(|\b(model|clf|classifier|pipeline)\.(predict|predict_proba|invoke|generate)\s*\(/;
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] : [])) : [];
203
225
  const DECISION = /\b(approv|reject|deny|denied|declin|eligib|hire|hiring|shortlist|credit|loan|underwrit|admit|admission|ban|suspend)\w*/i;
204
226
  const LOGGED = /\b(logger|log|logging|audit|auditLog|console)\.\w+\s*\(|\binsert\w*\s*\(|\.save\s*\(/;
205
227
  rules.push({
@@ -218,16 +240,16 @@ rules.push({
218
240
  ...DRAFT,
219
241
  }, {
220
242
  id: "ai.call-not-logged",
221
- title: "AI call with no record kept in this file",
243
+ title: "AI call with no record kept near it",
222
244
  status: "partial", severity: "medium",
223
245
  controls: [
224
246
  { framework: "eu-ai-act", id: "Art. 12", title: "Record-keeping" },
225
247
  { framework: "soc2", id: "CC7.2", title: "Monitoring of system components" },
226
248
  ],
227
249
  fix: "Log each AI call: time, model and version, input reference and output, without raw personal data.",
228
- 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.",
229
251
  extensions: CODE,
230
- fileTest: (lines) => lines.some((l) => LOGGED.test(l)) ? [] : lines.flatMap((l, i) => (AI_CALL.test(l) ? [i + 1] : [])),
252
+ fileTest: unloggedAiCalls,
231
253
  ...DRAFT,
232
254
  }, {
233
255
  id: "ai.hides-being-ai",
@@ -248,6 +270,8 @@ rules.push({
248
270
  note: "Marked Partial: you may already add marking after this call. Confirm it does.",
249
271
  extensions: CODE,
250
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,
251
275
  ...DRAFT,
252
276
  }, {
253
277
  id: "ai.emotion-or-biometric",
@@ -54,7 +54,9 @@ export const owaspRules = [
54
54
  rule({ id: "config.default-secret-key", title: "Default or placeholder secret key", status: "gap", severity: "high", controls: [A02, A07],
55
55
  fix: "Generate a long random secret per environment and load it from an environment variable or secret manager.",
56
56
  note: "With a known secret key, attackers can forge sessions, cookies or signed tokens (CWE-1394).", extensions: [...CODE, ".env"],
57
- 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) }),
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) }),
58
60
  rule({ id: "xml.external-entities", title: "XML parser may load external entities", status: "partial", severity: "high", controls: [A02],
59
61
  fix: "Use defusedxml in Python, or turn off entity resolution and DTD loading in your parser.",
60
62
  note: "A crafted XML file can read local files or call internal URLs (XML external entities, CWE-611).", extensions: CODE,
@@ -62,11 +64,11 @@ export const owaspRules = [
62
64
  // A03 Software Supply Chain Failures
63
65
  rule({ id: "deps.unpinned-version", title: "Dependency with no version limit", status: "gap", severity: "medium", controls: [A03],
64
66
  fix: "Pin a version or a range in package.json and commit the lockfile, so every install gets the code you tested.",
65
- note: "\"*\" or \"latest\" installs whatever is published next, including a compromised release (CWE-1357).", extensions: [".json"],
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
66
68
  test: (l) => /^\s*"(@?[\w.-]+\/)?[\w.-]+"\s*:\s*"(\*|latest|x)"\s*,?\s*$/.test(l) }),
67
69
  rule({ id: "deps.install-script", title: "Install script downloads code", status: "partial", severity: "medium", controls: [A03],
68
70
  fix: "Avoid downloading and running code in preinstall or postinstall. Vendor the file or document a manual step.",
69
- note: "Code fetched at install time isn't pinned or reviewed and runs with the installer's permissions (CWE-829).", extensions: [".json"],
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$/,
70
72
  test: (l) => /"(pre|post)?install"\s*:\s*"[^"]*\b(curl|wget|Invoke-WebRequest)\b/.test(l) }),
71
73
  rule({ id: "ci.action-unpinned", title: "Third-party GitHub Action not pinned to a commit", status: "partial", severity: "medium", controls: [A03],
72
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,7 +77,8 @@ export const owaspRules = [
75
77
  rule({ id: "ci.prt-checkout-head", title: "pull_request_target workflow checks out untrusted code", status: "gap", severity: "high", controls: [A03, A08],
76
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.",
77
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,
78
- fileTest: (lines) => lines.some((l) => /\bpull_request_target\b/.test(l))
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))
79
82
  ? lines.flatMap((l, i) => (/github\.event\.pull_request\.head\.(sha|ref)|refs\/pull\/.*\/(head|merge)/.test(l) ? [i + 1] : [])) : [] }),
80
83
  // A04 Cryptographic Failures
81
84
  rule({ id: "crypto.weak-random-token", title: "Predictable random numbers used for a secret", status: "gap", severity: "high", controls: [A04],
@@ -102,7 +105,8 @@ export const owaspRules = [
102
105
  rule({ id: "code.eval", title: "Code run from a string", status: "gap", severity: "high", controls: [A05],
103
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.",
104
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,
105
- test: (l) => /(^|[^.\w])eval\s*\(|\bnew Function\s*\(/.test(l) ? byInput(l) : false }),
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 }),
106
110
  rule({ id: "xss.raw-html", title: "HTML inserted without escaping", status: "partial", severity: "high", controls: [A05],
107
111
  fix: "Set text with textContent, let your framework escape values, or sanitise with DOMPurify before inserting HTML.",
108
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,
@@ -132,7 +136,7 @@ export const owaspRules = [
132
136
  rule({ id: "jwt.no-expiry", title: "JWT signed without an expiry", status: "partial", severity: "medium", controls: [A07],
133
137
  fix: "Add expiresIn (Node) or an exp claim (Python), and keep access tokens short-lived.",
134
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,
135
- test: (l) => /\bjwt\.(sign|encode)\(/.test(l) && !/expiresIn|\bexp\b/.test(l) }),
139
+ test: (l) => /\bjwt\.(sign|encode)\(/.test(l) && !/expiresIn|\bexp\b/.test(l), unlessNear: /expiresIn|["']exp["']|\bexp\s*[:=]/ }),
136
140
  // A08 Software or Data Integrity Failures
137
141
  rule({ id: "deserialize.unsafe", title: "Unsafe deserialisation", status: "gap", severity: "high", controls: [A08],
138
142
  fix: "Use JSON for data from outside. In Python use yaml.safe_load, never pickle or marshal on untrusted data.",
@@ -150,7 +154,14 @@ export const owaspRules = [
150
154
  rule({ id: "log.secret", title: "Secret or token written to logs", status: "gap", severity: "high", controls: [A09],
151
155
  fix: "Remove the value from the log call, or log only that it was present.",
152
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,
153
- test: (l) => { const a = logArgs(l); return a !== null && /\b(token|secret|authorization|api_?key|apiKey|bearer|access_token|refresh_token|private_?key|client_secret)\b/i.test(stripStrings(a)); } }),
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
+ } }),
154
165
  rule({ id: "log.injection", title: "Raw request data written to logs", status: "partial", severity: "low", controls: [A09],
155
166
  fix: "Log specific, validated fields, and strip line breaks from user input before logging it.",
156
167
  note: "Line breaks in user input can forge fake log entries and mislead an investigation (CWE-117).", extensions: CODE,
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lintsure/core",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Lintsure engine: rules, framework knowledge and reports for readiness checks of AI-written code. Not an audit or legal advice.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",