@lintsure/core 0.3.10 → 0.3.12

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/packs.js CHANGED
@@ -8,16 +8,24 @@ import { knowledge } from "./knowledge/index.js";
8
8
  import { rules } from "./rules/index.js";
9
9
  const PACK_NAME = /^@lintsure\/pack-[a-z0-9-]+$/;
10
10
  const loaded = new Set();
11
+ /** Packs registered in this process, as "id@version", for the policy fingerprint. */
12
+ export const packsLoaded = [];
13
+ /** Which pack added each framework, so a scan only uses the packs its own repo lists (the MCP server scans many repos). */
14
+ export const packFrameworks = new Map();
15
+ /** Packs loaded because some repo's lintsure.config.yaml listed them. Packs registered in code apply to every scan. */
16
+ export const configPacks = new Set();
11
17
  /** Adds a pack's frameworks, rules and mappings. Loading the same pack twice does nothing. */
12
18
  export function registerPack(p) {
13
19
  if (loaded.has(p.id))
14
20
  return;
15
21
  loaded.add(p.id);
22
+ packsLoaded.push(`${p.id}@${p.version ?? "0"}`);
16
23
  for (const [id, cs] of Object.entries(p.forExisting ?? {}))
17
24
  rules.find((r) => r.id === id)?.controls.push(...cs);
18
25
  rules.push(...p.rules);
19
26
  for (const k of p.knowledge) {
20
27
  knowledge.push(k);
28
+ packFrameworks.set(k.id, p.id);
21
29
  if (!ALL_FRAMEWORKS.includes(k.id))
22
30
  ALL_FRAMEWORKS.push(k.id);
23
31
  }
@@ -33,7 +41,9 @@ export async function loadPacks(names) {
33
41
  }
34
42
  try {
35
43
  const mod = await import(pathToFileURL(require.resolve(name)).href);
36
- registerPack((mod.default ?? mod.pack));
44
+ const pack = (mod.default ?? mod.pack);
45
+ registerPack(pack);
46
+ configPacks.add(pack.id);
37
47
  }
38
48
  catch {
39
49
  failed.push(name);
@@ -0,0 +1,3 @@
1
+ import type { Rule } from "./types.js";
2
+ /** The rules a described feature most likely runs into, best match first. Pure. */
3
+ export declare function checksFor(description: string, max?: number): Rule[];
@@ -0,0 +1,35 @@
1
+ // Before code is written: which Lintsure checks a planned feature is likely to meet, so the agent can avoid them.
2
+ // Plain word matching against what each rule is about, plus a few feature words. No model, same answer every time.
3
+ import { rules } from "./rules/index.js";
4
+ // Feature words people use, mapped to the rule id parts they usually lead to.
5
+ const TOPICS = [
6
+ [/\b(log ?in|sign ?(in|up)|auth\w*|password|session|account|oauth|sso)\b/i, ["session", "jwt", "password", "csrf", "cookie", "redirect", "secret"]],
7
+ [/\b(upload\w*|files?|images?|attachments?|download\w*)\b/i, ["upload", "path"]],
8
+ [/\b(pay\w*|stripe|checkout|billing|cards?|invoices?)\b/i, ["secret", "webhook", "transport", "pii"]],
9
+ [/\b(ai|llm|gpt|claude|chat\w*|prompts?|agents?|openai|anthropic|model)\b/i, ["ai", "llm"]],
10
+ [/\b(databases?|sql|quer\w*|supabase|postgres|tables?|prisma|mongo\w*)\b/i, ["sql", "supabase", "nosql", "mass"]],
11
+ [/\b(users?|profiles?|emails?|personal|customers?|analytics|tracking|gdpr)\b/i, ["pii", "gdpr"]],
12
+ [/\b(webhooks?|fetch\w*|urls?|proxy|crawl\w*|scrap\w*|preview)\b/i, ["ssrf", "transport", "redirect"]],
13
+ [/\b(api|endpoints?|routes?|server|backend|handlers?)\b/i, ["cors", "error", "sql", "mass", "config"]],
14
+ [/\b(shell|commands?|exec\w*|scripts?|cli|deploy\w*|ci|github actions?|workflows?)\b/i, ["cmd", "ci", "deps", "code"]],
15
+ [/\b(hooks?|mcp|cursor|claude code|agent config)\b/i, ["agent"]],
16
+ [/\b(env\w*|keys?|secrets?|tokens?|config\w*)\b/i, ["secret", "release", "config"]],
17
+ [/\b(html|render\w*|templates?|markdown|comments?|rich text)\b/i, ["xss", "template"]],
18
+ [/\b(mobile|android|ios|react native|expo)\b/i, ["mobile"]],
19
+ ];
20
+ const STOP = new Set(["with", "that", "this", "from", "into", "user", "users", "make", "build", "want", "need", "should", "will", "page", "feature", "add", "new", "the", "and", "for", "mode", "toggle", "button", "show", "list", "screen", "simple", "dark", "light"]);
21
+ /** The rules a described feature most likely runs into, best match first. Pure. */
22
+ export function checksFor(description, max = 8) {
23
+ const text = description.slice(0, 2000);
24
+ const parts = new Set(TOPICS.filter(([re]) => re.test(text)).flatMap(([, p]) => p));
25
+ const words = new Set((text.toLowerCase().match(/[a-z]{4,}/g) ?? []).filter((w) => !STOP.has(w)));
26
+ const scored = rules.map((r) => {
27
+ const idParts = r.id.split(/[.-]/);
28
+ let s = idParts.some((p) => parts.has(p)) ? 3 : 0;
29
+ for (const w of new Set(`${r.title} ${r.id}`.toLowerCase().match(/[a-z]{4,}/g) ?? []))
30
+ if (words.has(w))
31
+ s += 2;
32
+ return { r, s: s + (s && r.severity === "high" ? 1 : 0) };
33
+ });
34
+ return scored.filter((x) => x.s > 0).sort((a, b) => b.s - a.s || a.r.id.localeCompare(b.r.id)).slice(0, max).map((x) => x.r);
35
+ }
@@ -0,0 +1,32 @@
1
+ export type Reach = {
2
+ status: "entry" | "reachable" | "unreachable" | "unknown";
3
+ via?: string[];
4
+ };
5
+ export interface Graph {
6
+ importers: Map<string, Set<string>>;
7
+ imports: Map<string, Set<string>>;
8
+ entries: Set<string>;
9
+ unresolved: Map<string, string[]>;
10
+ /** Filled on first use: for each reached file, the file that imports it on a shortest path from an entry. */
11
+ parent?: Map<string, string>;
12
+ unresolvedNames?: Set<string>;
13
+ }
14
+ /** Literal specifiers a file imports. Pure. */
15
+ export declare function specifiers(text: string): string[];
16
+ export declare function stripJsonComments(text: string): string;
17
+ /** Path aliases from a tsconfig.json text (comments allowed): baseUrl and paths, as [prefix, targets] pairs. Pure. */
18
+ export declare function tsAliases(text: string | null, root?: string): {
19
+ root: string;
20
+ baseUrl: string | null;
21
+ paths: [string, string[], boolean][];
22
+ };
23
+ /** The project file a specifier points at, "external" for a package, or null when it looks local but can't be found. Pure. */
24
+ export declare function resolveSpec(from: string, spec: string, files: Set<string>, alias: ReturnType<typeof tsAliases>): string | "external" | null;
25
+ /** Files a project starts from that no code imports: package.json main/module/bin/exports, and scripts an HTML page
26
+ * loads with <script src>. Paths come back relative to the project root. Pure. */
27
+ export declare function declaredEntries(pkgs: Record<string, string>, html: Record<string, string>, files: Set<string>): string[];
28
+ /** Builds the import graph and the entry points from the project's JS/TS files. Pure. */
29
+ export declare function buildGraph(files: Record<string, string>, tsconfigs?: string | null | Record<string, string>, pkgDirs?: string[], extraEntries?: string[]): Graph;
30
+ /** Whether an entry point reaches this file, with the shortest chain entry -> ... -> file. "unknown" when nothing
31
+ * reaches it but an unresolved import somewhere could be pointing at it (same file name). Pure. */
32
+ export declare function reachOf(g: Graph, file: string): Reach;
@@ -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
+ }
@@ -18,8 +18,9 @@ export function toBaseline(r, created) {
18
18
  export function parseAccepted(text) {
19
19
  const out = [];
20
20
  for (const raw of text.split(/\r?\n/)) {
21
- const line = raw.replace(/\s+#.*$/, "").replace(/^#.*$/, "");
22
- const m = line.match(/^(\s*)(-\s+)?([a-z_]+)\s*:\s*(.*)$/);
21
+ const hash = raw.search(/(^|\s)#/); // linear: a long run of spaces can't make it backtrack
22
+ const line = hash < 0 ? raw : raw.slice(0, hash);
23
+ const m = line.match(/^([ \t]*)(-[ \t]+)?([a-z_]+)[ \t]*:(.*)$/);
23
24
  if (!m)
24
25
  continue;
25
26
  if (m[2])
@@ -1,5 +1,6 @@
1
1
  import { owaspForExisting, owaspRules } from "./owasp.js";
2
2
  import { stackRules } from "./stack.js";
3
+ import { moreRules } from "./more.js";
3
4
  import { craForExisting, craRules } from "./cra.js";
4
5
  import { standardsForExisting, standardsRules } from "./standards.js";
5
6
  const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
@@ -145,7 +146,9 @@ export const rules = [
145
146
  fix: "Send an internal user ID instead of the email or name. If personal data must go there, list the tool as a processor.",
146
147
  note: "Analytics vendors keep what you send them. Personal data there needs a lawful basis and a processing agreement.",
147
148
  extensions: CODE,
148
- 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),
149
+ // Also a bare track("event", { ... }), the way @vercel/analytics and similar SDKs are imported and called.
150
+ 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)
151
+ || /(^|[^.\w])track\s*\(\s*["'`][^"'`]+["'`]\s*,\s*\{/.test(l)) && PII.test(l),
149
152
  ...DRAFT,
150
153
  },
151
154
  {
@@ -193,6 +196,8 @@ export const rules = [
193
196
  note: "With checks off, anyone on the network path can read or change the traffic.",
194
197
  extensions: [...CODE, ".env"],
195
198
  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
199
+ // Only the switches with one safe opposite; env vars and ssl modes need a person.
200
+ 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"),
196
201
  ...DRAFT,
197
202
  },
198
203
  {
@@ -263,6 +268,7 @@ export const rules = [
263
268
  return /\b(res|response|reply|ctx|cookies?)\.(cookie|set|setCookie)\s*\(|Set-Cookie|\bcookie\s*:\s*\{|cookieOptions|serialize\(|SESSION_COOKIE/i.test(near)
264
269
  && !/csrf|xsrf/i.test(near) && !/\b(smtp|createTransport|nodemailer|ignoreTLS|requireTLS)\b/i.test(near) ? [i + 1] : [];
265
270
  }),
271
+ 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"),
266
272
  ...DRAFT,
267
273
  },
268
274
  {
@@ -286,7 +292,12 @@ const AI_CALL = new RegExp([
286
292
  /\b(openai|anthropic|client)\.(chat\.completions|responses|messages|completions)\.create\s*\(/.source,
287
293
  /\b\w+\.chat\.completions\.create\s*\(/.source,
288
294
  /\.generateContent(Stream)?\s*\(/.source,
289
- /\b(generateText|streamText|generateObject|streamObject)\s*\(/.source,
295
+ // Vercel AI SDK, including the experimental_ forms and its agent class (studied in vercel/ai).
296
+ /(?<![A-Za-z])(experimental_)?(generateText|streamText|generateObject|streamObject)\s*\(/.source,
297
+ // Its image, speech, video and transcription calls only in the SDK's own shape: apps name their own wrappers
298
+ // generateImage() or transcribe() too (field test 2026-11-18: 65 false gains before this).
299
+ /(?<![A-Za-z.])experimental_(generateImage|generateSpeech|generateVideo|transcribe)\s*\(|(?<![A-Za-z.])(generateImage|generateSpeech|generateVideo|transcribe)\s*\(\s*\{\s*model\s*:/.source,
300
+ /\bnew\s+(ToolLoopAgent|Experimental_Agent)\s*\(/.source,
290
301
  /\b(model|clf|classifier|pipeline)\.(predict|predict_proba|invoke|generate)\s*\(/.source,
291
302
  /\b(chain|llm|chatModel|agent|runnable)\w*\.(invoke|stream|batch)\s*\(/.source,
292
303
  // A provider URL counts only inside a request call, not where it's stored in a constant.
@@ -306,7 +317,8 @@ export const mediaModelCalls = (lines) => lines.some((l) => MEDIA_MODEL.test(l))
306
317
  // Whole words only: "banner" is not "ban" (field test, 139 repos).
307
318
  // Letters may not touch the word, but underscores may: loan_denied counts, banner doesn't.
308
319
  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;
309
- const LOGGED = /\b(logger|log|logging|audit|auditLog|console)\.\w+\s*\(|\binsert\w*\s*\(|\.save\s*\(/;
320
+ // The AI SDK's own record hooks count too: onFinish saving the chat, or telemetry switched on (vercel/ai docs).
321
+ 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*\{/;
310
322
  rules.push({
311
323
  id: "ai.automated-decision",
312
324
  title: "AI makes a decision about a person with no human check in the code",
@@ -356,7 +368,7 @@ rules.push({
356
368
  fix: "Mark generated media as AI-made in a machine-readable way (for example C2PA metadata) and label deepfakes for viewers.",
357
369
  note: "Marked Partial: you may already add marking after this call. Confirm it does.",
358
370
  extensions: CODE,
359
- 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),
371
+ 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),
360
372
  // Also: a generic AI call (e.g. generateContent) in a file that names an image, voice or video model.
361
373
  fileTest: mediaModelCalls,
362
374
  ...DRAFT,
@@ -379,6 +391,7 @@ rules.push({
379
391
  for (const r of rules)
380
392
  r.controls.push(...(owaspForExisting[r.id] ?? []));
381
393
  rules.push(...owaspRules);
394
+ rules.push(...moreRules);
382
395
  // Supabase, Next.js and Vite: open databases and secrets reaching the browser.
383
396
  rules.push(...stackRules);
384
397
  for (const r of rules)
@@ -0,0 +1,4 @@
1
+ import type { Rule } from "../types.js";
2
+ /** Lines that start a web-socket server in a file with no origin check (verifyClient, an origin test, allowRequest). Pure. */
3
+ export declare function wsNoOrigin(lines: string[]): number[];
4
+ export declare const moreRules: Rule[];
@@ -0,0 +1,70 @@
1
+ const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
2
+ const JS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
3
+ const MARKUP = [...CODE, ".html", ".vue", ".svelte", ".astro"];
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"), A04 = A("04", "Cryptographic Failures"), A06 = A("06", "Insecure Design"), A07 = A("07", "Authentication Failures"), A08 = A("08", "Software or Data Integrity Failures");
7
+ const rule = (r) => ({ ...r, ...DRAFT });
8
+ // A record looked up by an id from the request, with nothing on or near the line that ties it to the signed-in user.
9
+ const BY_REQUEST_ID = /\b(findUnique|findUniqueOrThrow|findFirst|findById|findByPk|findOne|findOneBy|get_object_or_404)\s*\([^;]*\b(req\.(params|query|body)|request\.(args|view_args|json)|params)\b[^;]*\bid\b|\.objects\.get\([^)]*\b(id|pk)\s*=\s*request\./;
10
+ const OWNER = /\b(userId|user_id|ownerId|owner_id|owner|tenantId|tenant_id|orgId|org_id|accountId|account_id|req\.user|request\.user|session\.user|currentUser|authorize|can\(|policy|permission)\b/;
11
+ // A web-socket server that never looks at where the connection came from.
12
+ const WS_SERVER = /\bnew\s+(WebSocketServer|WebSocket\.Server|WSServer)\s*\(|\bnew\s+Server\s*\([^)]*\bcors\b|\bio\s*=\s*new\s+Server\s*\(/;
13
+ /** Lines that start a web-socket server in a file with no origin check (verifyClient, an origin test, allowRequest). Pure. */
14
+ export function wsNoOrigin(lines) {
15
+ const text = lines.join("\n");
16
+ if (/\bverifyClient\b|\borigin\b|\ballowRequest\b|\bnoServer\s*:\s*true/.test(text))
17
+ return [];
18
+ return lines.flatMap((l, i) => (WS_SERVER.test(l) ? [i + 1] : []));
19
+ }
20
+ // Both sides of a comparison look like a secret value: a signature, token or key against an expected one.
21
+ const SECRETISH = String.raw `[\w.$\[\]"'-]*(?:signature|token|secret|hmac|digest|api_?key|apikey|password_hash)[\w.\[\]"'-]*`;
22
+ const UNSAFE_COMPARE = new RegExp(String.raw `(?<![\w.])${SECRETISH}\s*(?:===?|!==?)\s*${SECRETISH}`, "i");
23
+ export const moreRules = [
24
+ rule({ id: "authz.no-owner-check", title: "Record loaded by an id from the request, with no owner check", status: "partial", severity: "high", controls: [A01],
25
+ fix: "Look the record up by its id and the signed-in user (or tenant) together, for example where: { id, userId: req.user.id }, or check the owner before returning it.",
26
+ note: "Anyone who changes the id in the URL can read or change someone else's record (insecure direct object reference, CWE-639).", extensions: CODE,
27
+ unseen: "Lintsure can't see checks done in middleware or another function, so the owner may already be verified.",
28
+ confidence: "medium",
29
+ test: (l) => BY_REQUEST_ID.test(l) && !OWNER.test(l),
30
+ unlessNear: OWNER }),
31
+ rule({ id: "jwt.no-algorithm-pin", title: "Token verified without saying which algorithm is allowed", status: "partial", severity: "medium", controls: [A07],
32
+ fix: "Pass the algorithm you sign with, for example jwt.verify(token, key, { algorithms: [\"RS256\"] }), or algorithms=[\"HS256\"] in PyJWT.",
33
+ note: "Without a fixed list, some library versions accept a token signed with a different algorithm than you meant, for example one signed with your public key (CWE-347).", extensions: CODE,
34
+ test: (l) => /\bjwt\.verify\(\s*[^,()]+,\s*[^,()]+\)/.test(l) || /\bjwt\.decode\(\s*[\w.]+\s*,\s*[\w."']+\s*\)/.test(l) }),
35
+ rule({ id: "jwt.weak-secret", title: "Token signed with a short secret written in the code", status: "gap", severity: "high", controls: [A04, A07],
36
+ fix: "Read the signing key from the environment or a secret store, and make it at least 32 random bytes.",
37
+ note: "Anyone who reads the code, or guesses a short key, can sign their own login tokens (CWE-798, CWE-521).", extensions: CODE,
38
+ test: (l) => /\bjwt\.(sign|verify|encode|decode)\(\s*(?:\{[^{}]*\}|[^,(){}]+)\s*,\s*["'][^"']{1,31}["']/.test(l) }),
39
+ rule({ id: "proto.pollution", title: "Request data deep-merged into an object", status: "gap", severity: "high", controls: [A08],
40
+ fix: "Copy only the fields you expect, or validate the body with a schema first. If you must merge, drop __proto__, constructor and prototype keys.",
41
+ note: "A body like {\"__proto__\": {\"isAdmin\": true}} can change every object in the app (prototype pollution, CWE-1321).", extensions: JS,
42
+ test: (l) => /(?:\b(?:_\.merge|_\.mergeWith|_\.defaultsDeep|deepmerge|deepMerge|mergeDeep|merge)\s*\(|\$\.extend\(\s*true\s*,)[^;]*\b(req\.(body|query)|request\.(body|json))/.test(l) }),
43
+ rule({ id: "html.tabnabbing", title: "Link opens a new tab without rel=\"noopener\"", status: "partial", severity: "low", controls: [A06],
44
+ fix: "Add rel=\"noopener noreferrer\" to links with target=\"_blank\".",
45
+ note: "Current browsers already treat target=\"_blank\" as noopener, so this matters mainly for older browsers and webviews: the opened page could redirect your tab (CWE-1022).", extensions: MARKUP,
46
+ test: (l) => /\btarget\s*=\s*\{?\s*["']_blank["']/.test(l) && !/\brel\s*=\s*\{?\s*["'][^"']*\bno(opener|referrer)\b/.test(l) }),
47
+ rule({ id: "ws.no-origin-check", title: "Web-socket server with no origin check", status: "partial", severity: "medium", controls: [A01],
48
+ fix: "Check the Origin header when a connection opens (verifyClient in ws, cors.origin or allowRequest in socket.io) and allow only your own sites.",
49
+ note: "Browsers don't stop other sites opening a web socket to you, so a page on any site can use a signed-in visitor's cookies against it (cross-site WebSocket hijacking, CWE-1385).", extensions: JS,
50
+ unseen: "Lintsure can't see an origin check done in a proxy or an upgrade handler in another file.",
51
+ fileTest: wsNoOrigin }),
52
+ rule({ id: "k8s.privileged", title: "Container runs privileged or shares the host", status: "gap", severity: "high", controls: [A02],
53
+ fix: "Remove privileged, hostNetwork, hostPID and hostIPC, set allowPrivilegeEscalation: false, and run as a non-root user.",
54
+ note: "A privileged container, or one sharing the host's network or processes, can take over the machine it runs on if it is broken into (CWE-250).", extensions: [".yml", ".yaml"],
55
+ test: (l) => /^\s*-?\s*(privileged|allowPrivilegeEscalation|hostNetwork|hostPID|hostIPC)\s*:\s*true\b/.test(l) || /^\s*-?\s*runAsUser\s*:\s*0\s*$/.test(l) }),
56
+ rule({ id: "cloud.public-bucket", title: "Storage bucket open to the public", status: "gap", severity: "high", controls: [A01],
57
+ fix: "Keep the bucket private and block public access. Share single files with short-lived signed URLs instead.",
58
+ note: "Anyone on the internet can list or download what's in a public bucket, and with write access, replace it (CWE-284).", extensions: [".tf", ".json", ".yml", ".yaml", ...CODE],
59
+ test: (l) => /\bacl\s*[:=]\s*["']public-read(-write)?["']/i.test(l) || /\bblock_?public_?(acls|policy)\s*[:=]\s*false\b/i.test(l) || /\bpublicReadAccess\s*:\s*true\b/.test(l) || /"Principal"\s*:\s*"\*"/.test(l) && /s3:|"Effect"\s*:\s*"Allow"/.test(l) }),
60
+ rule({ id: "crypto.unsafe-compare", title: "Secret compared with == instead of a constant-time check", status: "partial", severity: "medium", controls: [A04],
61
+ fix: "Use crypto.timingSafeEqual (Node) or hmac.compare_digest (Python) to compare signatures, tokens and keys.",
62
+ note: "A plain comparison stops at the first wrong character, so response times can leak the secret bit by bit (timing attack, CWE-208).", extensions: CODE,
63
+ confidence: "medium",
64
+ test: (l) => UNSAFE_COMPARE.test(l) && !/\b(null|undefined|typeof|length)\b|["']\s*\)?\s*$/.test(l.replace(/\/\/.*$/, "").split(/===?|!==?/)[1] ?? ""),
65
+ unlessNear: /timingSafeEqual|compare_digest|safeCompare|constantTime|secureCompare/ }),
66
+ rule({ id: "graphql.introspection", title: "GraphQL introspection switched on", status: "partial", severity: "low", controls: [A02],
67
+ fix: "Turn introspection off in production, for example introspection: process.env.NODE_ENV !== \"production\".",
68
+ note: "Introspection hands anyone a full map of your API, including fields you never meant to advertise (CWE-200).", extensions: CODE,
69
+ test: (l) => /\bintrospection\s*:\s*true\b/.test(l) }),
70
+ ];
@@ -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[];