@lintsure/core 0.3.9 → 0.3.11

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,206 @@
1
+ // Reachability: which entry points (routes, API handlers, middleware, server actions, functions, workers) can reach a
2
+ // file through the project's own imports. A small resolver of our own: literal import/export/require/import()
3
+ // specifiers, relative paths with the usual extensions and index files, the .js -> .ts swap, and tsconfig
4
+ // baseUrl/paths. Packages are outside the project and not followed. A specifier we can't resolve is kept as an
5
+ // "unresolved" edge and makes the answer "unknown", never a guess. JavaScript and TypeScript only. Pure.
6
+ const CODE = /\.(m|c)?[jt]sx?$/;
7
+ const EXTS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
8
+ // Linear on purpose: the older import-then-names-then-from pattern backtracked quadratically on long runs of the word import
9
+ // (code review). Matching the from-clause alone covers import and export-from, including ones split over several lines.
10
+ const SPEC = /\bfrom\s*["']([^"'\n]+)["']|\bimport\s+["']([^"'\n]+)["']|\brequire\(\s*["']([^"'\n]+)["']\s*\)|\bimport\(\s*["']([^"'\n]+)["']\s*\)/g;
11
+ /** Literal specifiers a file imports. Pure. */
12
+ export function specifiers(text) {
13
+ const out = [];
14
+ for (const m of text.matchAll(SPEC))
15
+ out.push(m[1] ?? m[2] ?? m[3] ?? m[4]);
16
+ return out;
17
+ }
18
+ // JSON with line and block comments removed, leaving anything inside strings alone (a glob like "src/**" is not a comment). Pure.
19
+ export function stripJsonComments(text) {
20
+ let out = "", i = 0, str = false;
21
+ while (i < text.length) {
22
+ const c = text[i], n = text[i + 1];
23
+ if (str) {
24
+ out += c;
25
+ if (c === "\\") {
26
+ out += n ?? "";
27
+ i += 2;
28
+ continue;
29
+ }
30
+ if (c === '"')
31
+ str = false;
32
+ i++;
33
+ continue;
34
+ }
35
+ if (c === '"') {
36
+ str = true;
37
+ out += c;
38
+ i++;
39
+ continue;
40
+ }
41
+ if (c === "/" && n === "/") {
42
+ while (i < text.length && text[i] !== "\n")
43
+ i++;
44
+ continue;
45
+ }
46
+ if (c === "/" && n === "*") {
47
+ i += 2;
48
+ while (i < text.length && !(text[i] === "*" && text[i + 1] === "/"))
49
+ i++;
50
+ i += 2;
51
+ continue;
52
+ }
53
+ out += c;
54
+ i++;
55
+ }
56
+ return out;
57
+ }
58
+ /** Path aliases from a tsconfig.json text (comments allowed): baseUrl and paths, as [prefix, targets] pairs. Pure. */
59
+ export function tsAliases(text, root = "") {
60
+ if (!text)
61
+ return { root, baseUrl: null, paths: [] };
62
+ try {
63
+ const json = JSON.parse(stripJsonComments(text).replace(/,(\s*[}\]])/g, "$1"));
64
+ const o = json.compilerOptions ?? {}, base = typeof o.baseUrl === "string" ? o.baseUrl.replace(/^\.\/?/, "").replace(/\/$/, "") : null;
65
+ // [prefix, targets, wildcard]: a key without "*" matches only itself ("@app" is not "@apple/x").
66
+ const paths = Object.entries((o.paths ?? {})).map(([k, v]) => [k.replace(/\*$/, ""), v.map((t) => t.replace(/\*$/, "").replace(/^\.\//, "")), k.endsWith("*")]);
67
+ return { root, baseUrl: base, paths };
68
+ }
69
+ catch {
70
+ return { root, baseUrl: null, paths: [] };
71
+ }
72
+ }
73
+ const norm = (p) => { const out = []; for (const s of p.split("/")) {
74
+ if (s === "..")
75
+ out.pop();
76
+ else if (s && s !== ".")
77
+ out.push(s);
78
+ } return out.join("/"); };
79
+ const dir = (p) => p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "";
80
+ /** The project file a specifier points at, "external" for a package, or null when it looks local but can't be found. Pure. */
81
+ export function resolveSpec(from, spec, files, alias) {
82
+ const tryAll = (base) => {
83
+ const cands = [base, base.replace(/\.(m|c)?js$/, (e) => e.replace("js", "ts")), base.replace(/\.jsx$/, ".tsx"), ...EXTS.map((e) => base + e), ...EXTS.map((e) => `${base}/index${e}`)];
84
+ return cands.find((c) => files.has(c)) ?? null;
85
+ };
86
+ if (spec.startsWith("."))
87
+ return tryAll(norm(`${dir(from)}/${spec}`));
88
+ if (spec.startsWith("/"))
89
+ return tryAll(norm(spec));
90
+ for (const [prefix, targets, wild] of alias.paths)
91
+ if (wild ? spec.startsWith(prefix) : spec === prefix) {
92
+ for (const t of targets) {
93
+ const hit = tryAll(norm(`${alias.root}/${alias.baseUrl ?? ""}/${t}${spec.slice(prefix.length)}`));
94
+ if (hit)
95
+ return hit;
96
+ }
97
+ return null;
98
+ }
99
+ if (alias.baseUrl != null) {
100
+ const hit = tryAll(norm(`${alias.root}/${alias.baseUrl}/${spec}`));
101
+ if (hit)
102
+ return hit;
103
+ }
104
+ // "@/x" and "~/x" with no tsconfig entry are almost always local aliases, so they count as unresolved, not packages.
105
+ return /^[@~#]\//.test(spec) ? null : "external";
106
+ }
107
+ // Files a request or event starts in: Next.js routes, pages and API routes, middleware, server actions, serverless and
108
+ // Supabase/Netlify functions, Workers, Express/Hono/Fastify-style handlers, framework config files, and the top-level
109
+ // index/main/server/App file a runtime or bundler starts from.
110
+ const ENTRY_PATH = /(^|\/)(app\/(.+\/)?(route|page|layout)\.[jt]sx?|pages\/(.+\/)?[^/]+\.[jt]sx?|middleware\.[jt]s|supabase\/functions\/[^/]+\/index\.[jt]s|netlify\/functions\/.+\.[jt]s|[^/]+\.config\.[cm]?[jt]s|routes\/(.+\/)?\+(page|layout|server)(\.server)?\.[jt]s|hooks\.server\.[jt]s|app\/routes\/.+\.[jt]sx?|app\/(root|entry\.server|entry\.client)\.[jt]sx?|bin\/.+\.[cm]?[jt]sx?)$|^[^/]+\.[cm]?[jt]sx?$|^(src\/)?(api|functions)\/.+\.[cm]?[jt]s$/;
111
+ // api/ and functions/ count only at the project root (Vercel and Firebase style), not src/lib/api/client.ts (code review).
112
+ // Relative to a package folder (a folder with package.json): the file a runtime or bundler starts from.
113
+ const PKG_ENTRY = /^(src\/)?(index|main|server|app|App|cli|worker)\.[cm]?[jt]sx?$/;
114
+ const ENTRY_TEXT = /^\s*["']use server["']|\b(app|router|server|api)\.(get|post|put|patch|delete|all|route|use)\s*\(\s*["'`/]|\bexport\s+default\s*\{[^}]*\bfetch\b|\baddEventListener\(\s*["']fetch["']|\bDeno\.serve\(|\bcreateServer\(|\bexport\s+(async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\b/m;
115
+ /** Files a project starts from that no code imports: package.json main/module/bin/exports, and scripts an HTML page
116
+ * loads with <script src>. Paths come back relative to the project root. Pure. */
117
+ export function declaredEntries(pkgs, html, files) {
118
+ const out = [];
119
+ const add = (from, p) => { if (typeof p !== "string" || /^(https?:)?\/\//.test(p))
120
+ return; const hit = resolveSpec(from, p.startsWith(".") || p.startsWith("/") ? p : `./${p}`, files, tsAliases(null)); if (typeof hit === "string" && hit !== "external")
121
+ out.push(hit); };
122
+ for (const [path, text] of Object.entries(pkgs)) {
123
+ let j;
124
+ try {
125
+ j = JSON.parse(text);
126
+ }
127
+ catch {
128
+ continue;
129
+ }
130
+ const at = path.includes("/") ? `${path.slice(0, path.lastIndexOf("/"))}/package.json` : "package.json";
131
+ for (const k of ["main", "module", "browser", "types"])
132
+ add(at, j[k]);
133
+ for (const v of typeof j.bin === "string" ? [j.bin] : Object.values((j.bin ?? {})))
134
+ add(at, v);
135
+ const walk = (v) => { if (typeof v === "string")
136
+ add(at, v);
137
+ else if (v && typeof v === "object")
138
+ Object.values(v).forEach(walk); };
139
+ walk(j.exports);
140
+ }
141
+ for (const [path, text] of Object.entries(html))
142
+ for (const m of text.matchAll(/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["']/gi))
143
+ add(path, m[1].split(/[?#]/)[0]);
144
+ return out;
145
+ }
146
+ /** Builds the import graph and the entry points from the project's JS/TS files. Pure. */
147
+ export function buildGraph(files, tsconfigs = null, pkgDirs = [""], extraEntries = []) {
148
+ const set = new Set(Object.keys(files));
149
+ // Each file uses the tsconfig of its nearest folder that has one (monorepos keep one per package).
150
+ const configs = typeof tsconfigs === "string" || tsconfigs === null ? { "": tsconfigs ?? "" } : tsconfigs;
151
+ const aliases = Object.entries(configs).map(([d, t]) => tsAliases(t || null, d)).sort((a, b) => b.root.length - a.root.length);
152
+ // The nearest tsconfig that has aliases: a package tsconfig without paths falls back to the one above it.
153
+ const aliasFor = (f) => aliases.find((a) => (!a.root || f.startsWith(a.root + "/")) && (a.paths.length || a.baseUrl != null)) ?? tsAliases(null);
154
+ const pkgs = [...pkgDirs].sort((a, b) => b.length - a.length);
155
+ const pkgRel = (f) => { const d = pkgs.find((p) => !p || f.startsWith(p + "/")); return d ? f.slice(d.length + 1) : f; };
156
+ const importers = new Map(), imports = new Map(), entries = new Set(extraEntries.filter((e) => set.has(e))), unresolved = new Map();
157
+ for (const [f, text] of Object.entries(files)) {
158
+ if (!CODE.test(f))
159
+ continue;
160
+ if (ENTRY_PATH.test(f) || PKG_ENTRY.test(pkgRel(f)) || ENTRY_TEXT.test(text))
161
+ entries.add(f);
162
+ for (const s of specifiers(text)) {
163
+ const to = resolveSpec(f, s, set, aliasFor(f));
164
+ if (to === "external")
165
+ continue;
166
+ if (to === null) {
167
+ (unresolved.get(f) ?? unresolved.set(f, []).get(f)).push(s);
168
+ continue;
169
+ }
170
+ (importers.get(to) ?? importers.set(to, new Set()).get(to)).add(f);
171
+ (imports.get(f) ?? imports.set(f, new Set()).get(f)).add(to);
172
+ }
173
+ }
174
+ return { importers, imports, entries, unresolved };
175
+ }
176
+ /** Whether an entry point reaches this file, with the shortest chain entry -> ... -> file. "unknown" when nothing
177
+ * reaches it but an unresolved import somewhere could be pointing at it (same file name). Pure. */
178
+ export function reachOf(g, file) {
179
+ if (g.entries.has(file))
180
+ return { status: "entry" };
181
+ // One search outward from every entry point, done once per graph (it was one search per finding).
182
+ if (!g.parent) {
183
+ g.parent = new Map();
184
+ const queue = [...g.entries];
185
+ for (const e of queue)
186
+ g.parent.set(e, "");
187
+ for (let i = 0; i < queue.length; i++)
188
+ for (const to of g.imports.get(queue[i]) ?? [])
189
+ if (!g.parent.has(to)) {
190
+ g.parent.set(to, queue[i]);
191
+ queue.push(to);
192
+ }
193
+ g.unresolvedNames = new Set([...g.unresolved.values()].flatMap((specs) => specs.map((sp) => sp.replace(/\.[^./]+$/, "").split("/").pop())));
194
+ }
195
+ if (g.parent.has(file)) {
196
+ const via = [];
197
+ let x = file;
198
+ while (x) {
199
+ via.unshift(x);
200
+ x = g.parent.get(x) || undefined;
201
+ }
202
+ return { status: "reachable", via };
203
+ }
204
+ const base = file.replace(/^.*\//, "").replace(/\.[^.]+$/, "").replace(/^index$/, file.split("/").slice(-2, -1)[0] ?? "index");
205
+ return { status: g.unresolvedNames.has(base) ? "unknown" : "unreachable" };
206
+ }
@@ -39,7 +39,12 @@ export const craRules = [
39
39
  note: "Piping `curl` or `wget` straight into a shell runs whatever the server sends at that moment, with no check that it is the file you expect. Marked Partial: well-known installers over HTTPS are a common, accepted risk.",
40
40
  extensions: [".sh", ".bash", ".yml", ".yaml", ""], fileName: /\.(sh|bash|ya?ml)$|^Dockerfile/i,
41
41
  // Quoted text is dropped first: `echo "Install via: curl ... | bash"` tells a person what to run, it runs nothing (field test).
42
- test: (l) => /\b(curl|wget)\b[^|#\n]*\|\s*(sudo\s+)?(-\S+\s+)*(ba|z|da)?sh\b/.test(l.replace(/"(?:\\.|[^"\\])*"|'[^']*'/g, '""')), ...DRAFT },
42
+ // A script served from this machine (a CI test of the project's own installer) or an installer pinned to a version
43
+ // in its URL is not a moving download (0.3.9 review: 8 of 10 sampled findings were these, or prose).
44
+ test: (l) => /\b(curl|wget)\b[^|#\n]*\|\s*(sudo\s+)?(-\S+\s+)*(ba|z|da)?sh\b/.test(l.replace(/"(?:\\.|[^"\\])*"|'[^']*'/g, '""'))
45
+ && !/\b(localhost|127\.0\.0\.1|0\.0\.0\.0)\b/.test(l) && !/https?:\/\/\S*\/v?\d+\.\d+(\.\d+)?\/\S*install/.test(l),
46
+ // YAML is only run as a script in CI and compose files; elsewhere (manifests, risk registers) it is prose.
47
+ unlessPath: /^(?!.*(\.github\/workflows|\.gitlab-ci|\.circleci|bitbucket-pipelines|azure-pipelines|\.buildkite|docker-compose|(^|\/)compose\.)).*\.ya?ml$/i, ...DRAFT },
43
48
  { id: "ci.write-all-permissions", title: "Workflow gives its token write access to everything", status: "gap", severity: "medium", controls: [UPDATES, A03],
44
49
  fix: "Replace `permissions: write-all` with only what the job needs, for example `permissions: contents: read`, and grant write access per job where it's really used.",
45
50
  note: "With write-all, any step that is compromised, including a third-party action, can push code, change releases or edit issues with the workflow's token.",
@@ -10,6 +10,8 @@ const LOG_CALL = /\b(console\.(log|info|warn|error|debug)|logger\.\w+|log\.(info
10
10
  // [^\\] keeps the two alternatives apart: with "." a run of backslashes could match two ways, which backtracks
11
11
  // exponentially on text such as an array of regular expressions (found when statements were joined).
12
12
  const codeOnly = (l) => l.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
13
+ // Helpers that hide the raw value before it is logged.
14
+ const MASKED = /\b\w*(mask|hash|pseudonym|redact|anonymi[sz]e|obfuscate|scrub)\w*\s*\(/i;
13
15
  const PII = /\b(e-?mail|phone|ssn|social_?security|passport|date_?of_?birth|dob|password|passwd|credit_?card|card_?number|iban)\b/i;
14
16
  // The arguments of the first log call on a line, up to its matching ")". Other code on the same line is ignored.
15
17
  function logArgs(l) {
@@ -87,7 +89,9 @@ export const rules = [
87
89
  note: "Logs are copied to many places and kept for a long time. Personal data in them is hard to find and delete.",
88
90
  extensions: CODE,
89
91
  // ::add-mask:: tells GitHub Actions to hide the value in its logs.
90
- test: (l) => { const a = logArgs(l); return a !== null && !l.includes("::add-mask::") && PII.test(codeOnly(a)); },
92
+ // A value passed through a masking or hashing helper first (maskEmail(), pseudonym(), hash()) is not the raw value:
93
+ // every false alarm on 56 new repos in the 0.3.9 review was masked this way (12 of 12).
94
+ test: (l) => { const a = logArgs(l); return a !== null && !l.includes("::add-mask::") && PII.test(codeOnly(a)) && !MASKED.test(a); },
91
95
  ...DRAFT,
92
96
  },
93
97
  {
@@ -107,10 +111,14 @@ export const rules = [
107
111
  if (/\bplaceholder\s*[=:]/i.test(l))
108
112
  return false; // a form's example text (placeholder="sk_live_...")
109
113
  const m = l.match(KEY_FORMATS) ?? l.match(MORE_KEYS);
110
- return (!!m && !DOC_EXAMPLE.test(m[0]) && !/PRIVATE KEY( BLOCK)?-----(["'`]|\.\.\.)/.test(l)) || serviceRoleJwt(l) || dbUrlWithPassword(l);
114
+ // Placeholders say so: xoxb-your-bot-token, ghp_...fake..., a PEM header followed by "...", or by prose
115
+ // ("starts with -----BEGIN PRIVATE KEY----- and"). 0 of 7 sampled secret findings were real (0.3.9 review).
116
+ return (!!m && !DOC_EXAMPLE.test(m[0]) && !/your[-_]|fake|dummy|placeholder|changeme|sample/.test(m[0]) /* lowercase words: real keys are random */
117
+ && !/PRIVATE KEY( BLOCK)?-----(["'`]|\.\.\.|\\n\s*\.\.\.|\s+[a-zA-Z])/.test(l)) || serviceRoleJwt(l) || dbUrlWithPassword(l);
111
118
  },
112
- // Translation files mention "API key" and "secret" in every language, never a real key (0.3.9 labels).
113
- unlessPath: /(^|\/)(locales?|i18n|translations?|lang)\//i,
119
+ // Translation files mention "API key" and "secret" in every language, never a real key. Type definition files
120
+ // carry documentation examples, and secret-scanner configs list known test keys on purpose (0.3.9 review).
121
+ unlessPath: /(^|\/)(locales?|i18n|translations?|lang)\/|\.d\.ts$|(^|\/)(\.gitleaks\.toml|\.secrets\.baseline|\.trufflehog\.ya?ml)$/i,
114
122
  ...DRAFT,
115
123
  },
116
124
  {
@@ -137,7 +145,9 @@ export const rules = [
137
145
  fix: "Send an internal user ID instead of the email or name. If personal data must go there, list the tool as a processor.",
138
146
  note: "Analytics vendors keep what you send them. Personal data there needs a lawful basis and a processing agreement.",
139
147
  extensions: CODE,
140
- test: (l) => /\b(posthog|analytics|mixpanel|amplitude|segment|heap|gtag|ga|intercom|hotjar|sentry)\.(identify|track|capture|people\.set|setUser|setUserProperties|register)\s*\(/i.test(l) && PII.test(l),
148
+ // Also a bare track("event", { ... }), the way @vercel/analytics and similar SDKs are imported and called.
149
+ test: (l) => (/\b(posthog|analytics|mixpanel|amplitude|segment|heap|gtag|ga|intercom|hotjar|sentry)\.(identify|track|capture|people\.set|setUser|setUserProperties|register)\s*\(/i.test(l)
150
+ || /(^|[^.\w])track\s*\(\s*["'`][^"'`]+["'`]\s*,\s*\{/.test(l)) && PII.test(l),
141
151
  ...DRAFT,
142
152
  },
143
153
  {
@@ -185,6 +195,8 @@ export const rules = [
185
195
  note: "With checks off, anyone on the network path can read or change the traffic.",
186
196
  extensions: [...CODE, ".env"],
187
197
  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
198
+ // Only the switches with one safe opposite; env vars and ssl modes need a person.
199
+ patch: (l) => l.replace(/rejectUnauthorized(\s*):(\s*)false/, "rejectUnauthorized$1:$2true").replace(/\bverify(\s*)=(\s*)False\b/, "verify$1=$2True").replace(/InsecureSkipVerify(\s*):(\s*)true/, "InsecureSkipVerify$1:$2false"),
188
200
  ...DRAFT,
189
201
  },
190
202
  {
@@ -255,6 +267,7 @@ export const rules = [
255
267
  return /\b(res|response|reply|ctx|cookies?)\.(cookie|set|setCookie)\s*\(|Set-Cookie|\bcookie\s*:\s*\{|cookieOptions|serialize\(|SESSION_COOKIE/i.test(near)
256
268
  && !/csrf|xsrf/i.test(near) && !/\b(smtp|createTransport|nodemailer|ignoreTLS|requireTLS)\b/i.test(near) ? [i + 1] : [];
257
269
  }),
270
+ patch: (l) => l.replace(/\b(httpOnly|secure)(\s*):(\s*)false\b/g, "$1$2:$3true").replace(/(SESSION_COOKIE_(?:SECURE|HTTPONLY)\s*=\s*)False\b/, "$1True"),
258
271
  ...DRAFT,
259
272
  },
260
273
  {
@@ -278,7 +291,12 @@ const AI_CALL = new RegExp([
278
291
  /\b(openai|anthropic|client)\.(chat\.completions|responses|messages|completions)\.create\s*\(/.source,
279
292
  /\b\w+\.chat\.completions\.create\s*\(/.source,
280
293
  /\.generateContent(Stream)?\s*\(/.source,
281
- /\b(generateText|streamText|generateObject|streamObject)\s*\(/.source,
294
+ // Vercel AI SDK, including the experimental_ forms and its agent class (studied in vercel/ai).
295
+ /(?<![A-Za-z])(experimental_)?(generateText|streamText|generateObject|streamObject)\s*\(/.source,
296
+ // Its image, speech, video and transcription calls only in the SDK's own shape: apps name their own wrappers
297
+ // generateImage() or transcribe() too (field test 2026-11-18: 65 false gains before this).
298
+ /(?<![A-Za-z.])experimental_(generateImage|generateSpeech|generateVideo|transcribe)\s*\(|(?<![A-Za-z.])(generateImage|generateSpeech|generateVideo|transcribe)\s*\(\s*\{\s*model\s*:/.source,
299
+ /\bnew\s+(ToolLoopAgent|Experimental_Agent)\s*\(/.source,
282
300
  /\b(model|clf|classifier|pipeline)\.(predict|predict_proba|invoke|generate)\s*\(/.source,
283
301
  /\b(chain|llm|chatModel|agent|runnable)\w*\.(invoke|stream|batch)\s*\(/.source,
284
302
  // A provider URL counts only inside a request call, not where it's stored in a constant.
@@ -298,7 +316,8 @@ export const mediaModelCalls = (lines) => lines.some((l) => MEDIA_MODEL.test(l))
298
316
  // Whole words only: "banner" is not "ban" (field test, 139 repos).
299
317
  // Letters may not touch the word, but underscores may: loan_denied counts, banner doesn't.
300
318
  const DECISION = /(?<![a-z])(approve[ds]?|approval|reject(ed|ion)?|deny|denied|decline[ds]?|eligib(le|ility)|hire[ds]?|hiring|shortlist(ed)?|credit[_ ]?(score|limit|decision)|loan|underwrit[a-z]*|admit(ted)?|admission|ban(ned)?|suspend(ed)?)(?![a-z])/i;
301
- const LOGGED = /\b(logger|log|logging|audit|auditLog|console)\.\w+\s*\(|\binsert\w*\s*\(|\.save\s*\(/;
319
+ // The AI SDK's own record hooks count too: onFinish saving the chat, or telemetry switched on (vercel/ai docs).
320
+ const LOGGED = /\b(logger|log|logging|audit|auditLog|console)\.\w+\s*\(|\binsert\w*\s*\(|\.save\s*\(|\b(save|persist|record|store)[A-Z]\w*\s*\(|\bonFinish\s*:|\b(experimental_)?telemetry\s*:\s*\{/;
302
321
  rules.push({
303
322
  id: "ai.automated-decision",
304
323
  title: "AI makes a decision about a person with no human check in the code",
@@ -348,7 +367,7 @@ rules.push({
348
367
  fix: "Mark generated media as AI-made in a machine-readable way (for example C2PA metadata) and label deepfakes for viewers.",
349
368
  note: "Marked Partial: you may already add marking after this call. Confirm it does.",
350
369
  extensions: CODE,
351
- 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),
370
+ test: (l) => /\bimages\.(generate|edit)\s*\(|\baudio\.speech\.create\s*\(|(?<![A-Za-z])(textToSpeech|text_to_speech|generateImage|generate_image|generateVideo|generate_video|generateSpeech)\s*\(|\b(StableDiffusion\w*|DiffusionPipeline)\b/.test(l),
352
371
  // Also: a generic AI call (e.g. generateContent) in a file that names an image, voice or video model.
353
372
  fileTest: mediaModelCalls,
354
373
  ...DRAFT,
@@ -380,7 +399,7 @@ rules.push(...standardsRules);
380
399
  // After the push, so the new LLM rules also get their CWE tags.
381
400
  for (const r of rules)
382
401
  r.controls.push(...(standardsForExisting[r.id] ?? []));
383
- // Measured on 270 hand-labelled findings from 139 public repositories (0.3.9). These rules were real in fewer than
402
+ // Measured on 270 findings reviewed one by one from 139 public repositories (0.3.9). These rules were real in fewer than
384
403
  // half of their sampled findings, so they are held back unless --all (show: all) is set, and the report says how many.
385
404
  // A rule moves back to high confidence when a fresh labelled sample shows it is real in most findings.
386
405
  const MEDIUM_CONFIDENCE = new Set(["xss.raw-html", "error.empty-catch", "sql.string-built", "code.eval", "cmd.shell-built",
@@ -389,6 +408,8 @@ const MEDIUM_CONFIDENCE = new Set(["xss.raw-html", "error.empty-catch", "sql.str
389
408
  "jwt.unverified", "jwt.no-expiry", "mass-assignment", "transport.tls-verify-off", "crypto.weak-cipher", "crypto.weak-random-token",
390
409
  "ci.script-injection", "log.injection", "log.secret", "auth.hardcoded-password", "mobile.cleartext-traffic", "config.debug-on",
391
410
  "mobile.token-in-plain-storage",
411
+ // 0 of 7 real in the 0.3.9 review: the data was the app's own database, cache or worker pipe.
412
+ "deserialize.unsafe",
392
413
  // Reworked in 0.3.9 to need credentials; not yet measured on a fresh sample.
393
414
  "cors.any-origin"]);
394
415
  for (const r of rules)
@@ -1,4 +1,6 @@
1
1
  import type { Control, Rule } from "../types.js";
2
+ /** Agent instruction line: Gap for override, concealment or sending secrets out; Partial for download-and-run. Pure. */
3
+ export declare function instructionsUnsafe(l: string): boolean | "partial";
2
4
  /** True when a signing or encryption secret falls back to a fixed value written in the code. Pure. */
3
5
  export declare function fallbackSecret(l: string): boolean;
4
6
  export declare const owaspRules: Rule[];
@@ -1,7 +1,37 @@
1
1
  const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
2
2
  const MARKUP = [...CODE, ".html", ".vue", ".svelte", ".astro", ".jinja", ".j2"];
3
3
  const YAML = [".yml", ".yaml"];
4
+ // Files whose commands an agent or editor runs by itself: Claude Code settings, MCP server lists, Cursor, VS Code, Gemini CLI.
5
+ const AGENT_CONFIG = /(^|\/)(\.claude\/settings(\.local)?\.json|\.mcp\.json|\.cursor\/(mcp|hooks)\.json|\.vscode\/(tasks|mcp)\.json|\.gemini\/settings\.json)$/;
6
+ // Download-and-run shapes: piped into a shell, run from $( ), process substitution, base64 into a shell, encoded PowerShell,
7
+ // and download-then-execute chains.
8
+ const RUNS_REMOTE = new RegExp([
9
+ String.raw `\b(curl|wget|iwr|irm|Invoke-WebRequest|Invoke-RestMethod)\b[^|]*\|\s*(sudo\s+)?(sh|bash|zsh|dash|python3?|node|iex|pwsh|powershell)\b`,
10
+ String.raw `\b(sh|bash|zsh)\s+(-c\s+)?[\\"']*\$\(\s*(curl|wget)\b`,
11
+ String.raw `\b(sh|bash|zsh)\s+<\(\s*(curl|wget)\b`,
12
+ String.raw `\bbase64\s+(-d|--decode)\b[^|]*\|\s*(sh|bash|zsh|python3?|node)\b`,
13
+ String.raw `\b(powershell|pwsh)\b.*\s-e(nc|ncodedcommand)?\s+[A-Za-z0-9+/=]{24,}`,
14
+ String.raw `\b(curl|wget)\b[^;&|]*(&&|;)\s*(chmod\s+\+x|\.\/|sh\s|bash\s)`,
15
+ ].join("|"), "i");
16
+ // Files an agent reads as its own instructions.
17
+ const AGENT_INSTRUCTIONS = /(^|\/)(SKILL\.md|AGENTS\.md|CLAUDE\.md|GEMINI\.md|\.cursorrules|\.windsurfrules|copilot-instructions\.md)$|(^|\/)\.cursor\/rules\/[^/]+\.mdc?$|(^|\/)\.(claude|agents|codex|gemini)\/(skills|commands|agents)\/.+\.md$/i;
18
+ const OVERRIDE = /\b(ignore|disregard|forget|override)\s+(all\s+|any\s+)?(of\s+)?(your\s+|the\s+)?(previous|prior|above|earlier|system|original|user'?s?)\s+(instructions|rules|prompts?|messages|guidelines)\b/i;
19
+ const CONCEAL = /\b(do not|don'?t|never)\s+(tell|inform|mention|show|reveal|disclose)\s+(this\s+|it\s+|anything\s+)?(to\s+)?the\s+user\b|\bwithout\s+(telling|informing)\s+the\s+user\b/i;
20
+ // A line that says a download-and-run is blocked or forbidden describes a guard, it doesn't ask for one.
21
+ const FORBIDS = /\b(block(ed|s)?|forbid(den)?|never run|don'?t run|do not run|not allowed|denied)\b/i;
22
+ const EXFIL = /\b(curl|wget|Invoke-WebRequest|iwr|fetch)\b.*(\s-d\b|--data|--upload-file|\s-F\b|\s-T\b|-Method\s+Post|method:\s*["']POST).*(\.env\b|\.ssh|id_rsa|\.aws\/credentials|\$\{?[A-Z_]*(KEY|TOKEN|SECRET|PASSWORD)\b)/i;
23
+ // A line that names the attack to warn about it ("if a page says 'ignore previous instructions', don't follow it") is advice.
24
+ const WARNS = /["'`“”]|\b(if|when|e\.g\.|for example|such as|treat .* as data|never follow|don'?t follow|do not follow|watch out|be careful)\b/i;
25
+ /** Agent instruction line: Gap for override, concealment or sending secrets out; Partial for download-and-run. Pure. */
26
+ export function instructionsUnsafe(l) {
27
+ if (EXFIL.test(l))
28
+ return true;
29
+ if ((OVERRIDE.test(l) || CONCEAL.test(l)) && !WARNS.test(l))
30
+ return true;
31
+ return RUNS_REMOTE.test(l) && !FORBIDS.test(l) ? "partial" : false;
32
+ }
4
33
  const DRAFT = { mappedBy: "beta", reviewedAt: "pending" };
34
+ const LLM01 = { framework: "owasp-llm", id: "LLM01:2026", title: "Prompt Injection" }, LLM03 = { framework: "owasp-llm", id: "LLM03:2026", title: "Excessive Agency" };
5
35
  const A = (n, title) => ({ framework: "owasp-top10", id: `A${n}:2025`, title });
6
36
  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
37
  // Request data on the same line. Without it a match is Partial: the value may be safe text from your own code.
@@ -108,10 +138,35 @@ export const owaspRules = [
108
138
  fix: "Avoid downloading and running code in preinstall or postinstall. Vendor the file or document a manual step.",
109
139
  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$/,
110
140
  test: (l) => /"(pre|post)?install"\s*:\s*"[^"]*\b(curl|wget|Invoke-WebRequest)\b/.test(l) }),
141
+ // Agent settings that run commands on their own (Claude Code hooks, MCP servers, editor tasks). An attacker who can
142
+ // edit one of these files gets code run on every developer machine that opens the repo with that agent.
143
+ rule({ id: "agent.config-runs-remote-code", title: "Agent config downloads and runs code", status: "gap", severity: "high", controls: [A03],
144
+ fix: "Don't download and run scripts from agent hooks, MCP server commands or editor tasks. Pin a reviewed local script or a versioned package instead, and review changes to these files like code.",
145
+ note: "Agents run these commands on their own, often at startup, with your user's permissions. A changed URL or script runs on every machine that opens the repo (CWE-829, CWE-494).",
146
+ extensions: [".json"], pathMatch: AGENT_CONFIG,
147
+ seenIn: [{ title: "CVE-2025-59536: commands in a cloned repo's Claude Code project settings ran when it was opened (Check Point Research)", url: "https://research.checkpoint.com/2026/rce-and-api-token-exfiltration-through-claude-code-project-files-cve-2025-59536/", expect: ["CVE-2025-59536", "hooks", "Claude Code"] }],
148
+ test: (l) => RUNS_REMOTE.test(l) }),
149
+ // Instruction files are now code an agent follows: skills, AGENTS.md, CLAUDE.md, Cursor and Copilot rules. A line that
150
+ // tells the agent to drop earlier instructions, hide something from the user, send secrets out, or download and run a
151
+ // script is acted on the next time any agent opens the repo (skill collections spread these widely).
152
+ rule({ id: "agent.instructions-unsafe", title: "Agent instructions that override, hide or download and run", status: "gap", severity: "high", controls: [A03, LLM01],
153
+ fix: "Remove the line, or rewrite it so the agent asks the user first. Install tools with a pinned, reviewed command instead of piping a download into a shell, and never tell an agent to keep something from the user.",
154
+ note: "Agents read these files as instructions and act on them with your permissions. Gap when the line overrides earlier instructions, hides something from the user or sends secrets out. Partial when it downloads and runs a script, which some setup guides do on purpose (CWE-829, OWASP LLM01).",
155
+ extensions: [".md", ".mdc", ""], pathMatch: AGENT_INSTRUCTIONS,
156
+ unseen: "Lintsure reads the line, not who wrote it or whether the file came from a trusted skill. Check where this file came from before an agent uses it.",
157
+ test: instructionsUnsafe }),
158
+ // A project file that switches off the agent's own permission prompts: every agent that opens the repo then runs any
159
+ // command or edit without asking (Continue's headless default allows every tool, field study 2026-11).
160
+ rule({ id: "agent.permissions-allow-all", title: "Agent settings that skip every permission prompt", status: "gap", severity: "high", controls: [A02, LLM03],
161
+ fix: "Remove the bypass from the shared project file. Allow the few commands you trust by name (for example Bash(npm test)), and keep wider permissions in your own local settings, not in the repo.",
162
+ note: "Committed agent settings apply to everyone who opens the repo with that agent. Skipping prompts or allowing every shell command lets a bad instruction, a poisoned file or a mistake run without a person seeing it (CWE-250, OWASP LLM03 Excessive Agency).",
163
+ extensions: [".json", ".toml"], pathMatch: /(^|\/)(\.claude\/settings\.json|\.gemini\/settings\.json|\.codex\/config\.toml|\.continue\/(config|permissions)\.ya?ml|\.vscode\/settings\.json)$/,
164
+ test: (l) => /"defaultMode"\s*:\s*"bypassPermissions"|(?:^|[[,])\s*"(Bash|Bash\(\*\)|Bash\(:\*\)|\*)"\s*(?:[,\]]|$)|--dangerously-skip-permissions|"(yolo|autoAccept)"\s*:\s*true|\bapproval_policy\s*=\s*["']never["']|\bsandbox_mode\s*=\s*["']danger-full-access["']|"chat\.tools\.autoApprove"\s*:\s*true/.test(l) }),
111
165
  rule({ id: "ci.action-unpinned", title: "Third-party GitHub Action not pinned to a commit", status: "partial", severity: "medium", controls: [A03],
112
166
  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.",
113
167
  note: "A tag like @v1 can be moved by the action's owner, or by whoever takes over their account (CWE-829).", extensions: YAML,
114
- test: (l) => /^\s*-?\s*uses:\s*["']?(?!actions\/|github\/|\.\/|docker:\/\/)[\w.-]+\/[\w./-]+@(?![0-9a-f]{40}\b)[\w.-]+/.test(l) }),
168
+ test: (l) => /^\s*-?\s*uses:\s*["']?(?!actions\/|github\/|\.\/|docker:\/\/)[\w.-]+\/[\w./-]+@(?![0-9a-f]{40}\b)[\w.-]+/.test(l),
169
+ seenIn: [{ title: "CVE-2025-30066: tj-actions/changed-files tags were moved to a malicious commit that printed CI secrets to logs (CISA alert)", url: "https://www.cisa.gov/news-events/alerts/2025/03/18/supply-chain-compromise-third-party-tj-actionschanged-files-cve-2025-30066-and-reviewdogaction", expect: ["CVE-2025-30066", "tj-actions/changed-files", "secrets"] }] }),
115
170
  rule({ id: "ci.prt-checkout-head", title: "pull_request_target workflow checks out untrusted code", status: "gap", severity: "high", controls: [A03, A08],
116
171
  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.",
117
172
  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,
@@ -152,9 +207,10 @@ export const owaspRules = [
152
207
  fix: "Avoid eval and new Function. Parse data with JSON.parse or a real parser, and map names to functions with a lookup table.",
153
208
  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,
154
209
  // A method named eval is a definition, not a call (also TypeScript class methods, field test); $$eval is Playwright's;
155
- // "eval" inside a string is text.
156
- test: (l) => /\b(def|function|async)\s+eval\s*\(|^\s*((public|private|protected|static|override)\s+)*eval\s*\([^)]*\)\s*(:[^{=]+)?\{\s*$/.test(l) ? false
157
- : /(^|[^.\w$])eval\s*\(|\bnew Function\s*\(/.test(l.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, '""')) ? byInput(l) : false }),
210
+ // "eval" inside a string is text, also a string left open at the line end. A bare `eval(` ending the line is a
211
+ // wrapped call or method head: the joined statement decides (format robustness).
212
+ test: (l) => /\b(def|function|async)\s+eval\s*\(|^\s*((public|private|protected|static|override)\s+)*eval\s*\([^)]*\)\s*(:[^{=]+)?\{\s*$|^\s*eval\s*\(\s*$/.test(l) ? false
213
+ : /(^|[^.\w$])eval\s*\(|\bnew Function\s*\(/.test(l.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, '""').replace(/(["'])(?:\\.|(?!\1)[^\\])*$/, '""')) ? byInput(l) : false }),
158
214
  rule({ id: "xss.raw-html", title: "HTML inserted without escaping", status: "partial", severity: "medium", controls: [A05],
159
215
  fix: "Set text with textContent, let your framework escape values, or sanitise with DOMPurify before inserting HTML.",
160
216
  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,
@@ -9,3 +9,15 @@ export declare function functionsWithoutAuth(lines: string[], _shared?: string,
9
9
  /** A browser-exposed env name that holds a secret. Pure. */
10
10
  export declare function publicSecretName(n: string): boolean;
11
11
  export declare const stackRules: Rule[];
12
+ /** Auth route file: Partial on the line that handles POST, when neither this file, middleware nor package.json shows a
13
+ * rate limiter and the route doesn't hand sign-in to a provider that limits it. Pure. */
14
+ export declare function authWithoutRateLimit(lines: string[], _shared?: string, files?: Record<string, string>): Array<{
15
+ line: number;
16
+ status: "partial";
17
+ }>;
18
+ /** Root .gitignore: line 1 when the repo has a real .env file (not an example) and no ignore line mentions .env.
19
+ * Gap when one of those files holds a secret-looking value, Partial otherwise. Pure. */
20
+ export declare function envNotIgnored(lines: string[], _shared?: string, files?: Record<string, string>): {
21
+ line: number;
22
+ status: "gap" | "partial";
23
+ }[];
@@ -2,7 +2,7 @@ const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
2
2
  const DRAFT = { mappedBy: "beta", reviewedAt: "pending" };
3
3
  const GDPR32 = { framework: "gdpr", id: "Art. 32", title: "Security of processing" };
4
4
  const OW = (n, title) => ({ framework: "owasp-top10", id: `A${n}:2025`, title });
5
- const A01 = OW("01", "Broken Access Control"), A02 = OW("02", "Security Misconfiguration"), A04 = OW("04", "Cryptographic Failures");
5
+ const A01 = OW("01", "Broken Access Control"), A02 = OW("02", "Security Misconfiguration"), A04 = OW("04", "Cryptographic Failures"), A07 = OW("07", "Authentication Failures");
6
6
  const rule = (r) => ({ ...r, ...DRAFT });
7
7
  // Tables in schemas Supabase manages itself; RLS on these is not the app's job.
8
8
  const SYSTEM_SCHEMA = /^(auth|storage|realtime|extensions|supabase_\w+|pg_\w+|graphql\w*|vault)\./i;
@@ -65,7 +65,7 @@ export function functionsWithoutAuth(lines, _shared, files = {}) {
65
65
  // No bare PUBLIC_: it matches ordinary constants like PUBLIC_WITH_PRIVATE_AGENT.
66
66
  const PUBLIC_ENV = /\b(NEXT_PUBLIC|VITE|EXPO_PUBLIC|REACT_APP|NUXT_PUBLIC)_[A-Z0-9_]*/g;
67
67
  // Services whose API keys are always server-side secrets (widget and analytics keys are often public, so not these).
68
- const SECRET_SERVICE = /OPENAI|ANTHROPIC|CLAUDE|GEMINI|GOOGLE_AI|GROQ|MISTRAL|DEEPSEEK|COHERE|REPLICATE|ELEVENLABS|RESEND|SENDGRID|MAILGUN|POSTMARK|TWILIO|AWS|DATABASE|PINECONE|GITHUB_TOKEN/;
68
+ const SECRET_SERVICE = /OPENAI|ANTHROPIC|CLAUDE|GEMINI|GOOGLE_AI|GROQ|MISTRAL|DEEPSEEK|COHERE|REPLICATE|ELEVENLABS|RESEND|SENDGRID|MAILGUN|POSTMARK|TWILIO|AWS|DATABASE|PINECONE|GITHUB_TOKEN|AI_GATEWAY|V0_|XAI|OPENROUTER|FIREWORKS|TOGETHER|PERPLEXITY/;
69
69
  // Supabase projects keep their SQL in supabase/. Prisma or Drizzle migrations elsewhere talk to a database the
70
70
  // browser can't reach, so row level security isn't the point there (found in the field test: 263 false alarms).
71
71
  const SUPABASE_DIR = /(^|\/)supabase\//;
@@ -73,7 +73,9 @@ const SUPABASE_DIR = /(^|\/)supabase\//;
73
73
  const PUBLIC_BY_DESIGN = /ANON|PUBLISHABLE|_PK_|PUBLIC_KEY|FIREBASE|MAPS|MAPBOX|POSTHOG|SENTRY_DSN|ALGOLIA_SEARCH|SITE_KEY|MEASUREMENT_ID|URL$|_URL_/;
74
74
  // Words that make a name secret whatever service it belongs to. They win over the public list above:
75
75
  // NEXT_PUBLIC_FIREBASE_ADMIN_PRIVATE_KEY and VITE_POSTHOG_PERSONAL_API_KEY are secrets (review P14).
76
- const SECRET_WORD = /SECRET|PRIVATE|SERVICE_ROLE|SB_SECRET|PASSWORD|PERSONAL_(API_KEY|ACCESS_TOKEN|TOKEN)|(DATABASE|POSTGRES|DB|MONGO(DB)?|REDIS)_URL|CONNECTION_STRING/;
76
+ // Also Vercel's: a Blob read-write token, a Vercel API token, and an Edge Config connection string (its URL carries the
77
+ // read token), studied in vercel/storage.
78
+ const SECRET_WORD = /SECRET|PRIVATE|SERVICE_ROLE|SB_SECRET|PASSWORD|PERSONAL_(API_KEY|ACCESS_TOKEN|TOKEN)|(DATABASE|POSTGRES|DB|MONGO(DB)?|REDIS)_URL|CONNECTION_STRING|READ_WRITE|VERCEL_(API_)?TOKEN|(EDGE|GLOBAL)_CONFIG$/;
77
79
  /** A browser-exposed env name that holds a secret. Pure. */
78
80
  export function publicSecretName(n) {
79
81
  if (/FIREBASE\w*DATABASE_URL/.test(n))
@@ -84,13 +86,20 @@ export function publicSecretName(n) {
84
86
  return false;
85
87
  return SECRET_SERVICE.test(n) && /KEY|TOKEN/.test(n);
86
88
  }
89
+ // Route files for sign-in, sign-up, one-time codes and password resets (Next.js, SvelteKit, Remix, Express-style folders).
90
+ const AUTH_ROUTE = /(^|\/)(api\/|app\/|routes\/|pages\/api\/|server\/|functions\/)(.*\/)?[^/]*(login|log-in|signin|sign-in|signup|sign-up|(?<![\w-])register(?![\w-])|otp|one-time|magic-link|reset-password|forgot-password|password-reset|verify-code|2fa|mfa)[^/]*(\/[^/]+)?\.[cm]?[jt]s$/i;
91
+ const LIMITER = /rate.?limit|ratelimiter|throttl|slowDown|slow-down|@upstash\/ratelimit|rate-limiter-flexible|@arcjet|limiter\b|express-brute|bottleneck/i;
92
+ // Auth providers that limit sign-in attempts on their own servers: the route only hands the request over.
93
+ const PROVIDER_AUTH = /\bauth\.signInWith\w*\(|\bauth\.signUp\(|\bauth\.resetPasswordForEmail\(|@clerk\/|\bclerkClient\b|auth0|firebase\/auth|signInWithEmailAndPassword|cognito|@aws-amplify\/auth|stytch|workos/i;
94
+ const HANDLES_POST = /export\s+(async\s+)?(function|const)\s+POST\b|\b(app|router)\.post\s*\(|\bexport\s+const\s+actions\s*[:=]|method\s*===?\s*["']POST["']|export\s+(const|async function)\s+action\b|export\s*\{[^}]*\bPOST\b/;
87
95
  export const stackRules = [
88
96
  rule({ id: "supabase.rls-disabled", title: "Database table without row level security", status: "partial", severity: "high", controls: [GDPR32, A01],
89
97
  fix: "Add `alter table <name> enable row level security;` and a policy that limits each row to its owner, for example `using (auth.uid() = user_id)`.",
90
98
  note: "In Supabase, a table without row level security can be read and changed by anyone with your public anon key, which ships in every browser. Lintsure looks across every SQL file in supabase/. Marked Partial: it may be switched on outside these files, for example in the dashboard.", extensions: [".sql"],
91
99
  pathMatch: SUPABASE_DIR,
92
100
  sharedContext: true, // RLS is often switched on in a later migration (field test, 50 repos)
93
- fileTest: tablesWithoutRls }),
101
+ fileTest: tablesWithoutRls,
102
+ seenIn: [{ title: "CVE-2025-48757: missing row level security let anyone read or write the tables of apps generated with Lovable", url: "https://www.cve.org/CVERecord?id=CVE-2025-48757", check: "https://cveawg.mitre.org/api/cve/CVE-2025-48757", expect: ["Lovable", "Row-Level Security"] }] }),
94
103
  rule({ id: "supabase.policy-allows-all", title: "Database policy that lets everyone in", status: "partial", severity: "high", controls: [GDPR32, A01],
95
104
  fix: "Limit the policy to the right people, for example `using (auth.uid() = user_id)`. Keep `using (true)` only for data that is meant to be public, such as published posts.",
96
105
  note: "`using (true)` or `with check (true)` turns row level security on but lets every request through, so the table is as open as having no security at all. Marked Partial: public read access can be intended.", extensions: [".sql"],
@@ -129,5 +138,44 @@ export const stackRules = [
129
138
  note: "Public source maps let anyone read your original front-end code, comments and file structure, which makes other weaknesses easier to find. Marked Partial: some teams publish them on purpose.", extensions: CODE,
130
139
  // Only Next.js's browser source maps: Vite's sourcemap: true is normal in libraries and CLIs (field test: 5 false alarms).
131
140
  fileName: /^next\.config\./,
132
- test: (l) => /productionBrowserSourceMaps\s*:\s*true/.test(l) }),
141
+ test: (l) => /productionBrowserSourceMaps\s*:\s*true/.test(l),
142
+ patch: (l) => l.replace(/productionBrowserSourceMaps\s*:\s*true/, "productionBrowserSourceMaps: false") }),
143
+ rule({ id: "release.env-not-ignored", title: "Env files not kept out of git", status: "partial", severity: "medium", controls: [GDPR32, A02],
144
+ fix: "Add .env and .env.* to .gitignore (keep !.env.example if you share one), then check `git ls-files` for env files already committed and rotate any secret keys they held.",
145
+ note: "The project keeps settings in .env files, but .gitignore has no line for them, so the next `git add .` can publish them. Marked Gap when a file holds a secret-looking value (a key, token or password without a public prefix such as VITE_ or NEXT_PUBLIC_). Partial when only public settings are in it. Example and template files (.env.example) don't count.",
146
+ unseen: "Lintsure reads files, not git, so it can't tell whether the env file is already committed. Check with git ls-files.",
147
+ extensions: [""], fileName: /^\.gitignore$/, pathMatch: /^\.gitignore$/,
148
+ sharedFiles: /(^|\/)\.env(\.[\w.-]+)?$/,
149
+ insert: "# Local settings and keys (suggested by Lintsure)\n.env\n.env.*\n!.env.example\n",
150
+ fileTest: envNotIgnored }),
151
+ rule({ id: "auth.no-rate-limit", title: "Login or password reset with no rate limit in sight", status: "partial", severity: "medium", controls: [A07],
152
+ fix: "Limit how often one IP or account can try: a middleware limiter (for example @upstash/ratelimit, express-rate-limit or rate-limiter-flexible), or a firewall rule for this path. Lock or slow down after repeated failures.",
153
+ note: "Without a limit, anyone can try passwords, one-time codes or reset links as fast as they like (CWE-307). Partial: a firewall, an API gateway or your auth provider may already limit this outside the code.",
154
+ unseen: "Lintsure looked for a rate limiter in this file, middleware and package.json. It can't see limits set in a firewall, gateway or hosting dashboard.",
155
+ confidence: "medium",
156
+ extensions: CODE, pathMatch: AUTH_ROUTE, unlessPath: /\.(test|spec)\.[cm]?[jt]sx?$/,
157
+ sharedFiles: /(^|\/)(package\.json|middleware\.[cm]?[jt]s|vercel\.json)$/,
158
+ fileTest: authWithoutRateLimit }),
133
159
  ];
160
+ /** Auth route file: Partial on the line that handles POST, when neither this file, middleware nor package.json shows a
161
+ * rate limiter and the route doesn't hand sign-in to a provider that limits it. Pure. */
162
+ export function authWithoutRateLimit(lines, _shared, files = {}) {
163
+ const text = lines.join("\n");
164
+ if (LIMITER.test(text) || PROVIDER_AUTH.test(text) || Object.values(files).some((t) => LIMITER.test(t)))
165
+ return [];
166
+ const i = lines.findIndex((l) => HANDLES_POST.test(l));
167
+ return i < 0 ? [] : [{ line: i + 1, status: "partial" }];
168
+ }
169
+ // A secret-looking setting: the name says key, secret, token or password and it has no browser-public prefix.
170
+ const ENV_SECRET = /^\s*(?:export\s+)?(?!(?:VITE|NEXT_PUBLIC|REACT_APP|EXPO_PUBLIC|PUBLIC|NUXT_PUBLIC|GATSBY)_)(?![A-Z0-9_]*(?:PUBLISHABLE|ANON|PUBLIC))[A-Z0-9_]*(KEY|SECRET|TOKEN|PASSWORD|PRIVATE)[A-Z0-9_]*\s*=\s*["']?[^\s"'#]{8,}/m;
171
+ /** Root .gitignore: line 1 when the repo has a real .env file (not an example) and no ignore line mentions .env.
172
+ * Gap when one of those files holds a secret-looking value, Partial otherwise. Pure. */
173
+ export function envNotIgnored(lines, _shared, files = {}) {
174
+ const real = Object.entries(files).filter(([f]) => !/\.env\.(example|sample|template|dist|defaults?|schema)$/i.test(f) && !/(^|\/)(tests?|fixtures?|examples?|docs?)\//i.test(f));
175
+ if (!real.length)
176
+ return [];
177
+ // Lenient on purpose: any non-negated pattern naming .env counts (.env, .env*, *.env, **/.env.local, /.env).
178
+ if (lines.some((l) => { const t = l.trim(); return t && !t.startsWith("#") && !t.startsWith("!") && /\.env/.test(t); }))
179
+ return [];
180
+ return [{ line: 1, status: real.some(([, text]) => ENV_SECRET.test(text)) ? "gap" : "partial" }];
181
+ }
@@ -27,10 +27,12 @@ export const standardsForExisting = {
27
27
  };
28
28
  const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
29
29
  // Words for what a model sends back, so its output can be followed to a dangerous place on the same line.
30
- const MODEL_OUTPUT = /\b(completion|response|result|output|reply|answer|generation|llmResponse|aiResponse)\b[\w.?[\]]*\.(choices|content|text|output_text|message)\b|\.output_text\b|\bresult\.text\b/;
30
+ // Also the AI SDK's shapes: `const { text } = await generateText(...)` and a chat message part (`part.text`).
31
+ const MODEL_OUTPUT = /\b(completion|response|result|output|reply|answer|generation|llmResponse|aiResponse)\b[\w.?[\]]*\.(choices|content|text|output_text|message)\b|\.output_text\b|\bresult\.text\b|\bpart\.text\b|\bmessage\.content\b/;
31
32
  const SINKS = /\b(eval|exec|execSync|spawn|new Function)\s*\(|\.innerHTML\s*=|dangerouslySetInnerHTML|\.(query|execute|raw)\s*\(|\bsubprocess\.|\bos\.system\(/;
32
33
  // User input inside a system prompt: the model can't tell the app's instructions from the user's text.
33
- const USER_TEXT = /\$\{[^}]*\b(req\.(body|query|params)|request\.(json|form|args)|input|userInput|message|prompt|query|body)\b[^}]*\}|\{(user_input|user_message|query|message)\}/;
34
+ // An error's own text (`${error.message}`) is the app's, not the user's (vercel/ai study).
35
+ const USER_TEXT = /\$\{(?![^}]*\b(err|error|e|ex|exception)\.message\b)[^}]*\b(req\.(body|query|params)|request\.(json|form|args)|input|userInput|message|prompt|query|body)\b[^}]*\}|\{(user_input|user_message|query|message)\}/;
34
36
  const rule = (r) => ({ ...r, ...DRAFT });
35
37
  export const standardsRules = [
36
38
  // OWASP Top 10 for LLM Applications
@@ -44,7 +46,22 @@ export const standardsRules = [
44
46
  note: "A model's reply can be steered by anyone who can influence its input. Passing it straight to eval, a shell, a database query or innerHTML lets them run code or change data.",
45
47
  extensions: CODE,
46
48
  // Only in a file that calls an AI model: `nav.innerHTML = await response.text()` after a plain fetch is not model output (field test).
47
- fileTest: (lines) => (lines.some(isAiCall) ? lines.flatMap((l, i) => (MODEL_OUTPUT.test(l) && SINKS.test(l) ? [i + 1] : [])) : []) }),
49
+ // A useChat/useCompletion client file renders model output too, though the call itself is on the server.
50
+ fileTest: (lines) => (lines.some((l) => isAiCall(l) || /\buse(Chat|Completion|Object)\s*\(/.test(l)) ? lines.flatMap((l, i) => (MODEL_OUTPUT.test(l) && SINKS.test(l) ? [i + 1] : [])) : []) }),
51
+ // AI SDK agents loop through tool calls until a stop condition: one that never stops, or a huge step count, lets a
52
+ // single request run up cost without end (vercel/ai: isLoopFinished never stops on its own).
53
+ rule({ id: "llm.unbounded-agent-loop", title: "AI agent loop with no real step limit", status: "gap", severity: "medium", controls: [LLM06],
54
+ fix: "Stop the loop after a small number of steps, for example stopWhen: stepCountIs(10), and set maxOutputTokens.",
55
+ note: "Each step is another paid model call and maybe another tool run. With no limit, one request, or one prompt-injected document, can keep the agent going until something times out.",
56
+ extensions: CODE,
57
+ // A loop that never stops is a Gap; a very high step count is someone's choice, so Partial (field test: maxSteps 100, 200).
58
+ test: (l) => /\bstopWhen\s*:\s*isLoopFinished\s*\(\s*\)/.test(l) ? true : /\b(stepCountIs|isStepCount)\s*\(\s*\d{3,}\s*\)|\bmaxSteps\s*:\s*\d{3,}\b/.test(l) ? "partial" : false }),
59
+ // The client sending its own system prompt: anyone calling the route decides the AI's instructions.
60
+ rule({ id: "llm.client-controls-system", title: "The browser chooses the AI's system instructions", status: "gap", severity: "high", controls: [LLM01],
61
+ fix: "Build the system prompt on the server. Take only the user's messages from the request, and ignore any system text it sends.",
62
+ note: "Whoever calls the route can rewrite the rules the AI follows, including what it may say or which tools it may use (prompt injection, OWASP LLM01).",
63
+ extensions: CODE,
64
+ fileTest: (lines) => (lines.some((l) => isAiCall(l)) ? lines.flatMap((l, i) => (/\{[^}]*\bsystem\b[^}]*\}\s*=\s*(await\s+)?(req|request)\.(json\(\)|body)/.test(l) ? [i + 1] : [])) : []) }),
48
65
  rule({ id: "llm.no-output-limit", title: "AI call with no limit on how much it may generate", status: "partial", severity: "low", controls: [LLM06],
49
66
  fix: "Set a maximum output size on each call (max_tokens, maxTokens or max_output_tokens), and limit how often each user can call it.",
50
67
  note: "Without a limit, one request can run up a large bill or tie up the service (unbounded consumption). Marked Partial: the limit may be set in a shared client or wrapper.",