@lintsure/core 0.3.13 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { AGENT_CONFIG, poisonedDescription } from "./owasp.js";
1
2
  const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
2
3
  const JS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
3
4
  const MARKUP = [...CODE, ".html", ".vue", ".svelte", ".astro"];
@@ -13,14 +14,280 @@ const WS_SERVER = /\bnew\s+(WebSocketServer|WebSocket\.Server|WSServer)\s*\(|\bn
13
14
  /** Lines that start a web-socket server in a file with no origin check (verifyClient, an origin test, allowRequest). Pure. */
14
15
  export function wsNoOrigin(lines) {
15
16
  const text = lines.join("\n");
16
- if (/\bverifyClient\b|\borigin\b|\ballowRequest\b|\bnoServer\s*:\s*true/.test(text))
17
+ // `origin: "*"` and `origin: true` name the origin without checking it, so they don't count as a check.
18
+ if (/\bverifyClient\b|\borigin\b|\ballowRequest\b|\bnoServer\s*:\s*true/.test(text.replace(/\borigin\s*:\s*(["'`]\*["'`]|true\b)/g, "")))
17
19
  return [];
18
20
  return lines.flatMap((l, i) => (WS_SERVER.test(l) ? [i + 1] : []));
19
21
  }
20
22
  // Both sides of a comparison look like a secret value: a signature, token or key against an expected one.
21
23
  const SECRETISH = String.raw `[\w.$\[\]"'-]*(?:signature|token|secret|hmac|digest|api_?key|apikey|password_hash)[\w.\[\]"'-]*`;
22
24
  const UNSAFE_COMPARE = new RegExp(String.raw `(?<![\w.])${SECRETISH}\s*(?:===?|!==?)\s*${SECRETISH}`, "i");
25
+ // A file that registers tools an AI agent can call over MCP (TypeScript or Python SDKs).
26
+ const MCP_TOOL = /\.registerTool\(|\.tool\(\s*["'`]|@(mcp|server|app)\.tool\b|setRequestHandler\(\s*CallToolRequestSchema/;
27
+ const SHELL = /(?<![.\w$])(execSync|exec|execFile|execFileSync|spawn|spawnSync)\s*\(|\b(child_process|childProcess|cp)\.(execSync|exec|execFile|execFileSync|spawn|spawnSync)\s*\(|\bos\.(system|popen)\s*\(|\bsubprocess\.\w+\s*\([^)]*shell\s*=\s*True/;
28
+ const ENV_SECRET = /\b(process\.env|os\.environ(\.get)?|os\.getenv)\s*[.[(]\s*["']?\w*(TOKEN|SECRET|API_?KEY|PASSWORD|CREDENTIALS?)\w*/i;
29
+ /** Lines matching re in a file that registers MCP tools; nothing in other files. Pure. */
30
+ export function inMcpServer(lines, re) {
31
+ if (!lines.some((l) => MCP_TOOL.test(l)))
32
+ return [];
33
+ return lines.flatMap((l, i) => (re.test(l) && !/^\s*(\/\/|#)/.test(l) ? [i + 1] : []));
34
+ }
35
+ const LLM03 = { framework: "owasp-llm", id: "LLM03:2026", title: "Excessive Agency" };
36
+ const LLM04 = { framework: "owasp-llm", id: "LLM04:2026", title: "Supply Chain" };
37
+ const LLM01 = { framework: "owasp-llm", id: "LLM01:2026", title: "Prompt Injection" };
38
+ /** MCP config: a server run from a version that can change after you approved it (Partial), or reached over plain HTTP (Gap). Pure.
39
+ * shortcut: reads npx-style args only ("-y", "pkg"); add uvx and docker image tags when a field test shows them. */
40
+ export function mcpConfigUnsafe(lines) {
41
+ if (!lines.some((l) => /"(mcpServers|servers|context_servers)"\s*:/.test(l)))
42
+ return [];
43
+ const out = [];
44
+ lines.forEach((l, i) => {
45
+ if (/"(url|serverUrl|endpoint)"\s*:\s*"http:\/\/(?!localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|host\.docker\.internal)/.test(l)) {
46
+ out.push({ line: i + 1, status: "gap" });
47
+ return;
48
+ }
49
+ if (/@latest"/.test(l)) {
50
+ out.push({ line: i + 1, status: "partial" });
51
+ return;
52
+ }
53
+ const yes = /"(-y|--yes)"\s*,?\s*(.*)$/.exec(l);
54
+ if (!yes)
55
+ return;
56
+ const same = /^"([^"]+)"/.exec(yes[2].trim()), next = /^\s*"([^"]+)"/.exec(lines[i + 1] ?? "");
57
+ const pkg = same?.[1] ?? next?.[1];
58
+ if (pkg && /^(@[\w.-]+\/)?[\w.-]+$/.test(pkg))
59
+ out.push({ line: same ? i + 1 : i + 2, status: "partial" });
60
+ });
61
+ return out;
62
+ }
63
+ const DOCKERFILE = /^(Dockerfile|Containerfile)|\.Dockerfile$/i;
64
+ const NATIVE = [".java", ".kt", ".swift", ".go", ".dart"];
65
+ // An IV or nonce that is the same for every message: zero bytes or fixed text. Reusing one with the same key breaks
66
+ // AES-GCM outright and leaks patterns in CBC. A buffer that is filled with random bytes on the next lines is fine (unlessNear).
67
+ const STATIC_IV = /\b(iv|IV|nonce|initVector|initializationVector)\s*[:=]\s*(Buffer\.alloc\(\s*\d+\s*(,\s*0\s*)?\)|Buffer\.from\(\s*["'][^"']+["'])|\b(iv|nonce)\s*=\s*(b["'][^"']+["']|bytes\(\s*\d+\s*\))|\b(Iv|GCM)ParameterSpec\(\s*(\d+\s*,\s*)?(new\s+byte\[\d+\]|ByteArray\(\d+\)|"[^"]+"\.(getBytes|toByteArray)\()|\b(iv|nonce)\s*:?=\s*\[\]byte\("[^"]+"\)/;
68
+ /** Key sizes and work factors below what current guidance accepts. Pure. */
69
+ export function weakCryptoParameter(l) {
70
+ // PBKDF2 is also used to derive cache keys and ids, where the round count doesn't matter: Gap only when a password is named.
71
+ const kdf = () => (/pass(word|wd|phrase)?/i.test(l) ? true : "partial");
72
+ if (/^\s*(\/\/|#|\*)/.test(l))
73
+ return false;
74
+ // PBKDF2 under 10,000 rounds (OWASP asks for 600,000 with SHA-256; a four-digit count is far off any guidance).
75
+ if (/\bpbkdf2(Sync)?\(\s*[^,]+,\s*[^,]+,\s*\d{1,4}\s*,|\bpbkdf2_hmac\(\s*[^,]+,\s*[^,]+,\s*[^,]+,\s*\d{1,4}\s*[,)]|\bPBEKeySpec\(\s*[^,]+,\s*[^,]+,\s*\d{1,4}\s*,/.test(l))
76
+ return kdf();
77
+ if (/\bPBKDF2\w*\(/.test(l) && /\biterations\s*=\s*\d{1,4}\s*[,)]/.test(l))
78
+ return kdf();
79
+ // bcrypt below 10 rounds.
80
+ if (/\bbcrypt\.(hash|hashSync|genSalt|genSaltSync)\(\s*(?:[^,()]+,\s*)?[1-9]\s*[,)]|\bgensalt\(\s*(?:rounds\s*=\s*)?[1-9]\s*\)/.test(l))
81
+ return true;
82
+ // RSA keys under 2048 bits.
83
+ return /\bmodulusLength\s*:\s*(512|768|1024)\b|\bkey_size\s*=\s*(512|768|1024)\b|\brsa\.GenerateKey\(\s*[^,]+,\s*(512|768|1024)\s*\)|\b\w*([Kk]eyGen|kpg|[Gg]enerator)\w*\.initialize\(\s*(512|768|1024)\s*[,)]|\bopenssl\s+genrsa\b[^|;\n]*\s(512|768|1024)\b/.test(l);
84
+ }
85
+ /** Android release build that can be debugged: the manifest flag, or `debuggable true` inside the release block of build.gradle. Pure. */
86
+ export function debuggableBuild(lines) {
87
+ return lines.flatMap((l, i) => {
88
+ if (/android:debuggable\s*=\s*"true"/.test(l))
89
+ return [i + 1];
90
+ if (!/\b(isDebuggable\s*=\s*true|debuggable\s+true|debuggable\s*=\s*true)\b/.test(l))
91
+ return [];
92
+ const block = lines.slice(Math.max(0, i - 12), i).reverse().find((x) => /^\s*(release|debug|getByName\("(release|debug)"\)|named\("(release|debug)"\))\s*\{/.test(x)) ?? "";
93
+ return /release/.test(block) ? [i + 1] : [];
94
+ });
95
+ }
96
+ const GDPR = (id, title) => ({ framework: "gdpr", id, title });
97
+ /** A line that declares a stored field with one of these names: SQL column, Prisma, Mongoose, Sequelize, TypeORM, Django,
98
+ * SQLAlchemy. A TypeScript type (`cvv: string`) describes a form value, not storage, so it doesn't count. Pure. */
99
+ export function storedField(names) {
100
+ const re = new RegExp(String.raw `\b(${names})\b["']?\s*(:\s*(\{\s*type\s*:\s*)?(String|Number|Boolean|DataTypes\.\w+|Sequelize\.\w+|Schema\.Types\.\w+)\b|\s+(VARCHAR|CHAR|TEXT|INT|INTEGER|SMALLINT|BOOLEAN|JSONB?)\b|\s+(String|Int|Boolean|Json)\??\s*(@|$)|\s*=\s*(models|db|sa|sqlalchemy)\.\w+\(|\s*=\s*(mapped_column|Column)\(|\s*:\s*Mapped\[)`, "i");
101
+ return (l) => !/^\s*(\/\/|#|--|\*)/.test(l) && (re.test(l) || (/@(Column|Prop)\(/.test(l) && new RegExp(String.raw `\b(${names})\b`, "i").test(l))) && (/@(Column|Prop)\(/.test(l) || !/:\s*(string|number|boolean)\b/.test(l));
102
+ }
103
+ const CARD_CODE = storedField("cvv2?|cvc2?|card_?security_?code|card_?verification_?(code|value)");
104
+ const SPECIAL = storedField("religion|religious_?belief|ethnicity|ethnic_?origin|sexual_?orientation|political_?(affiliation|opinion|party)|trade_?union(_?membership)?|hiv_?status|genetic_?data");
105
+ const CONSENT_WORD = /consent|marketing|newsletter|subscribe|opt[-_ ]?in|promotional/i;
106
+ /** A consent or marketing checkbox that starts ticked, or its state that starts as true. Pure. */
107
+ export function consentPreticked(lines) {
108
+ return lines.flatMap((l, i) => {
109
+ // State that starts true for a consent value; a flag that only shows the banner is not consent.
110
+ const st = /\[\s*(\w+)\s*,\s*set\w+\s*\]\s*=\s*useState(<[^>]*>)?\(\s*true\s*\)/.exec(l);
111
+ if (st && CONSENT_WORD.test(st[1]) && !/show|open|visible|banner|modal|dialog|loading|seen/i.test(st[1]))
112
+ return [i + 1];
113
+ // `checked={value}` is controlled state; only a bare attribute or a literal true pre-ticks the box.
114
+ const attrs = l.replace(/\b(defaultChecked|checked)\s*=\s*\{(?!\s*true\s*\})[^}]*\}/g, "");
115
+ // A variable or arrow parameter named `checked` (`const checked = ...`, `checked => ...`) is code, not the attribute.
116
+ if (/^\s*(const|let|var|return|if)\b/.test(l) || !/(^|\s)(defaultChecked|checked)(\s*=\s*(\{\s*true\s*\}|["'](checked|true)["'])(\s|\/?>|$)|(?!\s*=)(\s|\/?>|$))/.test(attrs))
117
+ return [];
118
+ const near = lines.slice(Math.max(0, i - 4), i + 5).join("\n");
119
+ return /type\s*=\s*["']checkbox["']|<Checkbox\b/.test(near) && CONSENT_WORD.test(near) ? [i + 1] : [];
120
+ });
121
+ }
122
+ const IAC = [".tf", ".json", ".yml", ".yaml"];
123
+ // Ports that should never face the internet: remote login, databases, caches, search and the Docker API.
124
+ const ADMIN_PORTS = [22, 23, 3389, 5900, 1433, 1521, 3306, 5432, 6379, 9200, 9300, 11211, 27017, 5984, 2375, 2376];
125
+ const OPEN_CIDR = /cidr_blocks\s*=\s*\[[^\]]*"0\.0\.0\.0\/0"|ipv6_cidr_blocks\s*=\s*\[[^\]]*"::\/0"|\bCidrIp(v6)?\s*:\s*["']?(0\.0\.0\.0\/0|::\/0)|source_ranges\s*=\s*\[[^\]]*"0\.0\.0\.0\/0"|source_address_prefix\s*=\s*"(\*|0\.0\.0\.0\/0|Internet)"/;
126
+ /** A firewall rule that lets the whole internet reach an admin or database port. Reads the block around the open range:
127
+ * inbound only, and only when the ports are written there. Pure.
128
+ * shortcut: reads up to 10 lines either side of the range, not the parsed block; parse HCL if rules get longer. */
129
+ export function networkOpen(lines) {
130
+ return lines.flatMap((l, i) => {
131
+ if (!OPEN_CIDR.test(l) || /^\s*(#|\/\/)/.test(l))
132
+ return [];
133
+ const head = /^\s*(ingress|egress|resource|rule|allow|deny|security_rule|-\s*IpProtocol|SecurityGroup(Ingress|Egress))\b/;
134
+ let a = i, b = i;
135
+ while (a > 0 && i - a < 10 && !head.test(lines[a]))
136
+ a--;
137
+ while (b < lines.length - 1 && b - i < 10 && !/^\s*\}\s*$/.test(lines[b]) && !(b > i && head.test(lines[b + 1])))
138
+ b++;
139
+ const block = lines.slice(a, b + 1).join("\n");
140
+ if (/^\s*egress\b|SecurityGroupEgress|type\s*=\s*"egress"|direction\s*=\s*"(Outbound|EGRESS)"/im.test(block))
141
+ return [];
142
+ if (/protocol\s*=\s*"(-1|all)"|IpProtocol\s*:\s*["']?-1/.test(block))
143
+ return [i + 1];
144
+ const n = (re) => { const m = re.exec(block); return m ? Number(m[1]) : null; };
145
+ const lo = n(/\b(?:from_port|FromPort)\s*[=:]\s*"?(\d+)/), hi = n(/\b(?:to_port|ToPort)\s*[=:]\s*"?(\d+)/);
146
+ const single = [...block.matchAll(/\b(?:ports|destination_port_ranges?)\s*=\s*\[?([^\]\n]*)/g)].flatMap((m) => [...m[1].matchAll(/\d+/g)].map((x) => Number(x[0])));
147
+ if (lo !== null && ADMIN_PORTS.some((p) => p >= lo && p <= (hi ?? lo)))
148
+ return [i + 1];
149
+ return single.some((p) => ADMIN_PORTS.includes(p)) ? [i + 1] : [];
150
+ });
151
+ }
152
+ /** A policy statement that allows every action on every resource. A Deny statement with the same wildcards is a guard. Pure. */
153
+ export function iamAllowAll(lines) {
154
+ return lines.flatMap((l, i) => {
155
+ if (!/"?\bAction"?\s*[:=]\s*\[?\s*["']\*["']|\bactions\s*=\s*\[\s*"\*"\s*\]/.test(l))
156
+ return [];
157
+ const near = lines.slice(Math.max(0, i - 6), i + 7).join("\n");
158
+ return /"?\bResource"?\s*[:=]\s*\[?\s*["']\*["']|\bresources\s*=\s*\[\s*"\*"\s*\]/.test(near) && !/\bEffect"?\s*[:=]\s*["']Deny["']/i.test(near) ? [i + 1] : [];
159
+ });
160
+ }
161
+ // `from x import y` inside a RUN python block is not a FROM instruction.
162
+ const from = (l) => (/\bimport\b/.test(l) ? null : /^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+AS\s+(\S+))?/i.exec(l));
163
+ // Official server images start as root and drop to their own user in the entrypoint.
164
+ const DROPS_ROOT = /^(docker\.io\/)?(library\/)?(mysql|mariadb|postgres|redis|mongo|rabbitmq|memcached|elasticsearch|influxdb|grafana\/grafana|clickhouse\/clickhouse-server)(:|@|$)/i;
165
+ /** Dockerfile whose last stage never switches away from root: the last FROM line, or its `USER root` line. Pure. */
166
+ export function dockerRunsAsRoot(lines) {
167
+ let last = -1;
168
+ lines.forEach((l, i) => { if (from(l))
169
+ last = i; });
170
+ if (last < 0)
171
+ return [];
172
+ // Images built to run without root, and `scratch` (nothing to switch to), are left alone.
173
+ if (/nonroot|rootless|unprivileged|chainguard|\bscratch\b/i.test(from(lines[last])[1]) || DROPS_ROOT.test(from(lines[last])[1]))
174
+ return [];
175
+ const users = lines.map((l, i) => [i, /^\s*USER\s+(\S+)/i.exec(l)?.[1]]).filter(([i, u]) => i > last && u);
176
+ if (!users.length)
177
+ return [last + 1];
178
+ const [line, user] = users[users.length - 1];
179
+ return /^(root|0)(:|$)/.test(user) ? [line + 1] : [];
180
+ }
181
+ /** FROM lines with no tag or the `latest` tag. A stage name, a digest, a build argument and `scratch` are not images to pin. Pure. */
182
+ export function dockerImageUnpinned(lines) {
183
+ const stages = new Set();
184
+ return lines.flatMap((l, i) => {
185
+ const m = from(l);
186
+ if (!m)
187
+ return [];
188
+ const image = m[1];
189
+ if (m[2])
190
+ stages.add(m[2].toLowerCase());
191
+ if (stages.has(image.toLowerCase()) && image.toLowerCase() !== m[2]?.toLowerCase())
192
+ return [];
193
+ if (image === "scratch" || image.includes("$") || image.includes("@sha256:"))
194
+ return [];
195
+ const tag = /:([^/:]+)$/.exec(image)?.[1];
196
+ return !tag || tag === "latest" ? [i + 1] : [];
197
+ });
198
+ }
199
+ // A secret given a value at build time stays in the image's layers and history for anyone who pulls it.
200
+ const BUILD_SECRET = /^\s*(ENV|ARG)\s+(?!NEXT_PUBLIC_|VITE_|PUBLIC_|EXPO_PUBLIC_|REACT_APP_)\w*(PASSWORD|PASSWD|SECRET|TOKEN|API_?KEY|PRIVATE_KEY|ACCESS_KEY)(=|\s+)["']?(?!changeme|change[_-]me|example|your[_-]|placeholder|dummy|xxx|none\b|null\b|true\b|false\b)[^\s"'$<{]{6,}/i;
23
201
  export const moreRules = [
202
+ rule({ id: "crypto.static-iv", title: "Encryption with a fixed IV or nonce", status: "gap", severity: "medium", controls: [A04, GDPR("Art. 32", "Security of processing")],
203
+ fix: "Make a new random IV for every message (crypto.randomBytes, os.urandom, SecureRandom) and store it next to the ciphertext. It doesn't need to be secret, only never reused.",
204
+ note: "With the same key and the same IV, two messages can be compared and partly recovered. In AES-GCM a repeated nonce lets an attacker forge messages (CWE-329, CWE-323).",
205
+ extensions: [...CODE, ...NATIVE], test: (l) => STATIC_IV.test(l) && !/^\s*(\/\/|#|\*)/.test(l),
206
+ unlessNear: /randomFill|getRandomValues|randomBytes|rand\.Read|SecureRandom|nextBytes|urandom|secrets\.token/ }),
207
+ rule({ id: "crypto.weak-parameters", title: "Key size or work factor too low", status: "gap", severity: "medium", controls: [A04, GDPR("Art. 32", "Security of processing")],
208
+ fix: "Use RSA keys of 2048 bits or more, bcrypt with 10 rounds or more, and PBKDF2 with the iteration count current guidance gives (600,000 for SHA-256), or switch to Argon2.",
209
+ note: "Short keys can be factored and low work factors make stolen password hashes cheap to crack on ordinary hardware (CWE-326, CWE-916).",
210
+ extensions: [...CODE, ...NATIVE, ".sh", ".bash", ""], test: weakCryptoParameter }),
211
+ rule({ id: "mobile.debuggable-build", title: "Android release build that can be debugged", status: "gap", severity: "medium", controls: [A02, GDPR("Art. 32", "Security of processing")],
212
+ fix: "Remove android:debuggable from the manifest and keep debuggable false in the release build type. The build tools set it for debug builds on their own.",
213
+ note: "A debuggable app lets anyone with the phone attach a debugger, read its private files and change what it does (CWE-489).",
214
+ extensions: [".xml", ".gradle", ".kts"], fileName: /^(AndroidManifest\.xml|build\.gradle(\.kts)?)$/, fileTest: debuggableBuild }),
215
+ rule({ id: "privacy.consent-preticked", title: "Consent box that starts ticked", status: "gap", severity: "medium", controls: [GDPR("Art. 7", "Conditions for consent")],
216
+ fix: "Start the box empty and let the person tick it. Store when they did and the wording they saw.",
217
+ note: "Consent has to be an active choice. A box that is ticked for the person is not consent under the GDPR, so anything sent on that basis has no legal ground (Art. 7, recital 32).",
218
+ extensions: MARKUP, fileTest: consentPreticked,
219
+ unseen: "Lintsure can't tell whether this box is the legal basis for anything. A ticked box for a setting the person already chose earlier is fine." }),
220
+ rule({ id: "privacy.special-category-field", title: "Sensitive category of personal data stored", status: "partial", severity: "medium", controls: [GDPR("Art. 9", "Special categories of personal data")],
221
+ fix: "Check that you need this field at all. If you do, write down the Art. 9 exception you rely on, usually explicit consent, and limit who can read it.",
222
+ note: "Religion, ethnicity, sexual orientation, political views, union membership, health and genetic data may not be processed unless a specific exception applies. Marked Partial: the exception is a decision outside the code.",
223
+ extensions: [...CODE, ".sql", ".prisma"], test: (l) => SPECIAL(l) }),
224
+ rule({ id: "payment.card-code-stored", title: "Card security code stored", status: "gap", severity: "high", controls: [GDPR("Art. 32", "Security of processing"), A02],
225
+ fix: "Never store the card security code. Send the card straight to your payment provider and keep only the token it gives back.",
226
+ note: "The three or four digit code exists to prove the card is in the buyer's hand. Card scheme rules (PCI DSS 3.3.1) forbid keeping it after authorisation, even encrypted, and a leak makes every stored card usable.",
227
+ extensions: [...CODE, ".sql", ".prisma"], test: (l) => CARD_CODE(l) }),
228
+ rule({ id: "cloud.database-public", title: "Database reachable from the internet", status: "gap", severity: "high", controls: [A01, A02],
229
+ fix: "Set publicly_accessible to false, put the database in a private subnet, and reach it through the app, a bastion or a VPN.",
230
+ note: "A database with a public address is one leaked or guessed password away from a full data breach, and it is found by scanners within hours (CWE-284).",
231
+ extensions: [...IAC, ".ts", ".py"], test: (l) => /\bpublicly_accessible\s*=\s*true\b|\bPubliclyAccessible\s*:\s*["']?true\b|\bpubliclyAccessible\s*:\s*true\b|\bpublicly_accessible\s*=\s*True\b/.test(l) && !/^\s*(#|\/\/)/.test(l) }),
232
+ rule({ id: "cloud.network-open", title: "Admin or database port open to the whole internet", status: "gap", severity: "high", controls: [A01, A02],
233
+ fix: "Limit the rule to the addresses that need it (your office, a VPN, a bastion), or remove it and use a session manager.",
234
+ note: "Remote login and database ports that accept connections from 0.0.0.0/0 are scanned and attacked all day (CWE-284).",
235
+ extensions: IAC, fileTest: networkOpen,
236
+ unseen: "Lintsure reads this file only. It can't see a network ACL or a firewall in front that narrows the rule." }),
237
+ rule({ id: "cloud.iam-allow-all", title: "Policy that allows every action on every resource", status: "gap", severity: "high", controls: [A01, A02],
238
+ fix: "List the actions and resources the role really needs. Start from what it calls today and add as you go.",
239
+ note: "Whoever gets this role's credentials, through a leaked key or a compromised service, controls the whole account (CWE-732).",
240
+ extensions: IAC, fileTest: iamAllowAll }),
241
+ rule({ id: "cloud.function-url-no-auth", title: "Function URL that anyone can call", status: "partial", severity: "medium", controls: [A01, A07],
242
+ fix: "Use AWS_IAM as the authorization type, or check a signature or token in the function before doing anything.",
243
+ note: "With authorization set to NONE the function runs for anyone who has the URL. Marked Partial: public webhooks do this on purpose and check a signature in code.",
244
+ extensions: IAC, test: (l) => /\bauthorization_type\s*=\s*"NONE"|\bAuthType\s*:\s*["']?NONE\b/.test(l) && !/^\s*(#|\/\/)/.test(l) }),
245
+ rule({ id: "docker.runs-as-root", title: "Container image that runs as root", status: "partial", severity: "low", controls: [A02],
246
+ fix: "Add a user and switch to it in the last stage, for example `RUN adduser -D app` then `USER app`, or use a base image built to run without root.",
247
+ note: "With no USER line the app runs as root inside the container. A bug that lets someone run code then starts with full rights in the container, which makes breaking out to the host much easier (CWE-250). Marked Partial: the platform may set the user when it starts the container.",
248
+ extensions: [""], fileName: DOCKERFILE, fileTest: dockerRunsAsRoot,
249
+ unseen: "Lintsure can't see a user set at run time (Kubernetes runAsUser, docker run --user) or one the base image already sets." }),
250
+ rule({ id: "docker.image-unpinned", title: "Base image with no fixed version", status: "partial", severity: "low", controls: [A08],
251
+ fix: "Name a version, for example `FROM node:22.11-slim`, and update it on purpose. Pin a digest for anything you ship to others.",
252
+ note: "With no tag, or `latest`, every build can pull a different image, so a broken or tampered release reaches you without any change in your repo (CWE-829).",
253
+ extensions: [""], fileName: DOCKERFILE, fileTest: dockerImageUnpinned }),
254
+ rule({ id: "docker.secret-in-build", title: "Secret given a value in a Dockerfile", status: "gap", severity: "high", controls: [A02, A08],
255
+ fix: "Pass the secret when the container starts (an environment variable or a mounted secret), or use `RUN --mount=type=secret` for build steps. Rotate the value: it is in every image built so far.",
256
+ note: "ENV and ARG values are stored in the image. Anyone who can pull the image, or read its build history, can read the secret (CWE-798).",
257
+ extensions: [""], fileName: DOCKERFILE, test: (l) => BUILD_SECRET.test(l) }),
258
+ rule({ id: "mcp.config-unsafe-server", title: "MCP server run from a moving version or over plain HTTP", status: "partial", severity: "medium", controls: [LLM04, A08],
259
+ fix: "Pin the server to an exact version you have looked at, for example some-server@1.4.2, and update it on purpose. Use https for a remote server.",
260
+ note: "An agent trusts the tools this server offers. With no version, or @latest, the next start can load different code and different tool descriptions than the ones you approved. Over plain HTTP anyone on the network path can change them (OWASP LLM04, CWE-829).",
261
+ extensions: [".json"], pathMatch: AGENT_CONFIG,
262
+ unseen: "Lintsure can't see whether a lockfile or a private registry pins this package somewhere else.",
263
+ fileTest: mcpConfigUnsafe }),
264
+ // The model reads a tool's description before it decides to call the tool, so text there works as an instruction
265
+ // (tool poisoning, first reported for MCP in 2025). Any string in the server file counts: Python tools use the docstring.
266
+ rule({ id: "mcp.tool-description-poisoned", title: "MCP tool description that gives the agent orders", status: "gap", severity: "high", controls: [LLM01, LLM04],
267
+ fix: "Rewrite the description so it only says what the tool does and what it takes. Remove anything that tells the agent to ignore instructions, keep something from the user or read other files, and delete any invisible characters.",
268
+ note: "An agent reads tool descriptions as part of its instructions. A description that says to hide a step, ignore earlier rules or read key files can take over every agent that connects to this server (OWASP LLM01, CWE-1427).", extensions: [...CODE, ".json"],
269
+ unseen: "Lintsure reads this server's source, not the servers it connects to. It can't tell a real attack from a security tool that lists these phrases to detect them.",
270
+ // A scanner that lists these phrases to catch them is not an attack: lines that build a pattern or name an attempt are
271
+ // skipped, and in a JSON manifest only "description" values are read (field test: 6 of 6 new findings were detectors).
272
+ fileTest: (lines) => {
273
+ const code = lines.some((l) => MCP_TOOL.test(l));
274
+ if (!code && !lines.some((l) => /"inputSchema"\s*:/.test(l)))
275
+ return [];
276
+ return lines.flatMap((l, i) => (poisonedDescription(l) && !/^\s*(\/\/|#)/.test(l) && (code || /"description"\s*:/.test(l))
277
+ && !/re\.compile\(|new RegExp\(|\(\?i\)|\b(attempt|detect\w*|patterns?|injection)\b/i.test(l) ? [i + 1] : []));
278
+ } }),
279
+ rule({ id: "mcp.tool-runs-shell", title: "MCP tool that runs shell commands", status: "partial", severity: "high", controls: [LLM03, A06],
280
+ fix: "Run a fixed program with execFile and an argument list, never a command string. Check every argument against an allow-list, and ask the user before anything that changes files or systems.",
281
+ note: "The agent decides what to pass to this tool, and anything it reads (a web page, an issue, a file) can steer it. If tool input reaches the command, a prompt injection becomes a shell on this machine (CWE-78).", extensions: CODE,
282
+ unseen: "Lintsure can't tell whether the tool's input reaches the command, or whether the command is fixed.",
283
+ fileTest: (lines) => (lines.some((l) => /child_process|\bexeca\b|\bimport subprocess\b|\bfrom subprocess\b|\bimport os\b|\bshelljs\b|\bzx\b/.test(l)) ? inMcpServer(lines, SHELL) : []) }),
284
+ rule({ id: "mcp.tool-uses-secret", title: "MCP server reads a credential every tool shares", status: "partial", severity: "low", controls: [LLM03, A01],
285
+ fix: "Give the server a token with only the access its tools need, read-only where it can be. Split tools that write into a separate server or token.",
286
+ note: "Every tool in this server acts with this credential's full access, so the riskiest tool sets the blast radius for all of them. A separate key name doesn't narrow anything if the key itself can do more.", extensions: CODE,
287
+ confidence: "medium",
288
+ unseen: "Lintsure can't see what this credential is allowed to do.",
289
+ // One finding per credential name: the same key read in five places is still one shared key.
290
+ fileTest: (lines) => { const seen = new Set(); return inMcpServer(lines, ENV_SECRET).filter((n) => { const k = lines[n - 1].match(ENV_SECRET)[0]; return !seen.has(k) && !!seen.add(k); }); } }),
24
291
  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
292
  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
293
  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,
@@ -31,7 +298,9 @@ export const moreRules = [
31
298
  rule({ id: "jwt.no-algorithm-pin", title: "Token verified without saying which algorithm is allowed", status: "partial", severity: "medium", controls: [A07],
32
299
  fix: "Pass the algorithm you sign with, for example jwt.verify(token, key, { algorithms: [\"RS256\"] }), or algorithms=[\"HS256\"] in PyJWT.",
33
300
  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) }),
301
+ confidence: "medium",
302
+ // Also an options object written on the line that has no algorithms list.
303
+ test: (l) => /\bjwt\.verify\(\s*[^,()]+,\s*[^,()]+\)/.test(l) || /\bjwt\.verify\(\s*[^,()]+,\s*[^,()]+,\s*\{(?![^}]*\balgorithms\b)[^{}]*\}\s*\)/.test(l) || /\bjwt\.decode\(\s*[\w.]+\s*,\s*[\w."']+\s*\)/.test(l) }),
35
304
  rule({ id: "jwt.weak-secret", title: "Token signed with a short secret written in the code", status: "gap", severity: "high", controls: [A04, A07],
36
305
  fix: "Read the signing key from the environment or a secret store, and make it at least 32 random bytes.",
37
306
  note: "Anyone who reads the code, or guesses a short key, can sign their own login tokens (CWE-798, CWE-521).", extensions: CODE,
@@ -43,7 +312,10 @@ export const moreRules = [
43
312
  rule({ id: "html.tabnabbing", title: "Link opens a new tab without rel=\"noopener\"", status: "partial", severity: "low", controls: [A06],
44
313
  fix: "Add rel=\"noopener noreferrer\" to links with target=\"_blank\".",
45
314
  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) }),
315
+ // Held back by default (2,246 shown on 195 repos, field test 2026-11-20): low risk in current browsers, and JSX puts rel on the next line.
316
+ confidence: "medium",
317
+ test: (l) => /\btarget\s*=\s*\{?\s*["']_blank["']/.test(l) && !/\brel\s*=\s*\{?\s*["'][^"']*\bno(opener|referrer)\b/.test(l),
318
+ unlessNear: /\brel\s*=\s*\{?\s*["'][^"']*\bno(opener|referrer)\b/ }),
47
319
  rule({ id: "ws.no-origin-check", title: "Web-socket server with no origin check", status: "partial", severity: "medium", controls: [A01],
48
320
  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
321
  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,
@@ -52,13 +324,31 @@ export const moreRules = [
52
324
  rule({ id: "k8s.privileged", title: "Container runs privileged or shares the host", status: "gap", severity: "high", controls: [A02],
53
325
  fix: "Remove privileged, hostNetwork, hostPID and hostIPC, set allowPrivilegeEscalation: false, and run as a non-root user.",
54
326
  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) }),
327
+ // Also the one-line form, securityContext: {privileged: true}, and Compose's host namespaces.
328
+ test: (l) => /^\s*-?\s*(privileged|allowPrivilegeEscalation|hostNetwork|hostPID|hostIPC)\s*:\s*true\b/.test(l) || /^\s*-?\s*runAsUser\s*:\s*0\s*$/.test(l)
329
+ || /\bsecurityContext\s*:\s*\{[^}]*\b(privileged|allowPrivilegeEscalation)\s*:\s*true\b/.test(l) || /^\s*(network_mode|pid|ipc)\s*:\s*["']?host["']?\s*(#.*)?$/.test(l)
330
+ // Capabilities that amount to host access, written on one line, and security profiles switched off.
331
+ || /^\s*-?\s*(cap_add|add)\s*:\s*\[[^\]]*\b(SYS_ADMIN|SYS_PTRACE|SYS_MODULE|ALL)\b/.test(l) || /\b(seccomp|apparmor)[:=]unconfined\b/i.test(l),
332
+ // The same capabilities as list items: the nearest key above must be cap_add or add, never drop.
333
+ fileTest: (lines) => lines.flatMap((l, i) => {
334
+ if (!/^\s*-\s*["']?(SYS_ADMIN|SYS_PTRACE|SYS_MODULE|ALL)["']?\s*(#.*)?$/.test(l))
335
+ return [];
336
+ const key = lines.slice(Math.max(0, i - 6), i).reverse().find((x) => /^\s*-?\s*[\w-]+\s*:\s*(#.*)?$/.test(x)) ?? "";
337
+ return /^\s*-?\s*(cap_add|add)\s*:/.test(key) ? [i + 1] : [];
338
+ }) }),
56
339
  rule({ id: "docker.socket-mounted", title: "Docker socket mounted into a container", status: "partial", severity: "high", controls: [A02],
57
340
  fix: "Don't mount /var/run/docker.sock. If the container really needs Docker, point it at a separate, locked-down Docker daemon over TLS, or use a rootless or socket-proxy setup that allows only the calls it needs.",
58
341
  note: "Whatever runs in the container gets the host's Docker, and with it the whole machine: it can start a privileged container that mounts the host's disk (CWE-250). Mounting it read-only (:ro) doesn't help, because the API still works.", extensions: [".yml", ".yaml", ".json", ".sh", ""],
59
342
  unseen: "Lintsure can't tell whether this container is meant to manage Docker (a CI runner or a reverse proxy) or whether the host is a throwaway machine.",
60
343
  // A mount, not a client setting: DOCKER_HOST=unix:///var/run/docker.sock only says where to connect.
61
- test: (l) => /(?<!unix:\/)\/var\/run\/docker\.sock\b|\/\/\.\/pipe\/docker_engine/.test(l) && !/^\s*#|DOCKER_HOST\s*[:=]/.test(l) }),
344
+ // A socket proxy is the fix this rule asks for: the mount into the proxy itself is not a finding (0.3.14 review, 2 of 2).
345
+ // The service's image is the nearest `image:` line above the mount.
346
+ fileTest: (lines) => lines.flatMap((l, i) => {
347
+ if (!/(?<!unix:\/)\/var\/run\/docker\.sock\b|\/\/\.\/pipe\/docker_engine/.test(l) || /^\s*#|DOCKER_HOST\s*[:=]/.test(l))
348
+ return [];
349
+ const image = lines.slice(Math.max(0, i - 60), i).reverse().find((x) => /^\s*image\s*:/.test(x)) ?? "";
350
+ return /socket-proxy/i.test(image) ? [] : [i + 1];
351
+ }) }),
62
352
  rule({ id: "cloud.public-bucket", title: "Storage bucket open to the public", status: "gap", severity: "high", controls: [A01],
63
353
  fix: "Keep the bucket private and block public access. Share single files with short-lived signed URLs instead.",
64
354
  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],
@@ -73,4 +363,58 @@ export const moreRules = [
73
363
  fix: "Turn introspection off in production, for example introspection: process.env.NODE_ENV !== \"production\".",
74
364
  note: "Introspection hands anyone a full map of your API, including fields you never meant to advertise (CWE-200).", extensions: CODE,
75
365
  test: (l) => /\bintrospection\s*:\s*true\b/.test(l) }),
366
+ // ML models are code: a pickled checkpoint or a model repo's own Python runs when it is loaded (2026-11-20).
367
+ rule({ id: "ml.unsafe-model-load", title: "Model loaded in a way that can run code", status: "gap", severity: "high", controls: [A08, LLM04],
368
+ fix: "Load weights only: torch.load(path, weights_only=True), or use safetensors. Don't pass trust_remote_code=True; if a model needs it, pin the exact revision you reviewed.",
369
+ note: "A model checkpoint saved with pickle can carry code that runs the moment it is loaded, and trust_remote_code=True runs Python from the model's repository on your server (CWE-502). Since PyTorch 2.6, torch.load loads weights only by default, so a plain call is Partial: it depends on your PyTorch version.",
370
+ extensions: [".py", ".ipynb"],
371
+ unseen: "Lintsure can't see which PyTorch version runs this, or whether the model file comes only from you.",
372
+ test: (l) => {
373
+ if (/^\s*#/.test(l))
374
+ return false;
375
+ // torch.load inside a string (a list of forbidden calls) isn't a call.
376
+ if (/^[^"'`]*\btorch\.load\s*\(/.test(l))
377
+ return /weights_only\s*=\s*False/.test(l) ? true : /weights_only\s*=/.test(l) ? false : /\)/.test(l) ? "partial" : false;
378
+ // A pinned revision means someone chose that exact code; still Partial, never quiet.
379
+ if (/\btrust_remote_code\s*=\s*True\b/.test(l))
380
+ return "partial";
381
+ return false;
382
+ } }),
383
+ // Images ship with well-known first-run passwords; a compose file or manifest that keeps them leaves the service open.
384
+ rule({ id: "config.default-service-password", title: "Database or service left on its default password", status: "partial", severity: "high", controls: [A07, A02],
385
+ fix: "Set a long random password from a secret store or an untracked .env file, for example POSTGRES_PASSWORD=${POSTGRES_PASSWORD} with no default.",
386
+ note: "These defaults are published in every image's documentation, so anyone who can reach the port can log in (CWE-1393). Marked Partial: fine on a laptop with the port bound to 127.0.0.1, not on a server.",
387
+ extensions: [".yml", ".yaml", ".env", "", ".tf", ".tfvars", ".json", ".toml", ".sh"],
388
+ // CI service containers are thrown away after the run; example, dev, local, test and preview files use the defaults
389
+ // on purpose, whatever their naming (field test 2026-11-20: most hits were these).
390
+ unlessPath: /(^|\/)\.github\/|(^|\/)(integration|e2e|tests?|examples?|samples?|templates?)\/|(^|[\/._-])(example|sample|template|dev|development|local|test|testing|ci|e2e|preview|uffizzi|dusk)([._-][^\/]*)?$|(^|[\/._-])(dev|local|test|ci)[._-]/i,
391
+ // One finding per variable per file: a fallback reused in a connection string is the same weak password.
392
+ fileTest: (lines) => { const seen = new Set(); return lines.flatMap((l, i) => { const k = defaultPasswordKey(l); if (!k || seen.has(k))
393
+ return []; seen.add(k); return [i + 1]; }); } }),
76
394
  ];
395
+ /** The service password variable on this line when it's set to a well-known default, else null. Pure. */
396
+ export function defaultPasswordKey(l) {
397
+ if (/^\s*#/.test(l))
398
+ return null;
399
+ const v = String.raw `\s*[:=]\s*["']?`, end = String.raw `["']?\s*(?:#.*)?$`;
400
+ const pairs = [
401
+ ["POSTGRES_PASSWORD|PGPASSWORD|DB_PASSWORD|DATABASE_PASSWORD", "postgres|password|admin|root|changeme|secret"],
402
+ ["MYSQL_ROOT_PASSWORD|MYSQL_PASSWORD|MARIADB_ROOT_PASSWORD|MARIADB_PASSWORD", "root|password|admin|mysql|changeme|secret"],
403
+ ["MYSQL_ALLOW_EMPTY_PASSWORD|MARIADB_ALLOW_EMPTY_ROOT_PASSWORD", "yes|true|1"],
404
+ // The password alone: the matching default username would only repeat the same account.
405
+ ["MINIO_ROOT_PASSWORD|MINIO_SECRET_KEY", "minioadmin"],
406
+ ["RABBITMQ_DEFAULT_PASS", "guest"],
407
+ ["GF_SECURITY_ADMIN_PASSWORD", "admin"],
408
+ ["ELASTIC_PASSWORD", "changeme|elastic"],
409
+ ["MONGO_INITDB_ROOT_PASSWORD|MONGODB_ROOT_PASSWORD", "password|admin|example|mongo|root|changeme"],
410
+ ["REDIS_PASSWORD", "redis|password|changeme"],
411
+ ["PGADMIN_DEFAULT_PASSWORD|KEYCLOAK_ADMIN_PASSWORD|KC_BOOTSTRAP_ADMIN_PASSWORD|KEYCLOAK_PASSWORD", "admin|password|changeme"],
412
+ ];
413
+ // KEY=default, KEY: default, - KEY=default, ENV KEY=default, and a ${KEY:-default} fallback.
414
+ for (const [k, d] of pairs) {
415
+ const m = new RegExp(String.raw `(?:^|[\s"'-])(?:ENV\s+)?(${k})${v}(?:${d})${end}`, "i").exec(l) ?? new RegExp(String.raw `\$\{(${k}):?-(?:${d})\}`, "i").exec(l);
416
+ if (m)
417
+ return m[1].toUpperCase();
418
+ }
419
+ return null;
420
+ }
@@ -1,5 +1,9 @@
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. */
2
+ export declare const AGENT_CONFIG: RegExp;
3
+ /** True when a line carries text hidden from a human reader. Pure. */
4
+ export declare const hiddenText: (l: string) => boolean;
5
+ export declare const poisonedDescription: (l: string) => boolean;
6
+ /** Agent instruction line: Gap for override, concealment, hidden text or sending secrets out; Partial for download-and-run. Pure. */
3
7
  export declare function instructionsUnsafe(l: string): boolean | "partial";
4
8
  /** True when a signing or encryption secret falls back to a fixed value written in the code. Pure. */
5
9
  export declare function fallbackSecret(l: string): boolean;