@lintsure/core 0.3.5 → 0.3.6
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/index.d.ts +7 -2
- package/dist/src/index.js +82 -34
- package/dist/src/knowledge/cra.js +1 -1
- package/dist/src/knowledge/gdpr.js +1 -1
- package/dist/src/knowledge/owasp-top10.js +1 -1
- package/dist/src/rules/cra.js +1 -1
- package/dist/src/rules/index.js +31 -14
- package/dist/src/rules/owasp.d.ts +2 -0
- package/dist/src/rules/owasp.js +61 -15
- package/dist/src/rules/stack.d.ts +5 -0
- package/dist/src/rules/stack.js +48 -1
- package/dist/src/rules/standards.js +8 -4
- package/dist/src/types.d.ts +7 -1
- package/package.json +2 -2
package/dist/src/index.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ export * from "./guidance.js";
|
|
|
12
12
|
export { toAssessmentHtml } from "./assessment.js";
|
|
13
13
|
export * from "./knowledge/index.js";
|
|
14
14
|
export { loadPacks, registerPack, type Pack } from "./packs.js";
|
|
15
|
-
export declare const RULES_VERSION = "0.3.
|
|
15
|
+
export declare const RULES_VERSION = "0.3.6";
|
|
16
16
|
/** Shown with every result, in every interface. Lintsure prepares; people decide. */
|
|
17
17
|
export declare const DISCLAIMER: string;
|
|
18
18
|
/** What a report must never be read as. Used in the report and by the MCP server. */
|
|
@@ -34,11 +34,16 @@ export declare function readConfig(root: string): Promise<{
|
|
|
34
34
|
packsMissing?: string[];
|
|
35
35
|
}>;
|
|
36
36
|
export declare const SKIP_DIRS: string[];
|
|
37
|
+
/** A file is generated or minified when long lines make up more than a twentieth of it. Pure. */
|
|
38
|
+
export declare const isMinified: (lines: string[]) => boolean;
|
|
39
|
+
/** Normalises file extensions so rules written for .ts also read .mts and .cts, and every .env file is ".env". */
|
|
40
|
+
export declare function extOf(abs: string): string;
|
|
37
41
|
/** Scout: list files to check, sorted so output order never depends on the file system. */
|
|
38
42
|
export declare function listFiles(root: string, ignore?: string[]): Promise<string[]>;
|
|
43
|
+
export declare const NON_SHIPPING: RegExp;
|
|
39
44
|
/** The JSON object key that opens the block a line sits in, e.g. "peerDependencies". Pure. */
|
|
40
45
|
export declare function enclosingKey(lines: string[], i: number): string;
|
|
41
|
-
/** Marks lines that are only a comment or sit inside a block comment or
|
|
46
|
+
/** Marks lines that are only a comment or sit inside a block comment, Python docstring or multi-line string. Pure. */
|
|
42
47
|
export declare function commentLines(lines: string[], ext: string): boolean[];
|
|
43
48
|
export declare function scan(root: string, frameworks?: FrameworkId[], opts?: RecordOptions): Promise<Report>;
|
|
44
49
|
export declare function toMarkdown(r: Report): string;
|
package/dist/src/index.js
CHANGED
|
@@ -19,7 +19,7 @@ export { toAssessmentHtml } from "./assessment.js";
|
|
|
19
19
|
export * from "./knowledge/index.js";
|
|
20
20
|
export { loadPacks, registerPack } from "./packs.js";
|
|
21
21
|
import { loadPacks } from "./packs.js";
|
|
22
|
-
export const RULES_VERSION = "0.3.
|
|
22
|
+
export const RULES_VERSION = "0.3.6";
|
|
23
23
|
/** Shown with every result, in every interface. Lintsure prepares; people decide. */
|
|
24
24
|
export const DISCLAIMER = "Lintsure is a readiness tool, not an audit, a certification or legal advice. " +
|
|
25
25
|
"Its rules reflect our reading of the publicly available text of each framework, and they check code only. " +
|
|
@@ -92,17 +92,32 @@ export async function readConfig(root) {
|
|
|
92
92
|
return { frameworks: known, skipped: ids.filter((i) => !known.includes(i)), ignore, packsMissing };
|
|
93
93
|
}
|
|
94
94
|
// Dependencies, build output and caches: generated code, not code you wrote.
|
|
95
|
-
|
|
95
|
+
// Also other people's code copied in (vendor, third_party): not code you wrote (field test, 139 repos).
|
|
96
|
+
export const SKIP_DIRS = ["node_modules", ".git", "dist", "build", "out", ".output", ".next", ".nuxt", ".svelte-kit", ".astro", ".vercel", ".netlify", ".wrangler", ".turbo", ".cache", "venv", ".venv", "__pycache__", "coverage", "vendor", "third_party", "bower_components"];
|
|
96
97
|
const SKIP = new Set(SKIP_DIRS);
|
|
97
|
-
|
|
98
|
+
// Bundled builds of libraries checked into a repo, e.g. vue.global.js (field test, 139 repos).
|
|
99
|
+
const BUNDLED = /\.(min|global|bundle|umd|prod)\.(js|css)$/;
|
|
100
|
+
const MAX_LINE = 1000; // longer lines are minified or generated: they are ignored, not the whole file
|
|
98
101
|
const MAX_BYTES = 1_000_000;
|
|
102
|
+
/** A file is generated or minified when long lines make up more than a twentieth of it. Pure. */
|
|
103
|
+
export const isMinified = (lines) => lines.filter((l) => l.length > MAX_LINE).length > Math.max(1, lines.length / 20);
|
|
104
|
+
/** Normalises file extensions so rules written for .ts also read .mts and .cts, and every .env file is ".env". */
|
|
105
|
+
export function extOf(abs) {
|
|
106
|
+
const name = basename(abs);
|
|
107
|
+
if (/^\.env(\.[\w.-]+)?$/.test(name))
|
|
108
|
+
return ".env";
|
|
109
|
+
if (/^Dockerfile\b/i.test(name))
|
|
110
|
+
return ""; // Dockerfile.prod is still a Dockerfile
|
|
111
|
+
const e = extname(abs);
|
|
112
|
+
return e === ".mts" || e === ".cts" ? ".ts" : e;
|
|
113
|
+
}
|
|
99
114
|
/** Scout: list files to check, sorted so output order never depends on the file system. */
|
|
100
115
|
export async function listFiles(root, ignore = []) {
|
|
101
116
|
const out = [];
|
|
102
117
|
const ignored = (p) => { const r = relative(root, p).split(sep).join("/"); return ignore.some((i) => r === i || r.startsWith(i + "/")); };
|
|
103
118
|
async function walk(dir) {
|
|
104
119
|
for (const e of await readdir(dir, { withFileTypes: true })) {
|
|
105
|
-
if (SKIP.has(e.name) ||
|
|
120
|
+
if (SKIP.has(e.name) || BUNDLED.test(e.name))
|
|
106
121
|
continue;
|
|
107
122
|
const p = join(dir, e.name);
|
|
108
123
|
if (ignored(p))
|
|
@@ -116,11 +131,15 @@ export async function listFiles(root, ignore = []) {
|
|
|
116
131
|
await walk(root);
|
|
117
132
|
return out.sort();
|
|
118
133
|
}
|
|
119
|
-
|
|
134
|
+
// Code that doesn't ship: tests, fixtures, examples, docs, demos, stories and seed data. Most false alarms in the
|
|
135
|
+
// 139-repo field test came from here. Only the secret rules read these paths, and their findings there are Partial.
|
|
136
|
+
export const NON_SHIPPING = /(^|\/)(tests?|__tests__|__mocks__|mocks?|spec|fixtures?|__fixtures__|e2e|examples?|samples?|demos?|cookbooks?|docs?|stories|storybook|seeds?|seeders|benchmarks?)\/|\.(test|spec|stories)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.(py|go)$|(^|\/)conftest\.py$|(^|\/)\.env\.(example|sample|template|dist)$|(^|\/)(playwright|vitest|jest|cypress)\.config\.[cm]?[jt]s$/i;
|
|
120
137
|
// Rules that also read test files. Not auth.hardcoded-password: test logins are fake by design (field test, 50 repos).
|
|
121
138
|
const SECRET_RULES = new Set(["secret.in-source", "config.default-secret-key"]);
|
|
122
|
-
// Lines a person already reviewed and
|
|
123
|
-
|
|
139
|
+
// Lines a person already reviewed. lintsure-ignore and the secret allowlist pragma count only in a comment and apply
|
|
140
|
+
// to every rule. Other linters' markers (noqa, nosec, NOSONAR) don't hide secrets: `# noqa: E501` is about line length.
|
|
141
|
+
const REVIEWED = /(#|\/\/|\/\*|--)\s*(lintsure-ignore|pragma:\s*allowlist secret)\b/;
|
|
142
|
+
const OTHER_LINTER = /#\s*(noqa|nosec)\b|\/\/\s*NOSONAR\b/;
|
|
124
143
|
// Also hand-typed fake keys: alphabet or number runs, words where random text should be, a whole key block on one line.
|
|
125
144
|
const PLACEHOLDER = /test|fake|dummy|example|sample|placeholder|sanitized|mock|xxx|changeme|localhost|["'](password|pass|secret|elastic|admin)["']|abcdef|123456|\b(xox[baprs]|gh[pousr])[-_][a-z]+(-[a-z]+)*\b|PRIVATE KEY-----.*-----END/i;
|
|
126
145
|
/** The JSON object key that opens the block a line sits in, e.g. "peerDependencies". Pure. */
|
|
@@ -135,10 +154,11 @@ export function enclosingKey(lines, i) {
|
|
|
135
154
|
return "";
|
|
136
155
|
}
|
|
137
156
|
const HASH_COMMENTS = new Set([".py", ".rb", ".sh", ".yml", ".yaml", ".toml", ".env"]);
|
|
138
|
-
|
|
157
|
+
const C_LIKE = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".java", ".kt", ".swift", ".go", ".css", ".scss"]);
|
|
158
|
+
/** Marks lines that are only a comment or sit inside a block comment, Python docstring or multi-line string. Pure. */
|
|
139
159
|
export function commentLines(lines, ext) {
|
|
140
|
-
const hash = HASH_COMMENTS.has(ext), py = ext === ".py";
|
|
141
|
-
let block = false, doc = false;
|
|
160
|
+
const hash = HASH_COMMENTS.has(ext), py = ext === ".py", sql = ext === ".sql";
|
|
161
|
+
let block = false, doc = false, quote = "";
|
|
142
162
|
return lines.map((raw) => {
|
|
143
163
|
const t = raw.trim();
|
|
144
164
|
if (block) {
|
|
@@ -147,22 +167,32 @@ export function commentLines(lines, ext) {
|
|
|
147
167
|
return true;
|
|
148
168
|
}
|
|
149
169
|
if (doc) {
|
|
150
|
-
if (
|
|
170
|
+
if (t.includes(quote))
|
|
151
171
|
doc = false;
|
|
152
172
|
return true;
|
|
153
173
|
}
|
|
154
|
-
if (py
|
|
155
|
-
const q = t.match(/"""|'''/)[0];
|
|
156
|
-
|
|
174
|
+
if (py) {
|
|
175
|
+
const q = t.match(/"""|'''/)?.[0];
|
|
176
|
+
// An odd number of triple quotes opens a string that runs onto the next lines. A docstring line is text;
|
|
177
|
+
// `PROMPT = """` is code whose string continues, and its closing quotes must not open a fake docstring (field test).
|
|
178
|
+
if (q && t.split(q).length % 2 === 0) {
|
|
157
179
|
doc = true;
|
|
158
|
-
|
|
180
|
+
quote = q;
|
|
181
|
+
return /^[rbuf]*("""|''')/i.test(t);
|
|
182
|
+
}
|
|
183
|
+
if (q && /^[rbuf]*("""|''')/i.test(t) && t.endsWith(q))
|
|
184
|
+
return true; // one-line docstring
|
|
159
185
|
}
|
|
186
|
+
// `/* note */ code();` is code: only a line that is all comment counts.
|
|
160
187
|
if (t.startsWith("/*")) {
|
|
161
|
-
|
|
188
|
+
const end = t.indexOf("*/");
|
|
189
|
+
if (end < 0) {
|
|
162
190
|
block = true;
|
|
163
|
-
|
|
191
|
+
return true;
|
|
192
|
+
}
|
|
193
|
+
return !t.slice(end + 2).trim();
|
|
164
194
|
}
|
|
165
|
-
return t.startsWith("//") || t.startsWith("*") || t.startsWith("<!--") || (hash && t.startsWith("#"));
|
|
195
|
+
return t.startsWith("//") || (C_LIKE.has(ext) && t.startsWith("*")) || t.startsWith("<!--") || (hash && t.startsWith("#")) || (sql && t.startsWith("--"));
|
|
166
196
|
});
|
|
167
197
|
}
|
|
168
198
|
export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
@@ -189,14 +219,27 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
189
219
|
for (const r of active.filter((x) => x.sharedContext)) {
|
|
190
220
|
const texts = [];
|
|
191
221
|
for (const [k, abs] of all.entries()) {
|
|
192
|
-
const ext =
|
|
193
|
-
if (r.extensions.includes(ext) &&
|
|
194
|
-
|
|
222
|
+
const ext = extOf(abs), file = paths[k];
|
|
223
|
+
if (!r.extensions.includes(ext) || (r.fileName && !r.fileName.test(basename(abs))) || (r.pathMatch && !r.pathMatch.test(file)) || r.unlessPath?.test(file))
|
|
224
|
+
continue;
|
|
225
|
+
const text = await readFile(abs, "utf8").catch(() => "");
|
|
226
|
+
// Commented-out lines don't count: "-- alter table x enable row level security" switches nothing on.
|
|
227
|
+
const comment = commentLines(text.split(/\r?\n/), ext);
|
|
228
|
+
texts.push(text.split(/\r?\n/).filter((_, i) => !comment[i]).join("\n"));
|
|
195
229
|
}
|
|
196
230
|
shared.set(r.id, texts.join("\n"));
|
|
197
231
|
}
|
|
232
|
+
// Rules that read two files together (a config entry and the code it points to) get those files by path.
|
|
233
|
+
const sharedFiles = new Map();
|
|
234
|
+
for (const r of active.filter((x) => x.sharedFiles)) {
|
|
235
|
+
const files = {};
|
|
236
|
+
for (const [k, abs] of all.entries())
|
|
237
|
+
if (r.sharedFiles.test(paths[k]))
|
|
238
|
+
files[paths[k]] = await readFile(abs, "utf8").catch(() => "");
|
|
239
|
+
sharedFiles.set(r.id, files);
|
|
240
|
+
}
|
|
198
241
|
for (const abs of all) {
|
|
199
|
-
const ext =
|
|
242
|
+
const ext = extOf(abs);
|
|
200
243
|
const name = basename(abs);
|
|
201
244
|
const file = relative(root, abs).split(sep).join("/");
|
|
202
245
|
const relevant = active.filter((r) => r.extensions.includes(ext) && (!r.fileName || r.fileName.test(name)) && (!r.pathMatch || r.pathMatch.test(file)) && !r.unlessPath?.test(file));
|
|
@@ -205,9 +248,11 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
205
248
|
const buf = await readFile(abs);
|
|
206
249
|
if (buf.length > MAX_BYTES || buf.includes(0))
|
|
207
250
|
continue; // skip big or binary files
|
|
208
|
-
const
|
|
209
|
-
if (
|
|
251
|
+
const raw = buf.toString("utf8").split(/\r?\n/);
|
|
252
|
+
if (isMinified(raw))
|
|
210
253
|
continue; // minified or generated
|
|
254
|
+
// A single very long line (a data URL, a long prompt) is ignored on its own; the rest of the file is still read.
|
|
255
|
+
const lines = raw.map((l) => (l.length > MAX_LINE ? "" : l));
|
|
211
256
|
filesChecked++;
|
|
212
257
|
checkPoints += relevant.length; // one rule applied to one file is one check point
|
|
213
258
|
for (const r of relevant)
|
|
@@ -220,14 +265,16 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
220
265
|
fingerprint: fingerprint(r.id, file, lines[line - 1] ?? ""),
|
|
221
266
|
});
|
|
222
267
|
};
|
|
223
|
-
// Tests and
|
|
224
|
-
|
|
268
|
+
// Tests, fixtures, examples and docs are full of fake tokens and planted examples: only secret rules look at them,
|
|
269
|
+
// and what they find there is Partial (it may be a throwaway key).
|
|
270
|
+
const inTests = NON_SHIPPING.test(file);
|
|
225
271
|
const comment = commentLines(lines, ext);
|
|
226
272
|
for (const r of relevant) {
|
|
227
|
-
|
|
273
|
+
const secret = SECRET_RULES.has(r.id);
|
|
274
|
+
if (inTests && !secret)
|
|
228
275
|
continue;
|
|
229
276
|
// Comments describe code, they don't run. A real secret pasted into a comment still counts.
|
|
230
|
-
const skip =
|
|
277
|
+
const skip = secret ? null : comment;
|
|
231
278
|
if (r.test)
|
|
232
279
|
lines.forEach((text, i) => {
|
|
233
280
|
if (skip?.[i])
|
|
@@ -239,14 +286,14 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
239
286
|
return;
|
|
240
287
|
if (inTests && PLACEHOLDER.test(text))
|
|
241
288
|
return; // password="test_password", token="xoxb-test-..."
|
|
242
|
-
if (REVIEWED.test(text))
|
|
289
|
+
if (REVIEWED.test(text) || (!secret && OTHER_LINTER.test(text)))
|
|
243
290
|
return; // someone already looked at this line and marked it
|
|
244
|
-
add(r, i + 1, hit === "partial" ? "partial" : r.status);
|
|
291
|
+
add(r, i + 1, hit === "partial" || inTests ? "partial" : r.status);
|
|
245
292
|
});
|
|
246
293
|
// File rules see comment lines as blank, so "<img> in a comment" or a commented-out call doesn't count (field test).
|
|
247
294
|
if (r.fileTest)
|
|
248
|
-
for (const n of r.fileTest(skip ? lines.map((l, i) => (skip[i] ? "" : l)) : lines, shared.get(r.id)))
|
|
249
|
-
add(r, n);
|
|
295
|
+
for (const n of r.fileTest(skip ? lines.map((l, i) => (skip[i] ? "" : l)) : lines, shared.get(r.id), sharedFiles.get(r.id)))
|
|
296
|
+
typeof n === "number" ? add(r, n) : add(r, n.line, n.status);
|
|
250
297
|
}
|
|
251
298
|
}
|
|
252
299
|
// Auditor: one finding per rule per line; stable order.
|
|
@@ -260,8 +307,9 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
260
307
|
rulesVersion: RULES_VERSION,
|
|
261
308
|
frameworks: [...frameworks].sort(),
|
|
262
309
|
findings: deduped,
|
|
263
|
-
// Only the Checker sets Met: a rule that
|
|
264
|
-
|
|
310
|
+
// Only the Checker sets Met: a rule that read at least one file and found nothing. A rule with nothing to read
|
|
311
|
+
// (mobile rules in a web app) is not Met: nothing was checked.
|
|
312
|
+
met: active.filter((r) => !hit.has(r.id) && (perRule[r.id] ?? 0) > 0).map((r) => ({ ruleId: r.id, title: r.title, controls: r.controls.filter((c) => frameworks.includes(c.framework)) })),
|
|
265
313
|
outside: outsideFor(frameworks),
|
|
266
314
|
filesChecked,
|
|
267
315
|
disclaimer: DISCLAIMER,
|
|
@@ -21,7 +21,7 @@ export const cra = {
|
|
|
21
21
|
plain: "The product ships with safe settings switched on: debug off, real host names, strong secrets, secure cookies, nothing left open that the user has to close.",
|
|
22
22
|
evidence: "Production configuration and the default settings a new install starts with." },
|
|
23
23
|
{ ref: "Annex I Part I (2)(d)", title: "Protection from unauthorised access", inCode: "partly",
|
|
24
|
-
rules: ["auth.hardcoded-password", "jwt.unverified", "jwt.no-expiry", "supabase.rls-disabled", "supabase.policy-allows-all", "supabase.service-key-in-client", "cookie.trusted-role", "path.user-input", "fs.world-writable"],
|
|
24
|
+
rules: ["auth.hardcoded-password", "jwt.unverified", "jwt.no-expiry", "supabase.rls-disabled", "supabase.policy-allows-all", "supabase.service-key-in-client", "supabase.function-no-auth", "cookie.trusted-role", "path.user-input", "fs.world-writable"],
|
|
25
25
|
plain: "Logins, tokens and permissions that keep people out of what isn't theirs: no built-in passwords, verified tokens that expire, and access rules on data.",
|
|
26
26
|
evidence: "How users sign in, how roles are checked, and tests between two accounts." },
|
|
27
27
|
{ ref: "Annex I Part I (2)(e)", title: "Confidentiality of data", inCode: "yes",
|
|
@@ -50,7 +50,7 @@ export const gdpr = {
|
|
|
50
50
|
plain: "Keep a list of what personal data you process, why, with whom you share it and how long you keep it.",
|
|
51
51
|
evidence: "The register of processing activities." },
|
|
52
52
|
{ ref: "Art. 32", title: "Security of processing", inCode: "yes",
|
|
53
|
-
rules: ["pii.logged", "secret.in-source", "transport.plain-http", "transport.tls-verify-off", "crypto.weak-password-hash", "sql.string-built", "pii.in-url", "supabase.rls-disabled", "supabase.policy-allows-all", "supabase.service-key-in-client", "secret.public-env", "mobile.token-in-plain-storage", "mobile.cleartext-traffic", "mobile.backup-allowed"],
|
|
53
|
+
rules: ["pii.logged", "secret.in-source", "transport.plain-http", "transport.tls-verify-off", "crypto.weak-password-hash", "sql.string-built", "pii.in-url", "supabase.rls-disabled", "supabase.policy-allows-all", "supabase.service-key-in-client", "supabase.function-no-auth", "secret.public-env", "mobile.token-in-plain-storage", "mobile.cleartext-traffic", "mobile.backup-allowed"],
|
|
54
54
|
plain: "Protect personal data with security that fits the risk: encryption, access control, testing and the ability to recover.",
|
|
55
55
|
evidence: "Security measures and when they were last tested." },
|
|
56
56
|
{ ref: "Art. 33–34", title: "Breach notification", inCode: "no",
|
|
@@ -16,7 +16,7 @@ export const owaspTop10 = {
|
|
|
16
16
|
},
|
|
17
17
|
obligations: [
|
|
18
18
|
{ ref: "A01:2025", title: "Broken Access Control", inCode: "partly",
|
|
19
|
-
rules: ["path.user-input", "redirect.open", "ssrf.user-url", "csrf.disabled", "fs.world-writable", "cors.any-origin", "cookie.trusted-role", "supabase.rls-disabled", "supabase.policy-allows-all", "supabase.service-key-in-client"],
|
|
19
|
+
rules: ["path.user-input", "redirect.open", "ssrf.user-url", "csrf.disabled", "fs.world-writable", "cors.any-origin", "cookie.trusted-role", "supabase.rls-disabled", "supabase.policy-allows-all", "supabase.service-key-in-client", "supabase.function-no-auth"],
|
|
20
20
|
plain: "People must only reach the data and actions meant for them. This covers file paths, redirects, requests your server makes on a user's behalf (SSRF), forged requests from other sites, and permissions kept where users can change them.",
|
|
21
21
|
evidence: "A list of roles and what each may do, and tests showing one user can't read or change another user's data." },
|
|
22
22
|
{ ref: "A01:2025 (ownership checks)", title: "Every record is checked against the signed-in user", inCode: "no",
|
package/dist/src/rules/cra.js
CHANGED
|
@@ -7,7 +7,7 @@ const A03 = { framework: "owasp-top10", id: "A03:2025", title: "Software Supply
|
|
|
7
7
|
const A08 = { framework: "owasp-top10", id: "A08:2025", title: "Software or Data Integrity Failures" };
|
|
8
8
|
const tag = (c, ids) => Object.fromEntries(ids.map((id) => [id, [c]]));
|
|
9
9
|
/** CRA controls for rules that already exist. Merged by id in rules/index.ts. */
|
|
10
|
-
export const craForExisting = mergeTags(tag(DEFAULTS, ["config.debug-on", "config.allowed-hosts-any", "config.default-secret-key", "cors.any-origin", "build.sourcemaps-public", "csrf.disabled", "session.cookie-insecure"]), tag(ACCESS, ["auth.hardcoded-password", "jwt.unverified", "jwt.no-expiry", "supabase.rls-disabled", "supabase.policy-allows-all", "supabase.service-key-in-client", "cookie.trusted-role", "path.user-input", "fs.world-writable"]), tag(CONFIDENTIAL, ["transport.plain-http", "transport.tls-verify-off", "crypto.weak-cipher", "crypto.weak-password-hash", "crypto.weak-random-token", "secret.in-source", "secret.public-env"]), tag(INTEGRITY, ["sql.string-built", "cmd.shell-built", "code.eval", "deserialize.unsafe", "xss.raw-html", "template.user-string", "nosql.operator-input", "xml.external-entities", "mass-assignment", "html.script-no-sri"]), tag(MINIMAL, ["pii.logged", "pii.in-url", "pii.to-analytics"]), tag(SURFACE, ["ssrf.user-url", "redirect.open", "upload.unrestricted", "error.stack-to-client"]), tag(LOGGING, ["log.secret", "log.injection"]), tag(COMPONENTS, ["deps.unpinned-version", "deps.install-script"]), tag(UPDATES, ["ci.action-unpinned", "ci.prt-checkout-head"]));
|
|
10
|
+
export const craForExisting = mergeTags(tag(DEFAULTS, ["config.debug-on", "config.allowed-hosts-any", "config.default-secret-key", "cors.any-origin", "build.sourcemaps-public", "csrf.disabled", "session.cookie-insecure"]), tag(ACCESS, ["auth.hardcoded-password", "jwt.unverified", "jwt.no-expiry", "supabase.rls-disabled", "supabase.policy-allows-all", "supabase.service-key-in-client", "supabase.function-no-auth", "cookie.trusted-role", "path.user-input", "fs.world-writable"]), tag(CONFIDENTIAL, ["transport.plain-http", "transport.tls-verify-off", "crypto.weak-cipher", "crypto.weak-password-hash", "crypto.weak-random-token", "secret.in-source", "secret.public-env"]), tag(INTEGRITY, ["sql.string-built", "cmd.shell-built", "code.eval", "deserialize.unsafe", "xss.raw-html", "template.user-string", "nosql.operator-input", "xml.external-entities", "mass-assignment", "html.script-no-sri"]), tag(MINIMAL, ["pii.logged", "pii.in-url", "pii.to-analytics"]), tag(SURFACE, ["ssrf.user-url", "redirect.open", "upload.unrestricted", "error.stack-to-client"]), tag(LOGGING, ["log.secret", "log.injection"]), tag(COMPONENTS, ["deps.unpinned-version", "deps.install-script"]), tag(UPDATES, ["ci.action-unpinned", "ci.prt-checkout-head"]));
|
|
11
11
|
function mergeTags(...maps) {
|
|
12
12
|
const out = {};
|
|
13
13
|
for (const m of maps)
|
package/dist/src/rules/index.js
CHANGED
|
@@ -83,7 +83,8 @@ export const rules = [
|
|
|
83
83
|
fix: "Use https:// for every external call.",
|
|
84
84
|
note: "Marked Partial: the call may carry no sensitive data. Confirm, then switch to HTTPS anyway.",
|
|
85
85
|
extensions: CODE,
|
|
86
|
-
|
|
86
|
+
// Loopback, private ranges and single-label service names (http://redis:6379) stay on the machine or network (field test).
|
|
87
|
+
test: (l) => /\b(fetch|axios\.\w+|requests\.\w+|http\.(get|request))\s*\(\s*["'`]http:\/\/(?!localhost|127\.|0\.0\.0\.0|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[::1\]|host\.docker\.internal)[\w-]+\.[\w.-]+/.test(l),
|
|
87
88
|
...DRAFT,
|
|
88
89
|
},
|
|
89
90
|
{
|
|
@@ -92,9 +93,8 @@ export const rules = [
|
|
|
92
93
|
status: "gap", severity: "high",
|
|
93
94
|
controls: [
|
|
94
95
|
{ framework: "gdpr", id: "Art. 5(1)(c)", title: "Data minimisation" },
|
|
95
|
-
{ framework: "gdpr", id: "Art. 28", title: "Processors" },
|
|
96
96
|
],
|
|
97
|
-
fix: "Send an internal user ID instead of the email or name,
|
|
97
|
+
fix: "Send an internal user ID instead of the email or name. If personal data must go there, list the tool as a processor.",
|
|
98
98
|
note: "Analytics vendors keep what you send them. Personal data there needs a lawful basis and a processing agreement.",
|
|
99
99
|
extensions: CODE,
|
|
100
100
|
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),
|
|
@@ -124,7 +124,12 @@ export const rules = [
|
|
|
124
124
|
note: "MD5 and SHA-1 are fast, so leaked hashes can be cracked quickly.",
|
|
125
125
|
extensions: CODE,
|
|
126
126
|
// Sentences in strings ("the server asked for an MD5 password hash") are messages, not hashing (field test).
|
|
127
|
-
|
|
127
|
+
// The hash must be applied to a password. HMAC, HTTP Digest and fixed vendor formats require the algorithm;
|
|
128
|
+
// they don't store passwords (field test, 139 repos).
|
|
129
|
+
test: (l) => {
|
|
130
|
+
const c = l.replace(/(["'`])(?:(?!\1).)*\s(?:(?!\1).)*\1/g, '""');
|
|
131
|
+
return /\b(md5|sha1)\b[^;\n]{0,60}\bpass(word|wd)?\b/i.test(c) && !/hmac|digest\s*(auth|access)|\brealm\b|\bnonce\b|cookie/i.test(c);
|
|
132
|
+
},
|
|
128
133
|
...DRAFT,
|
|
129
134
|
},
|
|
130
135
|
{
|
|
@@ -153,12 +158,18 @@ export const rules = [
|
|
|
153
158
|
test: (l) => {
|
|
154
159
|
// SQL keywords are written in UPPER or lower case; "Select a plan from..." in a sentence is not SQL.
|
|
155
160
|
// A keyword after a dot or before "(" is a method call (hash.update(...), select(Model) in SQLAlchemy), not SQL text.
|
|
156
|
-
|
|
161
|
+
// A statement's shape: SELECT ... FROM, INSERT INTO, UPDATE x SET, DELETE FROM. "Could not update user ${id} from ..." is a message.
|
|
162
|
+
if (!/(?<![.\w])(SELECT\b(?!\s*\()[^"'`]*\bFROM\b|INSERT\s+INTO\b|UPDATE\s+[\w."`${}]+\s+SET\b|DELETE\s+FROM\b)/i.test(l))
|
|
163
|
+
return false;
|
|
164
|
+
if (/\b(throw|Error|message|msg)\b/.test(l) && !/\.(query|execute|exec|raw|run|prepare|all|get)\s*\(/.test(l))
|
|
157
165
|
return false;
|
|
158
166
|
const parts = [...l.matchAll(SQL_PARTS)].map((m) => m.slice(1).find(Boolean) ?? "");
|
|
159
167
|
if (!parts.length)
|
|
160
168
|
return false;
|
|
161
|
-
|
|
169
|
+
if (parts.some((p) => USER_INPUT.test(p)))
|
|
170
|
+
return true;
|
|
171
|
+
// Table and column names, placeholder lists and CONSTANTS are your own text, not values (field test, 139 repos).
|
|
172
|
+
return parts.every((p) => /^\s*([A-Z][A-Z0-9_]*|[\w.]*(table|Table|TABLE|column|Column|cols|fields|placeholders?|Placeholders|schema|Schema|alias|orderBy|sortField|direction)\w*)\s*$/.test(p)) ? false : "partial";
|
|
162
173
|
},
|
|
163
174
|
// Tagged templates from Postgres.js, Drizzle, Prisma and similar send ${} values as parameters, not as SQL text (field test).
|
|
164
175
|
unlessNear: /(?<![.\w])(sql|safeSql|tx|Prisma\.sql)(<[^>`]*>)?\s*`|\$queryRaw\s*`/,
|
|
@@ -173,12 +184,13 @@ export const rules = [
|
|
|
173
184
|
note: "Marked Partial: fine for a public, read-only API. Risky when the API uses cookies or returns user data.",
|
|
174
185
|
extensions: CODE,
|
|
175
186
|
test: (l) => /Access-Control-Allow-Origin["']?\s*[,:]\s*["']\*["']|origin\s*:\s*(["']\*["']|true\b)|CORS_ALLOW_ALL_ORIGINS\s*=\s*True|allow_origins\s*=\s*\[\s*["']\*["']/.test(l),
|
|
187
|
+
unlessPath: /(^|\/)(vite|webpack|rollup|next|nuxt|astro)\.config\.|openapi|swagger/i, // dev servers and published API specs (field test)
|
|
176
188
|
...DRAFT,
|
|
177
189
|
},
|
|
178
190
|
{
|
|
179
191
|
id: "session.cookie-insecure",
|
|
180
192
|
title: "Session cookie without Secure or HttpOnly",
|
|
181
|
-
status: "partial", severity: "
|
|
193
|
+
status: "partial", severity: "low",
|
|
182
194
|
controls: [],
|
|
183
195
|
fix: "Set secure: true and httpOnly: true on session cookies.",
|
|
184
196
|
note: "Without these flags a session cookie can be read by scripts or sent over plain HTTP. Marked Partial: confirm it is a session cookie.",
|
|
@@ -226,7 +238,9 @@ export const unloggedAiCalls = (lines) => {
|
|
|
226
238
|
const MEDIA_MODEL = /["'`](dall-e-\d|gpt-image-[\w.]+|imagen-[\w.-]+|gemini-[\w.-]*-image[\w.-]*|tts-1[\w-]*|gpt-4o[\w-]*-tts|veo-[\w.-]+|sora-[\w.-]+|eleven_[\w]+|black-forest-labs\/flux[\w./-]*|stable-diffusion[\w./-]*)["'`]/i;
|
|
227
239
|
/** AI calls in a file that names an image, voice or video model. Pure. */
|
|
228
240
|
export const mediaModelCalls = (lines) => lines.some((l) => MEDIA_MODEL.test(l)) ? lines.flatMap((l, i) => (isAiCall(l) ? [i + 1] : [])) : [];
|
|
229
|
-
|
|
241
|
+
// Whole words only: "banner" is not "ban" (field test, 139 repos).
|
|
242
|
+
// Letters may not touch the word, but underscores may: loan_denied counts, banner doesn't.
|
|
243
|
+
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;
|
|
230
244
|
const LOGGED = /\b(logger|log|logging|audit|auditLog|console)\.\w+\s*\(|\binsert\w*\s*\(|\.save\s*\(/;
|
|
231
245
|
rules.push({
|
|
232
246
|
id: "ai.automated-decision",
|
|
@@ -240,7 +254,8 @@ rules.push({
|
|
|
240
254
|
note: "Credit, hiring, admission and similar decisions about people are high-risk under Annex III. Marked Partial: a review step may exist elsewhere.",
|
|
241
255
|
extensions: CODE,
|
|
242
256
|
// A model's output and a decision word on the same line, e.g. status = model.predict(x) > 0.5 ? "approved" : "rejected".
|
|
243
|
-
|
|
257
|
+
// score() and invoke() are too generic: a music score, a memory ranking (field test).
|
|
258
|
+
test: (l) => /\b(predict|predict_proba|classify|generateText|generateObject)\w*\s*\(|\.chat\.completions\.create\s*\(/.test(l) && DECISION.test(l),
|
|
244
259
|
...DRAFT,
|
|
245
260
|
}, {
|
|
246
261
|
id: "ai.call-not-logged",
|
|
@@ -259,12 +274,14 @@ rules.push({
|
|
|
259
274
|
}, {
|
|
260
275
|
id: "ai.hides-being-ai",
|
|
261
276
|
title: "AI told to hide that it is an AI",
|
|
262
|
-
status: "
|
|
277
|
+
status: "partial", severity: "high",
|
|
263
278
|
controls: [{ framework: "eu-ai-act", id: "Art. 50(1)", title: "Transparency for AI interacting with people" }],
|
|
264
279
|
fix: "Remove the instruction and tell users they are talking to an AI.",
|
|
265
|
-
note: "People must be told when they interact with an AI system, unless it is obvious.",
|
|
280
|
+
note: "People must be told when they interact with an AI system, unless it is obvious. Marked Partial: role-play wording can be harmless.",
|
|
266
281
|
extensions: [...CODE, ".md", ".txt", ".yaml", ".yml", ".json"],
|
|
267
|
-
|
|
282
|
+
unlessPath: /(^|\/)(README|CHANGELOG|CONTRIBUTING|SECURITY|LICENSE)[^/]*$|(^|\/)docs?\//i, // text about the rule, not a prompt
|
|
283
|
+
// "Act as a human resources advisor" is a job title, not a disguise.
|
|
284
|
+
test: (l) => /\b(pretend|act|behave|pose)\s+(to\s+be\s+|as\s+|like\s+)(a\s+)?(real\s+)?(human|person)\b(?!\s+(resources?|readable|reviewer))|\bnever\s+(say|reveal|mention|admit|disclose)\b.{0,40}\b(ai|a\.i\.|bot|language model|assistant)\b/i.test(l),
|
|
268
285
|
...DRAFT,
|
|
269
286
|
}, {
|
|
270
287
|
id: "ai.synthetic-media",
|
|
@@ -281,14 +298,14 @@ rules.push({
|
|
|
281
298
|
}, {
|
|
282
299
|
id: "ai.emotion-or-biometric",
|
|
283
300
|
title: "Emotion recognition or biometric categorisation",
|
|
284
|
-
status: "
|
|
301
|
+
status: "partial", severity: "high",
|
|
285
302
|
controls: [
|
|
286
303
|
{ framework: "eu-ai-act", id: "Art. 5(1)(f)", title: "Prohibited: emotion recognition at work and in education" },
|
|
287
304
|
{ framework: "eu-ai-act", id: "Annex III(1)", title: "High-risk: biometrics" },
|
|
288
305
|
{ framework: "gdpr", id: "Art. 9", title: "Special categories of personal data" },
|
|
289
306
|
],
|
|
290
307
|
fix: "Check whether this use is banned or high-risk before shipping. Remove it if it infers emotions of staff or students.",
|
|
291
|
-
note: "Some uses are banned outright since February 2025
|
|
308
|
+
note: "Some uses are banned outright since February 2025 (emotion recognition at work or in education); others are high-risk. Marked Partial: whether a ban applies depends on whose data is analysed and where, which code can't show.",
|
|
292
309
|
extensions: CODE,
|
|
293
310
|
test: (l) => /\b(detect|recogni[sz]e|analy[sz]e|infer|predict)\w*_?(emotion|sentiment_from_face|facial_expression)|\bemotion(s)?\s*[:=]\s*\w*\.(detect|analy)|\bDeepFace\.analyze\s*\(|\bdetect_faces?\b.*\bemotion|\b(face_recognition|FaceAttributes|DetectFaces)\b/i.test(l),
|
|
294
311
|
...DRAFT,
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { Control, Rule } from "../types.js";
|
|
2
|
+
/** True when a signing or encryption secret falls back to a fixed value written in the code. Pure. */
|
|
3
|
+
export declare function fallbackSecret(l: string): boolean;
|
|
2
4
|
export declare const owaspRules: Rule[];
|
|
3
5
|
/** Existing rules that also relate to an OWASP Top 10:2025 category. Added to their controls at load time. */
|
|
4
6
|
export declare const owaspForExisting: Record<string, Control[]>;
|
package/dist/src/rules/owasp.js
CHANGED
|
@@ -24,6 +24,29 @@ function logArgs(l) {
|
|
|
24
24
|
}
|
|
25
25
|
const stripStrings = (l) => l.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
|
|
26
26
|
const rule = (r) => ({ ...r, ...DRAFT });
|
|
27
|
+
// A signing or encryption secret that falls back to text in the code when the env var is missing, e.g.
|
|
28
|
+
// os.getenv("JWT_SECRET", "change-me-in-production") or process.env.SESSION_SECRET || "dev-secret". If the variable
|
|
29
|
+
// is ever unset, everyone who has read the code knows the key (field test, 139 repos: forgeable login tokens).
|
|
30
|
+
// JS: `process.env.X || "v"` / `?? "v"`. Python: `os.getenv("X", "v")` / `os.environ.get("X", "v")`. A comma counts only
|
|
31
|
+
// inside Python's getter, so `assert.notEqual(process.env.X, "v")` is not a fallback (field test, 139 repos).
|
|
32
|
+
const FALLBACK_JS = /(?:process\.env\.|import\.meta\.env\.|process\.env\[\s*["']|Deno\.env\.get\(\s*["'])([A-Z0-9_]+)["']?\s*[\])]?\s*(?:\|\||\?\?)\s*["']([^"']{6,})["']/;
|
|
33
|
+
const FALLBACK_PY = /(?:os\.environ\.get|os\.getenv)\(\s*["']([A-Z0-9_]+)["']\s*,\s*["']([^"']{6,})["']/;
|
|
34
|
+
// Keys that sign or encrypt (sessions, tokens, cookies). Credentials for another service (CLIENT_SECRET, S3 keys) just
|
|
35
|
+
// fail when unset; a signing key with a known default lets anyone forge logins.
|
|
36
|
+
const SIGNING_NAME = /(^|_)(SECRET|SECRET_KEY|JWT_SECRET|JWT_KEY|AUTH_SECRET|SESSION_SECRET|SESSION_KEY|COOKIE_SECRET|SIGNING_KEY|SIGNING_SECRET|HMAC_KEY|HMAC_SECRET|ENCRYPTION_KEY|CALLBACK_SECRET|WEBHOOK_SECRET)$/;
|
|
37
|
+
/** True when a signing or encryption secret falls back to a fixed value written in the code. Pure. */
|
|
38
|
+
export function fallbackSecret(l) {
|
|
39
|
+
if (/^\s*(\*|\/\/|#)/.test(l))
|
|
40
|
+
return false; // documentation, not code
|
|
41
|
+
const m = FALLBACK_JS.exec(l) ?? FALLBACK_PY.exec(l);
|
|
42
|
+
if (!m)
|
|
43
|
+
return false;
|
|
44
|
+
const [, name, value] = m;
|
|
45
|
+
if (!SIGNING_NAME.test(name) || /CLIENT_SECRET$|ACCESS_KEY$|API_SECRET/.test(name))
|
|
46
|
+
return false;
|
|
47
|
+
// Not a key: a URL, a path, a number, a template, the variable's own name, or a header/region-like word.
|
|
48
|
+
return !/^(https?:|\/|\d+$|true$|false$|none$|null$|undefined$)/i.test(value) && !/^\$\{|^<|your[-_]/i.test(value) && value !== name;
|
|
49
|
+
}
|
|
27
50
|
export const owaspRules = [
|
|
28
51
|
// A01 Broken Access Control
|
|
29
52
|
rule({ id: "path.user-input", title: "File path built from request data", status: "gap", severity: "high", controls: [A01],
|
|
@@ -56,16 +79,26 @@ export const owaspRules = [
|
|
|
56
79
|
note: "With a known secret key, attackers can forge sessions, cookies or signed tokens (CWE-1394).", extensions: [...CODE, ".env"],
|
|
57
80
|
// The value must be a quoted literal, or an env-style KEY=value line: `self.secret = secret` is a variable.
|
|
58
81
|
test: (l) => /\b(SECRET_KEY|JWT_SECRET|SESSION_SECRET|secret)\s*[:=]\s*["'](django-insecure-|changeme|change-me|secret\b|mysecret|keyboard cat|dev-secret|supersecret)/i.test(l)
|
|
59
|
-
|| /^\s*(SECRET_KEY|JWT_SECRET|SESSION_SECRET)\s*=\s*(django-insecure-|changeme|change-me|secret\b|mysecret|dev-secret|supersecret)/i.test(l)
|
|
82
|
+
|| /^\s*(SECRET_KEY|JWT_SECRET|SESSION_SECRET)\s*=\s*(django-insecure-|changeme|change-me|secret\b|mysecret|dev-secret|supersecret)/i.test(l)
|
|
83
|
+
|| fallbackSecret(l) }),
|
|
84
|
+
// Python's standard XML parsers don't load external entities (since 3.7.1), so only explicit opt-ins count (field test).
|
|
60
85
|
rule({ id: "xml.external-entities", title: "XML parser may load external entities", status: "partial", severity: "high", controls: [A02],
|
|
61
86
|
fix: "Use defusedxml in Python, or turn off entity resolution and DTD loading in your parser.",
|
|
62
87
|
note: "A crafted XML file can read local files or call internal URLs (XML external entities, CWE-611).", extensions: CODE,
|
|
63
|
-
test: (l) => /resolve_entities\s*=\s*True|\bnoent\s*:\s*true
|
|
88
|
+
test: (l) => /resolve_entities\s*=\s*True|\bnoent\s*:\s*true|feature_external_ges\s*,\s*True/.test(l) }),
|
|
64
89
|
// A03 Software Supply Chain Failures
|
|
65
90
|
rule({ id: "deps.unpinned-version", title: "Dependency with no version limit", status: "gap", severity: "medium", controls: [A03],
|
|
66
91
|
fix: "Pin a version or a range in package.json and commit the lockfile, so every install gets the code you tested.",
|
|
67
92
|
note: "\"*\" or \"latest\" installs whatever is published next, including a compromised release (CWE-1357).", extensions: [".json"], fileName: /^package\.json$/, unlessInKey: /^peerDependencies/, // lockfiles and peer deps use "*" on purpose
|
|
68
|
-
|
|
93
|
+
// In a monorepo, "*" pointing at another package in the same repo is a workspace link, not a download (field test).
|
|
94
|
+
sharedContext: true,
|
|
95
|
+
fileTest: (lines, shared = "") => {
|
|
96
|
+
const local = new Set([...shared.matchAll(/^\s*"name"\s*:\s*"([^"]+)"/gm)].map((m) => m[1]));
|
|
97
|
+
return lines.flatMap((l, i) => {
|
|
98
|
+
const m = /^\s*"((?:@[\w.-]+\/)?[\w.-]+)"\s*:\s*"(\*|latest|x)"\s*,?\s*$/.exec(l);
|
|
99
|
+
return m && !local.has(m[1]) && !/^\s*"peerDependencies"/.test(lines.slice(0, i).reverse().find((x) => /"\w*[dD]ependencies"\s*:/.test(x)) ?? "") ? [i + 1] : [];
|
|
100
|
+
});
|
|
101
|
+
} }),
|
|
69
102
|
rule({ id: "deps.install-script", title: "Install script downloads code", status: "partial", severity: "medium", controls: [A03],
|
|
70
103
|
fix: "Avoid downloading and running code in preinstall or postinstall. Vendor the file or document a manual step.",
|
|
71
104
|
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$/,
|
|
@@ -78,8 +111,10 @@ export const owaspRules = [
|
|
|
78
111
|
fix: "Use the pull_request trigger for workflows that build or run code from a pull request. If you need pull_request_target, never check out the pull request's code in it.",
|
|
79
112
|
note: "pull_request_target runs with your repository's secrets; checking out the contributor's code lets a pull request run with them (CWE-829).", extensions: YAML,
|
|
80
113
|
// A job that only runs once the PR is merged checks out code that is already on the base branch.
|
|
81
|
-
|
|
82
|
-
|
|
114
|
+
// Only the checkout itself counts (a `ref:` or a git command), not an `if:` or an env var that names the head (field test, 139 repos).
|
|
115
|
+
fileTest: (lines) => lines.some((l) => /^\s*(-\s*)?pull_request_target\s*:?\s*$|^\s*on\s*:.*\bpull_request_target\b/.test(l)) && !lines.some((l) => /pull_request\.merged\s*==\s*true/.test(l))
|
|
116
|
+
? lines.flatMap((l, i) => (/github\.event\.pull_request\.head\.(sha|ref)|refs\/pull\/.*\/(head|merge)/.test(l)
|
|
117
|
+
&& /^\s*(-\s*)?ref\s*:|\bgit\s+(checkout|fetch|switch)\b|\bgh\s+pr\s+checkout\b/.test(l) ? [i + 1] : [])) : [] }),
|
|
83
118
|
// A04 Cryptographic Failures
|
|
84
119
|
rule({ id: "crypto.weak-random-token", title: "Predictable random numbers used for a secret", status: "gap", severity: "high", controls: [A04],
|
|
85
120
|
fix: "Use crypto.randomBytes or crypto.randomUUID in Node, or the secrets module in Python, for tokens, codes and IDs people shouldn't guess.",
|
|
@@ -98,12 +133,15 @@ export const owaspRules = [
|
|
|
98
133
|
if (/verify_signature["']?\s*:\s*False|\bverify\s*=\s*False|algorithms\s*[:=]\s*\[\s*["']none["']/i.test(l) && /jwt/i.test(l))
|
|
99
134
|
return true;
|
|
100
135
|
return /\bjwt\.decode\(\s*[\w.]+\s*\)/.test(l) ? "partial" : false; // Node jwt.decode reads a token without verifying it
|
|
101
|
-
}
|
|
136
|
+
},
|
|
137
|
+
// Peeking at a claim before verifying it nearby is fine (field test, 139 repos).
|
|
138
|
+
unlessNear: /\bjwt\.verify\(|\bjwtVerify\(|\bverify(Token|Jwt|JWT)\(/ }),
|
|
102
139
|
// A05 Injection
|
|
103
140
|
rule({ id: "cmd.shell-built", title: "Shell command built from strings", status: "gap", severity: "high", controls: [A05],
|
|
104
141
|
fix: "Pass arguments as an array (execFile, spawn, subprocess.run([...])) instead of building a command string, and never use shell=True with outside input.",
|
|
105
142
|
note: "Characters like ; or $( ) in an inserted value run extra commands (OS command injection, CWE-78). Partial when the value may be fixed text from your own code.", extensions: CODE,
|
|
106
|
-
|
|
143
|
+
// A plain exec() or child_process.exec(), not regex.exec() or db.exec() (field test, 139 repos).
|
|
144
|
+
test: (l) => /(?<![.\w])(exec|execSync)\s*\(\s*(`[^`]*\$\{|["'][^"']*["']\s*\+)|\b(child_process|childProcess|cp)\.(exec|execSync)\s*\(\s*(`[^`]*\$\{|["'][^"']*["']\s*\+)|\bsubprocess\.\w+\([^)]*shell\s*=\s*True|\bos\.(system|popen)\(\s*(f["']|["'][^"']*["']\s*[+%]|\w)/.test(l) ? byInput(l) : false }),
|
|
107
145
|
rule({ id: "code.eval", title: "Code run from a string", status: "gap", severity: "high", controls: [A05],
|
|
108
146
|
fix: "Avoid eval and new Function. Parse data with JSON.parse or a real parser, and map names to functions with a lookup table.",
|
|
109
147
|
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,
|
|
@@ -111,12 +149,12 @@ export const owaspRules = [
|
|
|
111
149
|
// "eval" inside a string is text.
|
|
112
150
|
test: (l) => /\b(def|function|async)\s+eval\s*\(|^\s*((public|private|protected|static|override)\s+)*eval\s*\([^)]*\)\s*(:[^{=]+)?\{\s*$/.test(l) ? false
|
|
113
151
|
: /(^|[^.\w$])eval\s*\(|\bnew Function\s*\(/.test(l.replace(/(["'])(?:\\.|(?!\1).)*\1/g, '""')) ? byInput(l) : false }),
|
|
114
|
-
rule({ id: "xss.raw-html", title: "HTML inserted without escaping", status: "partial", severity: "
|
|
152
|
+
rule({ id: "xss.raw-html", title: "HTML inserted without escaping", status: "partial", severity: "medium", controls: [A05],
|
|
115
153
|
fix: "Set text with textContent, let your framework escape values, or sanitise with DOMPurify before inserting HTML.",
|
|
116
154
|
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,
|
|
117
155
|
// Clearing an element, DOMPurify-cleaned HTML and JSON-LD made with JSON.stringify are safe (field test).
|
|
118
156
|
test: (l) => /\.(innerHTML|outerHTML)\s*[+]?=|\bdocument\.write(ln)?\(|\bdangerouslySetInnerHTML\b|\bv-html=|\{@html\b|\|\s*safe\b|\bmark_safe\(|\bMarkup\(/.test(l)
|
|
119
|
-
&& !/innerHTML\s*=\s*(""|''|``)\s*;?\s*$|DOMPurify\.sanitize|\bsanitize(Html)?\(|__html:\s*JSON\.stringify\(/.test(l)
|
|
157
|
+
&& !/innerHTML\s*=\s*(""|''|``)\s*;?\s*$|DOMPurify\.sanitize|\bsanitize(Html)?\(|\b(esc|escape|escapeHtml|htmlEscape|xss)\(|__html:\s*JSON\.stringify\(/.test(l)
|
|
120
158
|
// Fixed markup written in the code, with nothing inserted, can't carry someone else's input.
|
|
121
159
|
&& !/innerHTML\s*=\s*("[^"$]*"|'[^'$]*'|`[^`$]*`)\s*;?\s*$/.test(l) }),
|
|
122
160
|
rule({ id: "template.user-string", title: "Template built from request data", status: "gap", severity: "high", controls: [A05],
|
|
@@ -143,7 +181,9 @@ export const owaspRules = [
|
|
|
143
181
|
unlessPath: /(^|\/)(locales?|i18n|lang|langs|translations?)\//i, // the word "password" in other languages
|
|
144
182
|
test: (l) => /\b(password|passwd|pwd|db_pass)\s*[:=]\s*["'][^"'\s]{4,}["']/i.test(l) && !/(example|placeholder|changeme|your[_-]|xxx|\*\*\*|<|process\.env|os\.environ|getenv|type\s*[:=]|label|autocomplete)/i.test(l)
|
|
145
183
|
// Translations ("Парола", "Passwort") and obvious stand-ins ("new-password", "hashed-password", "hunter2") are not credentials (field test).
|
|
146
|
-
&& !/[:=]\s*["'][^"']*(passw|hash|redact|hidden|\bhunter2\b|[^\x00-\x7F])/i.test(l)
|
|
184
|
+
&& !/[:=]\s*["'][^"']*(passw|hash|redact|hidden|\bhunter2\b|[^\x00-\x7F])/i.test(l)
|
|
185
|
+
// Validation messages and schema types ({ password: "Required" }, { password: "string" }) are not credentials (field test).
|
|
186
|
+
&& !/[:=]\s*["'](required|string|text|str|number|optional|invalid[^"']*|[A-Z][a-z]+ [^"']*)["']/.test(l) }),
|
|
147
187
|
rule({ id: "jwt.no-expiry", title: "JWT signed without an expiry", status: "partial", severity: "medium", controls: [A07],
|
|
148
188
|
fix: "Add expiresIn (Node) or an exp claim (Python), and keep access tokens short-lived.",
|
|
149
189
|
note: "A stolen token without an expiry works forever (insufficient session expiration, CWE-613). Partial because the expiry may be set in a payload built elsewhere.", extensions: CODE,
|
|
@@ -152,11 +192,15 @@ export const owaspRules = [
|
|
|
152
192
|
rule({ id: "deserialize.unsafe", title: "Unsafe deserialisation", status: "gap", severity: "high", controls: [A08],
|
|
153
193
|
fix: "Use JSON for data from outside. In Python use yaml.safe_load, never pickle or marshal on untrusted data.",
|
|
154
194
|
note: "Deserialising untrusted data with these functions can run attacker code on your server (CWE-502).", extensions: CODE,
|
|
155
|
-
|
|
156
|
-
|
|
195
|
+
// Gap when request data is on the line; otherwise Partial (a model file you made yourself is a different risk).
|
|
196
|
+
// yaml.load is flagged only with an unsafe loader: js-yaml 4 is safe by default, and Safe loaders are safe (field test).
|
|
197
|
+
test: (l) => /\b(c?[Pp]ickle|dill)\.loads?\(|\byaml\.load\([^)]*Loader\s*=\s*(yaml\.)?(Unsafe|Full)?Loader\b|\byaml\.unsafe_load\(|\bmarshal\.loads?\(|\bjsonpickle\.decode\(|\bshelve\.open\(|\b(serialize|nodeSerialize)\.unserialize\(/.test(l) ? byInput(l) : false }), // node-serialize, not an app's own unserialize()
|
|
198
|
+
rule({ id: "html.script-no-sri", title: "Third-party script loaded without an integrity check", status: "partial", severity: "low", controls: [A08],
|
|
157
199
|
fix: "Add integrity and crossorigin attributes with the file's hash, or host the file yourself.",
|
|
158
200
|
note: "If the CDN or package is compromised, the changed script runs on your site (CWE-353, CWE-829).", extensions: MARKUP,
|
|
159
|
-
|
|
201
|
+
// Services that change their script on purpose and don't support SRI (payments, analytics, captchas, widgets) are left out.
|
|
202
|
+
test: (l) => /<script\b[^>]*\bsrc=["']https?:\/\/(?!localhost|127\.0\.0\.1)[^"']+["'][^>]*>/i.test(l) && !/\bintegrity=/i.test(l)
|
|
203
|
+
&& !/js\.stripe\.com|plausible\.io|googletagmanager\.com|google-analytics\.com|google\.com\/recaptcha|challenges\.cloudflare\.com|cdn\.paddle\.com|cdn\.tailwindcss\.com|embed\.reddit|platform\.twitter|connect\.facebook|static\.cloudflareinsights|umami|posthog|hotjar|clarity\.ms/i.test(l) }),
|
|
160
204
|
rule({ id: "cookie.trusted-role", title: "Permissions read from a cookie", status: "partial", severity: "high", controls: [A08, A01],
|
|
161
205
|
fix: "Keep roles and permissions on the server, looked up from the authenticated user, not in a cookie the browser can change.",
|
|
162
206
|
note: "Users can edit their own cookies and give themselves admin rights (CWE-565).", extensions: CODE,
|
|
@@ -178,14 +222,16 @@ export const owaspRules = [
|
|
|
178
222
|
note: "Line breaks in user input can forge fake log entries and mislead an investigation (CWE-117).", extensions: CODE,
|
|
179
223
|
test: (l) => { const a = logArgs(l); return a !== null && /\b(req\.(body|query|params|headers)|request\.(args|form|json|data))\b(?!\.\w)/.test(a); } }),
|
|
180
224
|
// A10 Mishandling of Exceptional Conditions
|
|
181
|
-
|
|
225
|
+
// Partial and low: most ignored errors in practice are deliberate fallbacks (field test, 139 repos: 0 of 6 were real).
|
|
226
|
+
rule({ id: "error.empty-catch", title: "Error caught and ignored", status: "partial", severity: "low", controls: [A10],
|
|
182
227
|
fix: "Handle the error, log it, or let it propagate. If ignoring it is deliberate, say why in a comment and catch only the specific error.",
|
|
183
228
|
note: "Silent failures hide attacks and bugs, and can leave the app running in a broken or unsafe state (CWE-390).", extensions: CODE,
|
|
184
229
|
test: (l) => /\bcatch\s*(\(\s*\w*\s*\))?\s*\{\s*\}|^\s*except(\s+[\w.,() ]+)?\s*:\s*pass\b/.test(l) }),
|
|
185
230
|
rule({ id: "error.stack-to-client", title: "Error details sent to the user", status: "gap", severity: "medium", controls: [A10, A02],
|
|
186
231
|
fix: "Log the full error on the server and send users a short, generic message with a reference id.",
|
|
187
232
|
note: "Stack traces show file paths, library versions and sometimes data, which helps attackers (CWE-209).", extensions: CODE,
|
|
188
|
-
|
|
233
|
+
// A traceback counts only when it goes into a response, not into logs, a CLI or a prompt (field test, 139 repos).
|
|
234
|
+
test: (l) => !LOG_CALL.test(l) && /\bres\.(status\(\d+\)\.)?(send|json|end)\(\s*(\{[^}]*)?\b(err|error|e)\.stack\b|\bres\.(status\(\d+\)\.)?send\(\s*(err|error)\s*\)|\b(return|jsonify|JSONResponse|HttpResponse|Response|make_response)\b[^\n]*\btraceback\.format_exc\(\)/.test(l) }),
|
|
189
235
|
];
|
|
190
236
|
/** Existing rules that also relate to an OWASP Top 10:2025 category. Added to their controls at load time. */
|
|
191
237
|
export const owaspForExisting = {
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import type { Rule } from "../types.js";
|
|
2
2
|
/** Tables created in this SQL file with no "enable row level security" for them in the same file. Pure. */
|
|
3
3
|
export declare function tablesWithoutRls(lines: string[], shared?: string): number[];
|
|
4
|
+
/** In supabase/config.toml: functions with verify_jwt = false whose code shows no caller check of its own. Pure. */
|
|
5
|
+
export declare function functionsWithoutAuth(lines: string[], _shared?: string, files?: Record<string, string>): Array<{
|
|
6
|
+
line: number;
|
|
7
|
+
status: "gap" | "partial";
|
|
8
|
+
}>;
|
|
4
9
|
export declare const stackRules: Rule[];
|
package/dist/src/rules/stack.js
CHANGED
|
@@ -24,6 +24,37 @@ export function tablesWithoutRls(lines, shared) {
|
|
|
24
24
|
});
|
|
25
25
|
return out;
|
|
26
26
|
}
|
|
27
|
+
// Signs that a function checks its caller: a user session, a JWT, a webhook signature or a shared secret.
|
|
28
|
+
const CALLER_CHECK = /auth\.getUser\(|auth\.getClaims\(|getClaims\(|jwtVerify\(|verify(Jwt|JWT|Token|Signature|Webhook|Request)\w*\(|constructEvent(Async)?\(|createHmac\(|timingSafeEqual|crypto\.subtle\.(verify|importKey)|headers\.get\(\s*["'](authorization|x-[\w-]*(secret|signature|token|key|api-key))["']\s*\)|Deno\.env\.get\(\s*["'][A-Z_]*(WEBHOOK|CRON|SHARED|SIGNING|CALLBACK|FUNCTION)[A-Z_]*SECRET["']/i;
|
|
29
|
+
const HIGH_IMPACT = /SERVICE_ROLE|service_role|sb_secret_|api\.openai\.com|api\.anthropic\.com|generativelanguage\.googleapis|OPENAI_API_KEY|ANTHROPIC_API_KEY|GEMINI_API_KEY/;
|
|
30
|
+
/** In supabase/config.toml: functions with verify_jwt = false whose code shows no caller check of its own. Pure. */
|
|
31
|
+
export function functionsWithoutAuth(lines, _shared, files = {}) {
|
|
32
|
+
const out = [];
|
|
33
|
+
let fn = "";
|
|
34
|
+
lines.forEach((l, i) => {
|
|
35
|
+
const head = /^\s*\[functions\.([\w-]+)\]/.exec(l);
|
|
36
|
+
if (head) {
|
|
37
|
+
fn = head[1];
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (/^\s*\[/.test(l)) {
|
|
41
|
+
fn = "";
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (!fn || !/^\s*verify_jwt\s*=\s*false\b/.test(l))
|
|
45
|
+
return;
|
|
46
|
+
const own = Object.entries(files).filter(([p]) => p.includes(`supabase/functions/${fn}/`));
|
|
47
|
+
if (!own.length)
|
|
48
|
+
return; // the code isn't in this repo: nothing to judge
|
|
49
|
+
// Follow imports of shared helpers (../_shared/auth.ts), so a check kept in a helper counts.
|
|
50
|
+
const imported = Object.entries(files).filter(([p]) => /\/_shared\//.test(p) && own.some(([, t]) => t.includes(p.split("/").pop().replace(/\.(ts|js|mjs)$/, ""))));
|
|
51
|
+
const text = [...own, ...imported].map(([, t]) => t).join("\n");
|
|
52
|
+
if (CALLER_CHECK.test(text))
|
|
53
|
+
return;
|
|
54
|
+
out.push({ line: i + 1, status: HIGH_IMPACT.test(own.map(([, t]) => t).join("\n")) ? "gap" : "partial" });
|
|
55
|
+
});
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
27
58
|
// Browser-exposed env prefixes: Next.js, Vite, Expo, Create React App, Nuxt, SvelteKit/Astro (PUBLIC_).
|
|
28
59
|
// No bare PUBLIC_: it matches ordinary constants like PUBLIC_WITH_PRIVATE_AGENT.
|
|
29
60
|
const PUBLIC_ENV = /\b(NEXT_PUBLIC|VITE|EXPO_PUBLIC|REACT_APP|NUXT_PUBLIC)_[A-Z0-9_]*/g;
|
|
@@ -45,12 +76,28 @@ export const stackRules = [
|
|
|
45
76
|
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.",
|
|
46
77
|
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"],
|
|
47
78
|
pathMatch: SUPABASE_DIR,
|
|
48
|
-
|
|
79
|
+
// A read-only policy (for select) that is open on purpose, such as published posts, is common and fine;
|
|
80
|
+
// open insert, update, delete or "all" policies are the risk (field test, 139 repos).
|
|
81
|
+
fileTest: (lines) => lines.flatMap((l, i) => {
|
|
82
|
+
if (!/\b(using|with\s+check)\s*\(\s*true\s*\)/i.test(l))
|
|
83
|
+
return [];
|
|
84
|
+
const start = lines.slice(Math.max(0, i - 8), i + 1).join(" ");
|
|
85
|
+
return /\bfor\s+select\b/i.test(start.slice(start.toLowerCase().lastIndexOf("create policy"))) ? [] : [i + 1];
|
|
86
|
+
}) }),
|
|
87
|
+
rule({ id: "supabase.function-no-auth", title: "Supabase Edge Function anyone can call", status: "partial", severity: "high", controls: [GDPR32, A01],
|
|
88
|
+
fix: "Keep verify_jwt on for this function, or check the caller yourself at the top of the handler: supabase.auth.getUser() for users, or the provider's signature for a webhook.",
|
|
89
|
+
note: "verify_jwt = false switches off Supabase's check that the caller is logged in, so anyone who knows the URL can call the function. Webhooks do this on purpose and verify a signature instead. Lintsure flags it only when the function's own code shows no check of its own. Marked Gap when the function also uses the service-role key or a paid AI API, because then anyone can read or change data, or spend your credits.",
|
|
90
|
+
extensions: [".toml"], fileName: /^config\.toml$/, pathMatch: SUPABASE_DIR,
|
|
91
|
+
sharedFiles: /(^|\/)supabase\/functions\/.+\.(ts|js|mjs)$/,
|
|
92
|
+
fileTest: functionsWithoutAuth }),
|
|
49
93
|
rule({ id: "secret.public-env", title: "Secret in a variable the browser can see", status: "gap", severity: "high", controls: [GDPR32, A04],
|
|
50
94
|
fix: "Rename the variable without the public prefix (NEXT_PUBLIC_, VITE_ and so on), use it only in server code, and rotate the key, since it has already been shipped to browsers.",
|
|
51
95
|
note: "Variables starting with NEXT_PUBLIC_, VITE_, EXPO_PUBLIC_ or REACT_APP_ are copied into the JavaScript every visitor downloads. Anyone can read a secret, service-role or private key put there. Keys that are public by design (Supabase anon, Stripe publishable, Firebase) are not flagged.",
|
|
52
96
|
extensions: [...CODE, ".env"],
|
|
97
|
+
unlessPath: /\.d\.ts$/, // type declarations (env.d.ts) name variables, they don't ship values (field test)
|
|
53
98
|
test: (l) => {
|
|
99
|
+
if (/^\s*(readonly\s+)?[A-Z0-9_]+\??\s*:\s*string\b/.test(l))
|
|
100
|
+
return false; // a typed field, not a value
|
|
54
101
|
const names = l.match(PUBLIC_ENV) ?? [];
|
|
55
102
|
const risky = names.filter((n) => !PUBLIC_BY_DESIGN.test(n));
|
|
56
103
|
return risky.some((n) => /SECRET|PRIVATE|SERVICE_ROLE|PASSWORD|SB_SECRET/.test(n) || (SECRET_SERVICE.test(n) && /KEY|TOKEN/.test(n)));
|
|
@@ -15,14 +15,15 @@ export const standardsForExisting = {
|
|
|
15
15
|
"sql.string-built": [W(89, "SQL Injection")], "nosql.operator-input": [W(20, "Improper Input Validation")],
|
|
16
16
|
"csrf.disabled": [W(352, "Cross-Site Request Forgery")], "path.user-input": [W(22, "Path Traversal")],
|
|
17
17
|
"cmd.shell-built": [W(78, "OS Command Injection"), W(77, "Command Injection")], "code.eval": [W(94, "Code Injection")],
|
|
18
|
-
"llm.output-to-sink": [W(94, "Code Injection")
|
|
18
|
+
"llm.output-to-sink": [W(94, "Code Injection"), W(79, "Cross-site Scripting"), W(78, "OS Command Injection"), W(89, "SQL Injection")],
|
|
19
|
+
"supabase.function-no-auth": [W(306, "Missing Authentication for Critical Function")], "upload.unrestricted": [W(434, "Unrestricted Upload of File with Dangerous Type")],
|
|
19
20
|
"deserialize.unsafe": [W(502, "Deserialization of Untrusted Data")], "ssrf.user-url": [W(918, "Server-Side Request Forgery")],
|
|
20
21
|
"supabase.rls-disabled": [W(862, "Missing Authorization")], "supabase.policy-allows-all": [W(284, "Improper Access Control")],
|
|
21
22
|
"supabase.service-key-in-client": [W(284, "Improper Access Control")], "cookie.trusted-role": [W(863, "Incorrect Authorization")],
|
|
22
23
|
"fs.world-writable": [W(284, "Improper Access Control")], "mass-assignment": [W(20, "Improper Input Validation"), W(639, "Authorization Bypass Through User-Controlled Key")],
|
|
23
24
|
"pii.in-url": [W(200, "Exposure of Sensitive Information")], "error.stack-to-client": [W(200, "Exposure of Sensitive Information")],
|
|
24
25
|
"build.sourcemaps-public": [W(200, "Exposure of Sensitive Information")], "llm.no-output-limit": [W(770, "Allocation of Resources Without Limits or Throttling")],
|
|
25
|
-
|
|
26
|
+
// ai.call-not-logged: no LLM tag. Logging is record-keeping (AI Act Art. 12), not a limit on consumption (LLM06).
|
|
26
27
|
};
|
|
27
28
|
const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
|
|
28
29
|
// Words for what a model sends back, so its output can be followed to a dangerous place on the same line.
|
|
@@ -42,7 +43,8 @@ export const standardsRules = [
|
|
|
42
43
|
fix: "Treat model output like input from a stranger: validate it against what you expect, escape it for HTML, and never run it as code, a shell command or SQL.",
|
|
43
44
|
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.",
|
|
44
45
|
extensions: CODE,
|
|
45
|
-
|
|
46
|
+
// 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] : [])) : []) }),
|
|
46
48
|
rule({ id: "llm.no-output-limit", title: "AI call with no limit on how much it may generate", status: "partial", severity: "low", controls: [LLM06],
|
|
47
49
|
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.",
|
|
48
50
|
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.",
|
|
@@ -58,7 +60,9 @@ export const standardsRules = [
|
|
|
58
60
|
fix: "Turn off cleartext traffic (usesCleartextTraffic false on Android, no NSAllowsArbitraryLoads on iOS) and use HTTPS everywhere. Allow exceptions per domain only if you must.",
|
|
59
61
|
note: "With cleartext allowed, anyone on the same Wi-Fi can read and change what the app sends and receives.",
|
|
60
62
|
extensions: [".xml", ".plist", ".json"], fileName: /^(AndroidManifest\.xml|network_security_config\.xml|Info\.plist|app\.json|app\.config\.json)$/,
|
|
61
|
-
|
|
63
|
+
// The iOS key counts only when its value is <true/> (on the same or next line), not <false/> (field test).
|
|
64
|
+
fileTest: (lines) => lines.flatMap((l, i) => /usesCleartextTraffic["']?\s*[=:]\s*["']?true|cleartextTrafficPermitted\s*=\s*"true"/.test(l)
|
|
65
|
+
|| (/<key>NSAllowsArbitraryLoads<\/key>/.test(l) && /<true\s*\/>/.test(l + (lines[i + 1] ?? ""))) ? [i + 1] : []) }),
|
|
62
66
|
rule({ id: "mobile.backup-allowed", title: "App data included in device backups", status: "partial", severity: "low", controls: [GDPR32],
|
|
63
67
|
fix: "Set android:allowBackup=\"false\", or limit what's backed up with backup rules that leave out tokens and personal data.",
|
|
64
68
|
note: "Backups can be copied off the phone and read elsewhere. Marked Partial: backing up non-sensitive settings is fine.",
|
package/dist/src/types.d.ts
CHANGED
|
@@ -35,10 +35,16 @@ export interface Rule {
|
|
|
35
35
|
test?(line: string): boolean | "partial";
|
|
36
36
|
/** File rule, for checks that need context (e.g. "an AI call with no logging in this file").
|
|
37
37
|
* Returns 1-based line numbers to flag. Must be pure. */
|
|
38
|
-
fileTest?(lines: string[], shared?: string): number
|
|
38
|
+
fileTest?(lines: string[], shared?: string, files?: Record<string, string>): Array<number | {
|
|
39
|
+
line: number;
|
|
40
|
+
status: Status;
|
|
41
|
+
}>;
|
|
39
42
|
/** Optional: fileTest also gets the text of every file this rule reads, joined (for example all Supabase
|
|
40
43
|
* migrations, so row level security switched on in a later file counts). */
|
|
41
44
|
sharedContext?: boolean;
|
|
45
|
+
/** Optional: fileTest also gets these other files by path ("/"-separated, relative to the scanned folder),
|
|
46
|
+
* for checks that need two files read together, such as a config entry and the code it points to. */
|
|
47
|
+
sharedFiles?: RegExp;
|
|
42
48
|
/** Repository check: returns the path of a file the repo should have but doesn't (e.g. "SECURITY.md"),
|
|
43
49
|
* or null. Gets every file path relative to the scanned folder, "/"-separated. Must be pure. */
|
|
44
50
|
repoTest?(files: string[]): string | null;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lintsure/core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.6",
|
|
4
4
|
"description": "Lintsure engine: rules, framework knowledge and reports for readiness checks of AI-written code. Not an audit or legal advice.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
},
|
|
30
30
|
"keywords": [
|
|
31
31
|
"compliance",
|
|
32
|
-
"gdpr",
|
|
32
|
+
"gdpr",
|
|
33
33
|
"eu-ai-act",
|
|
34
34
|
"mcp",
|
|
35
35
|
"static-analysis",
|