@lintsure/core 0.3.5 → 0.3.7
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/assessment.js +1 -1
- package/dist/src/index.d.ts +11 -2
- package/dist/src/index.js +117 -41
- 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/record.d.ts +1 -1
- package/dist/src/record.js +4 -0
- package/dist/src/rules/cra.js +3 -2
- package/dist/src/rules/index.d.ts +4 -0
- package/dist/src/rules/index.js +69 -16
- package/dist/src/rules/owasp.d.ts +2 -0
- package/dist/src/rules/owasp.js +70 -16
- package/dist/src/rules/stack.d.ts +7 -0
- package/dist/src/rules/stack.js +68 -4
- package/dist/src/rules/standards.js +8 -4
- package/dist/src/types.d.ts +7 -1
- package/package.json +2 -2
package/dist/src/assessment.js
CHANGED
|
@@ -33,7 +33,7 @@ export function toAssessmentHtml(r, opts) {
|
|
|
33
33
|
const fws = r.frameworks;
|
|
34
34
|
const sorted = [...r.findings].sort((a, b) => SEV.indexOf(a.severity) - SEV.indexOf(b.severity));
|
|
35
35
|
const rec = r.record;
|
|
36
|
-
const RESULT = { finding: "Finding", observation: "Observation", "no issue found": "No issue found" };
|
|
36
|
+
const RESULT = { finding: "Finding", observation: "Observation", "no issue found": "No issue found", "not checked": "Not checked (no files)" };
|
|
37
37
|
const recordBody = rec ? `<p>A dated record of what this run checked and what it saw. It is a readiness record of an automated code check, not an audit.</p>
|
|
38
38
|
<table class="counts"><tr><th>Check points</th><th>Findings</th><th>Observations</th><th>Accepted</th><th>Fixed since baseline</th></tr>
|
|
39
39
|
<tr><td>${rec.counts.checkPoints}</td><td>${rec.counts.findings}</td><td>${rec.counts.observations}</td><td>${rec.counts.accepted}</td><td>${rec.counts.fixedSinceBaseline}</td></tr></table>
|
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.7";
|
|
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,20 @@ 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;
|
|
44
|
+
/** True for code that doesn't ship: tests, fixtures, examples, docs, stories and seed data. A folder name only counts
|
|
45
|
+
* when it comes before any app or route root in the path: examples/site/app/page.tsx is an example, while
|
|
46
|
+
* app/api/demo/route.ts and src/samples/handler.ts are live code. Pure. */
|
|
47
|
+
export declare function isNonShipping(file: string): boolean;
|
|
39
48
|
/** The JSON object key that opens the block a line sits in, e.g. "peerDependencies". Pure. */
|
|
40
49
|
export declare function enclosingKey(lines: string[], i: number): string;
|
|
41
|
-
/** Marks lines that are only a comment or sit inside a block comment or
|
|
50
|
+
/** Marks lines that are only a comment or sit inside a block comment, Python docstring or multi-line string. Pure. */
|
|
42
51
|
export declare function commentLines(lines: string[], ext: string): boolean[];
|
|
43
52
|
export declare function scan(root: string, frameworks?: FrameworkId[], opts?: RecordOptions): Promise<Report>;
|
|
44
53
|
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.7";
|
|
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,36 @@ 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|factories|\.dev|benchmarks?)\/|\.(test|spec|stories)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.(py|go)$|(^|\/)(conftest\.py|pytest\.ini|tox\.ini)$|(^|\/)\.env\.(example|sample|template|dist)$|(^|\/)(playwright|vitest|jest|cypress)\.config\.[cm]?[jt]s$/i;
|
|
137
|
+
// In Next.js, Remix and Supabase a folder name is a route or a function name: app/api/demo and a function called
|
|
138
|
+
// "test" are live endpoints (review P3). Inside these roots only real test files count as non-shipping.
|
|
139
|
+
// Example, demo, docs and sample folders inside application source (src/, lib/, server/) are shipping code too.
|
|
140
|
+
const LIVE_ROOT = /(^|\/)(app|pages|api|routes|supabase\/functions|src|lib|server)\//;
|
|
141
|
+
const NS_FOLDER = /(^|\/)(tests?|__tests__|__mocks__|mocks?|spec|fixtures?|__fixtures__|e2e|examples?|samples?|demos?|cookbooks?|docs?|stories|storybook|seeds?|seeders|benchmarks?)\//i;
|
|
142
|
+
const TEST_FILE = /(^|\/)__tests__\/|[._-]tests?\/|\.(test|spec|stories)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.(py|go)$|(^|\/)(conftest\.py|pytest\.ini|tox\.ini)$/i;
|
|
143
|
+
/** True for code that doesn't ship: tests, fixtures, examples, docs, stories and seed data. A folder name only counts
|
|
144
|
+
* when it comes before any app or route root in the path: examples/site/app/page.tsx is an example, while
|
|
145
|
+
* app/api/demo/route.ts and src/samples/handler.ts are live code. Pure. */
|
|
146
|
+
export function isNonShipping(file) {
|
|
147
|
+
if (TEST_FILE.test(file))
|
|
148
|
+
return true;
|
|
149
|
+
const live = LIVE_ROOT.exec(file), ns = NS_FOLDER.exec(file);
|
|
150
|
+
if (!live || (ns && ns.index < live.index))
|
|
151
|
+
return NON_SHIPPING.test(file);
|
|
152
|
+
// Under a route root every folder is a URL or function name, so only test files (handled above) are skipped.
|
|
153
|
+
if (/^(app|pages|api|routes|supabase\/functions)$/.test(live[2]))
|
|
154
|
+
return false;
|
|
155
|
+
// Under src/, lib/ or server/, test folders are still tests; example, demo, docs and sample folders are app code.
|
|
156
|
+
return /(^|\/)(tests?|__tests__|__mocks__|mocks?|spec|fixtures?|__fixtures__|e2e|seeds?|seeders|factories|stories|storybook)\//i.test(file.slice(live.index));
|
|
157
|
+
}
|
|
120
158
|
// Rules that also read test files. Not auth.hardcoded-password: test logins are fake by design (field test, 50 repos).
|
|
121
|
-
const SECRET_RULES = new Set(["secret.in-source"
|
|
122
|
-
// Lines a person already reviewed and
|
|
123
|
-
|
|
159
|
+
const SECRET_RULES = new Set(["secret.in-source"]); // not config.default-secret-key: a test secret is a test value (review P19)
|
|
160
|
+
// Lines a person already reviewed. lintsure-ignore and the secret allowlist pragma count only in a comment and apply
|
|
161
|
+
// to every rule. Other linters' markers (noqa, nosec, NOSONAR) don't hide secrets: `# noqa: E501` is about line length.
|
|
162
|
+
const REVIEWED = /(#|\/\/|\/\*|--)\s*(lintsure-ignore|pragma:\s*allowlist secret)\b/;
|
|
163
|
+
const OTHER_LINTER = /#\s*(noqa|nosec)\b|\/\/\s*NOSONAR\b/;
|
|
124
164
|
// Also hand-typed fake keys: alphabet or number runs, words where random text should be, a whole key block on one line.
|
|
125
165
|
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
166
|
/** The JSON object key that opens the block a line sits in, e.g. "peerDependencies". Pure. */
|
|
@@ -135,10 +175,11 @@ export function enclosingKey(lines, i) {
|
|
|
135
175
|
return "";
|
|
136
176
|
}
|
|
137
177
|
const HASH_COMMENTS = new Set([".py", ".rb", ".sh", ".yml", ".yaml", ".toml", ".env"]);
|
|
138
|
-
|
|
178
|
+
const C_LIKE = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".java", ".kt", ".swift", ".go", ".css", ".scss"]);
|
|
179
|
+
/** Marks lines that are only a comment or sit inside a block comment, Python docstring or multi-line string. Pure. */
|
|
139
180
|
export function commentLines(lines, ext) {
|
|
140
|
-
const hash = HASH_COMMENTS.has(ext), py = ext === ".py";
|
|
141
|
-
let block = false, doc = false;
|
|
181
|
+
const hash = HASH_COMMENTS.has(ext), py = ext === ".py", sql = ext === ".sql";
|
|
182
|
+
let block = false, doc = false, quote = "";
|
|
142
183
|
return lines.map((raw) => {
|
|
143
184
|
const t = raw.trim();
|
|
144
185
|
if (block) {
|
|
@@ -147,22 +188,34 @@ export function commentLines(lines, ext) {
|
|
|
147
188
|
return true;
|
|
148
189
|
}
|
|
149
190
|
if (doc) {
|
|
150
|
-
if (
|
|
191
|
+
if (t.includes(quote))
|
|
151
192
|
doc = false;
|
|
152
193
|
return true;
|
|
153
194
|
}
|
|
154
|
-
if (py
|
|
155
|
-
|
|
156
|
-
|
|
195
|
+
if (py) {
|
|
196
|
+
if (t.startsWith("#"))
|
|
197
|
+
return true; // a comment that mentions """ opens no string (review P8)
|
|
198
|
+
const q = t.match(/"""|'''/)?.[0];
|
|
199
|
+
// An odd number of triple quotes opens a string that runs onto the next lines. A docstring line is text;
|
|
200
|
+
// `PROMPT = """` is code whose string continues, and its closing quotes must not open a fake docstring (field test).
|
|
201
|
+
if (q && t.split(q).length % 2 === 0) {
|
|
157
202
|
doc = true;
|
|
158
|
-
|
|
203
|
+
quote = q;
|
|
204
|
+
return /^[rbuf]*("""|''')/i.test(t);
|
|
205
|
+
}
|
|
206
|
+
if (q && /^[rbuf]*("""|''')/i.test(t) && t.endsWith(q))
|
|
207
|
+
return true; // one-line docstring
|
|
159
208
|
}
|
|
209
|
+
// `/* note */ code();` is code: only a line that is all comment counts.
|
|
160
210
|
if (t.startsWith("/*")) {
|
|
161
|
-
|
|
211
|
+
const end = t.indexOf("*/");
|
|
212
|
+
if (end < 0) {
|
|
162
213
|
block = true;
|
|
163
|
-
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
return !t.slice(end + 2).trim();
|
|
164
217
|
}
|
|
165
|
-
return t.startsWith("//") || t.startsWith("*") || t.startsWith("<!--") || (hash && t.startsWith("#"));
|
|
218
|
+
return t.startsWith("//") || (C_LIKE.has(ext) && t.startsWith("*")) || t.startsWith("<!--") || (hash && t.startsWith("#")) || (sql && t.startsWith("--"));
|
|
166
219
|
});
|
|
167
220
|
}
|
|
168
221
|
export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
@@ -189,14 +242,27 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
189
242
|
for (const r of active.filter((x) => x.sharedContext)) {
|
|
190
243
|
const texts = [];
|
|
191
244
|
for (const [k, abs] of all.entries()) {
|
|
192
|
-
const ext =
|
|
193
|
-
if (r.extensions.includes(ext) &&
|
|
194
|
-
|
|
245
|
+
const ext = extOf(abs), file = paths[k];
|
|
246
|
+
if (!r.extensions.includes(ext) || (r.fileName && !r.fileName.test(basename(abs))) || (r.pathMatch && !r.pathMatch.test(file)) || r.unlessPath?.test(file))
|
|
247
|
+
continue;
|
|
248
|
+
const text = await readFile(abs, "utf8").catch(() => "");
|
|
249
|
+
// Commented-out lines don't count: "-- alter table x enable row level security" switches nothing on.
|
|
250
|
+
const comment = commentLines(text.split(/\r?\n/), ext);
|
|
251
|
+
texts.push(text.split(/\r?\n/).filter((_, i) => !comment[i]).join("\n"));
|
|
195
252
|
}
|
|
196
253
|
shared.set(r.id, texts.join("\n"));
|
|
197
254
|
}
|
|
255
|
+
// Rules that read two files together (a config entry and the code it points to) get those files by path.
|
|
256
|
+
const sharedFiles = new Map();
|
|
257
|
+
for (const r of active.filter((x) => x.sharedFiles)) {
|
|
258
|
+
const files = {};
|
|
259
|
+
for (const [k, abs] of all.entries())
|
|
260
|
+
if (r.sharedFiles.test(paths[k]))
|
|
261
|
+
files[paths[k]] = await readFile(abs, "utf8").catch(() => "");
|
|
262
|
+
sharedFiles.set(r.id, files);
|
|
263
|
+
}
|
|
198
264
|
for (const abs of all) {
|
|
199
|
-
const ext =
|
|
265
|
+
const ext = extOf(abs);
|
|
200
266
|
const name = basename(abs);
|
|
201
267
|
const file = relative(root, abs).split(sep).join("/");
|
|
202
268
|
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,13 +271,12 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
205
271
|
const buf = await readFile(abs);
|
|
206
272
|
if (buf.length > MAX_BYTES || buf.includes(0))
|
|
207
273
|
continue; // skip big or binary files
|
|
208
|
-
const
|
|
209
|
-
if (
|
|
274
|
+
const raw = buf.toString("utf8").split(/\r?\n/);
|
|
275
|
+
if (isMinified(raw))
|
|
210
276
|
continue; // minified or generated
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
perRule[r.id] = (perRule[r.id] ?? 0) + 1;
|
|
277
|
+
// A single very long line (a data URL, a long prompt) is ignored on its own; the rest of the file is still read.
|
|
278
|
+
const lines = raw.map((l) => (l.length > MAX_LINE ? "" : l));
|
|
279
|
+
let ran = 0;
|
|
215
280
|
const add = (r, line, status = r.status) => {
|
|
216
281
|
const controls = r.controls.filter((c) => frameworks.includes(c.framework));
|
|
217
282
|
findings.push({
|
|
@@ -220,14 +285,20 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
220
285
|
fingerprint: fingerprint(r.id, file, lines[line - 1] ?? ""),
|
|
221
286
|
});
|
|
222
287
|
};
|
|
223
|
-
// Tests and
|
|
224
|
-
|
|
288
|
+
// Tests, fixtures, examples and docs are full of fake tokens and planted examples: only secret rules look at them,
|
|
289
|
+
// and what they find there is Partial (it may be a throwaway key).
|
|
290
|
+
const inTests = isNonShipping(file);
|
|
225
291
|
const comment = commentLines(lines, ext);
|
|
226
292
|
for (const r of relevant) {
|
|
227
|
-
|
|
293
|
+
const secret = SECRET_RULES.has(r.id);
|
|
294
|
+
if (inTests && !secret)
|
|
228
295
|
continue;
|
|
296
|
+
// Count only what actually ran: a file skipped as a test is not a check point (review P1).
|
|
297
|
+
ran++;
|
|
298
|
+
checkPoints++;
|
|
299
|
+
perRule[r.id] = (perRule[r.id] ?? 0) + 1;
|
|
229
300
|
// Comments describe code, they don't run. A real secret pasted into a comment still counts.
|
|
230
|
-
const skip =
|
|
301
|
+
const skip = secret ? null : comment;
|
|
231
302
|
if (r.test)
|
|
232
303
|
lines.forEach((text, i) => {
|
|
233
304
|
if (skip?.[i])
|
|
@@ -239,15 +310,19 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
239
310
|
return;
|
|
240
311
|
if (inTests && PLACEHOLDER.test(text))
|
|
241
312
|
return; // password="test_password", token="xoxb-test-..."
|
|
242
|
-
if (
|
|
313
|
+
if (inTests && /PRIVATE KEY/.test(text))
|
|
314
|
+
return; // test keys and certificates are fixtures by design (review P24)
|
|
315
|
+
if (REVIEWED.test(text) || (!secret && OTHER_LINTER.test(text)))
|
|
243
316
|
return; // someone already looked at this line and marked it
|
|
244
|
-
add(r, i + 1, hit === "partial" ? "partial" : r.status);
|
|
317
|
+
add(r, i + 1, hit === "partial" || inTests ? "partial" : r.status);
|
|
245
318
|
});
|
|
246
319
|
// File rules see comment lines as blank, so "<img> in a comment" or a commented-out call doesn't count (field test).
|
|
247
320
|
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);
|
|
321
|
+
for (const n of r.fileTest(skip ? lines.map((l, i) => (skip[i] ? "" : l)) : lines, shared.get(r.id), sharedFiles.get(r.id)))
|
|
322
|
+
typeof n === "number" ? add(r, n) : add(r, n.line, n.status);
|
|
250
323
|
}
|
|
324
|
+
if (ran)
|
|
325
|
+
filesChecked++;
|
|
251
326
|
}
|
|
252
327
|
// Auditor: one finding per rule per line; stable order.
|
|
253
328
|
const seen = new Set();
|
|
@@ -260,8 +335,9 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
260
335
|
rulesVersion: RULES_VERSION,
|
|
261
336
|
frameworks: [...frameworks].sort(),
|
|
262
337
|
findings: deduped,
|
|
263
|
-
// Only the Checker sets Met: a rule that
|
|
264
|
-
|
|
338
|
+
// Only the Checker sets Met: a rule that read at least one file and found nothing. A rule with nothing to read
|
|
339
|
+
// (mobile rules in a web app) is not Met: nothing was checked.
|
|
340
|
+
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
341
|
outside: outsideFor(frameworks),
|
|
266
342
|
filesChecked,
|
|
267
343
|
disclaimer: DISCLAIMER,
|
|
@@ -272,7 +348,7 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
272
348
|
const LABEL = { gap: "Gap", partial: "Partial", met: "Met", outside: "Outside code" };
|
|
273
349
|
const acceptedLine = (a) => `> Accepted by ${a.by} on ${a.date}: ${a.reason}` + (a.expired ? ` (review date ${a.reviewBy} has passed: look at it again)` : a.reviewBy ? ` (review by ${a.reviewBy})` : "");
|
|
274
350
|
const ctl = (c) => c.map((x) => `${x.framework.toUpperCase()} ${x.id}`).join(" · ");
|
|
275
|
-
const RESULT = { finding: "Finding", observation: "Observation", "no issue found": "No issue found" };
|
|
351
|
+
const RESULT = { finding: "Finding", observation: "Observation", "no issue found": "No issue found", "not checked": "Not checked (no files)" };
|
|
276
352
|
/** The record block: identification, scope, what applies and why, counts, and results by control. */
|
|
277
353
|
function recordLines(r) {
|
|
278
354
|
const c = r.record;
|
|
@@ -294,7 +370,7 @@ function recordLines(r) {
|
|
|
294
370
|
"### What applies, and why", "",
|
|
295
371
|
...c.applies.map((a) => `- **${a.framework}**: ${a.why}`), "",
|
|
296
372
|
"### Results by control", "",
|
|
297
|
-
"A finding is a Gap the code itself shows. An observation is a Partial that depends on context a person must confirm. No issue found means the rules found nothing in the files they read, not that the control is met.", "",
|
|
373
|
+
"A finding is a Gap the code itself shows. An observation is a Partial that depends on context a person must confirm. No issue found means the rules found nothing in the files they read, not that the control is met. Not checked means no file of the right kind was read for that control.", "",
|
|
298
374
|
"| Framework | Control | Rules | Check points | Result | Items |", "|---|---|---|---|---|---|",
|
|
299
375
|
...c.byControl.map((b) => `| ${b.framework} | ${b.control} ${b.title} | ${b.rules.join(", ")} | ${b.checkPoints} | ${RESULT[b.result]} | ${b.findingIds.join(", ") || "-"} |`), "",
|
|
300
376
|
];
|
|
@@ -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/record.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { FrameworkId, Report, Severity } from "./types.js";
|
|
2
|
-
export type ControlResult = "finding" | "observation" | "no issue found";
|
|
2
|
+
export type ControlResult = "finding" | "observation" | "no issue found" | "not checked";
|
|
3
3
|
export interface CheckRecord {
|
|
4
4
|
/** Stable id for this run, for example LS-20261108-1a2b3c. */
|
|
5
5
|
id: string;
|
package/dist/src/record.js
CHANGED
|
@@ -41,6 +41,10 @@ export async function buildRecord(r, root, checkPoints, perRule, rulesRun, ruleC
|
|
|
41
41
|
row.checkPoints += perRule[rule.id] ?? 0;
|
|
42
42
|
controls.set(key, row);
|
|
43
43
|
}
|
|
44
|
+
// A control whose rules ran on no file was not checked; "no issue found" would claim more than the scan did (review P2).
|
|
45
|
+
for (const row of controls.values())
|
|
46
|
+
if (row.checkPoints === 0)
|
|
47
|
+
row.result = "not checked";
|
|
44
48
|
for (const f of r.findings) {
|
|
45
49
|
if (f.accepted && !f.accepted.expired)
|
|
46
50
|
continue;
|
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)
|
|
@@ -65,7 +65,8 @@ export function untrustedInRun(lines) {
|
|
|
65
65
|
const indent = l.search(/\S/);
|
|
66
66
|
if (runIndent >= 0 && indent >= 0 && indent <= runIndent)
|
|
67
67
|
runIndent = -1;
|
|
68
|
-
|
|
68
|
+
// Also `script:` in actions/github-script, where the text becomes JavaScript instead of shell (review P17).
|
|
69
|
+
const run = /^(\s*-?\s*)(?:run|script):\s*(.*)$/.exec(l);
|
|
69
70
|
if (run) {
|
|
70
71
|
if (/^[|>][-+]?\s*$/.test(run[2])) {
|
|
71
72
|
runIndent = run[1].length;
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import type { Rule } from "../types.js";
|
|
2
|
+
/** A Supabase (or any) JWT whose payload says role: service_role. Decoded exactly, so near-zero false alarms. Pure. */
|
|
3
|
+
export declare function serviceRoleJwt(l: string): boolean;
|
|
4
|
+
/** A database connection URL with an inline password that isn't a local default or a placeholder. Pure. */
|
|
5
|
+
export declare function dbUrlWithPassword(l: string): boolean;
|
|
2
6
|
export declare const rules: Rule[];
|
|
3
7
|
export declare const isAiCall: (l: string) => boolean;
|
|
4
8
|
/** The first AI call in a file with no log or save between 10 lines above and 30 below (one finding per file). Pure. */
|
package/dist/src/rules/index.js
CHANGED
|
@@ -44,6 +44,35 @@ const KEY_FORMATS = new RegExp([
|
|
|
44
44
|
].join("|"));
|
|
45
45
|
// Example values from provider docs (AKIAIOSFODNN7EXAMPLE and the like) and obvious fill-ins.
|
|
46
46
|
const DOC_EXAMPLE = /EXAMPLE|X{6,}|x{6,}|0{12,}|1234567890abcdef/;
|
|
47
|
+
// More fixed-prefix secrets this audience leaks: Stripe webhook secrets, Supabase secret keys, Resend keys (review P13).
|
|
48
|
+
const MORE_KEYS = /\bwhsec_[0-9A-Za-z]{24,}|\bsb_secret_[0-9A-Za-z_-]{20,}|\bre_[0-9A-Za-z]{8,}_[0-9A-Za-z]{16,}/;
|
|
49
|
+
/** A Supabase (or any) JWT whose payload says role: service_role. Decoded exactly, so near-zero false alarms. Pure. */
|
|
50
|
+
export function serviceRoleJwt(l) {
|
|
51
|
+
for (const m of l.matchAll(/eyJ[\w-]{10,}\.(eyJ[\w-]{10,})\.[\w-]{10,}/g)) {
|
|
52
|
+
try {
|
|
53
|
+
if (/"role"\s*:\s*"service_role"/.test(Buffer.from(m[1], "base64url").toString("utf8")))
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
catch { /* not a JWT */ }
|
|
57
|
+
}
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
/** A database connection URL with an inline password that isn't a local default or a placeholder. Pure. */
|
|
61
|
+
export function dbUrlWithPassword(l) {
|
|
62
|
+
if (/placeholder|e\.g\.|for example|format:/i.test(l))
|
|
63
|
+
return false; // documentation of the format, not a value
|
|
64
|
+
const m = /\b(postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|rediss?):\/\/([^:\s"'`/@]+):([^@\s"'`]{4,})@([^/\s"'`:?]+)/.exec(l);
|
|
65
|
+
if (!m)
|
|
66
|
+
return false;
|
|
67
|
+
const [, , user, pass, host] = m;
|
|
68
|
+
// Only internet hosts: single names (db, hoppscotch-db) are containers on a private network; example.com is a sample.
|
|
69
|
+
if (!host.includes(".") || /^(localhost|127\.|0\.0\.0\.0|10\.|192\.168\.)|(^|\.)example\.(com|org|net)$|\.local$|\.internal$/i.test(host))
|
|
70
|
+
return false;
|
|
71
|
+
// Values built at run time ({$pass}, ${pass}, %s) and stand-ins (pass, testpass, changeme) aren't stored passwords (field test, 139 repos).
|
|
72
|
+
if (/[{}$%<>[\]]/.test(user + pass + host))
|
|
73
|
+
return false;
|
|
74
|
+
return pass !== user && !/^(pass|pw|pwd|test\w*|dev\w*|demo\w*|local\w*)$|password|passwd|changeme|secret|example|xxx|your|\*{3}|placeholder|postgres$|root$|admin$/i.test(pass);
|
|
75
|
+
}
|
|
47
76
|
export const rules = [
|
|
48
77
|
{
|
|
49
78
|
id: "pii.logged",
|
|
@@ -68,9 +97,16 @@ export const rules = [
|
|
|
68
97
|
],
|
|
69
98
|
fix: "Move the secret to an environment variable or secrets manager, then rotate it: it is already in your git history.",
|
|
70
99
|
note: "Anyone with read access to the repo, or a leaked copy of it, can use this key.",
|
|
71
|
-
|
|
100
|
+
// Every text format a key ends up in: shell, Terraform, Go, Ruby, PHP, notebooks, Vue and Svelte files, Dockerfiles
|
|
101
|
+
// ("" is extensionless files), not only JavaScript and Python (review P13).
|
|
102
|
+
extensions: [...CODE, ".env", ".json", ".yaml", ".yml", ".toml", ".sh", ".bash", ".zsh", ".ps1", ".vue", ".svelte", ".astro", ".tf", ".tfvars", ".go", ".rb", ".php", ".java", ".kt", ".cs", ".swift", ".ipynb", ".properties", ".ini", ".cfg", ".conf", ".xml", ".gradle", ""],
|
|
72
103
|
// A key header that ends right at a quote (or "...") is code looking for a key, e.g. key.includes('-----BEGIN PRIVATE KEY-----').
|
|
73
|
-
test: (l) => {
|
|
104
|
+
test: (l) => {
|
|
105
|
+
if (/\bplaceholder\s*[=:]/i.test(l))
|
|
106
|
+
return false; // a form's example text (placeholder="sk_live_...")
|
|
107
|
+
const m = l.match(KEY_FORMATS) ?? l.match(MORE_KEYS);
|
|
108
|
+
return (!!m && !DOC_EXAMPLE.test(m[0]) && !/PRIVATE KEY( BLOCK)?-----(["'`]|\.\.\.)/.test(l)) || serviceRoleJwt(l) || dbUrlWithPassword(l);
|
|
109
|
+
},
|
|
74
110
|
...DRAFT,
|
|
75
111
|
},
|
|
76
112
|
{
|
|
@@ -83,7 +119,8 @@ export const rules = [
|
|
|
83
119
|
fix: "Use https:// for every external call.",
|
|
84
120
|
note: "Marked Partial: the call may carry no sensitive data. Confirm, then switch to HTTPS anyway.",
|
|
85
121
|
extensions: CODE,
|
|
86
|
-
|
|
122
|
+
// Loopback, private ranges and single-label service names (http://redis:6379) stay on the machine or network (field test).
|
|
123
|
+
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
124
|
...DRAFT,
|
|
88
125
|
},
|
|
89
126
|
{
|
|
@@ -92,9 +129,8 @@ export const rules = [
|
|
|
92
129
|
status: "gap", severity: "high",
|
|
93
130
|
controls: [
|
|
94
131
|
{ framework: "gdpr", id: "Art. 5(1)(c)", title: "Data minimisation" },
|
|
95
|
-
{ framework: "gdpr", id: "Art. 28", title: "Processors" },
|
|
96
132
|
],
|
|
97
|
-
fix: "Send an internal user ID instead of the email or name,
|
|
133
|
+
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
134
|
note: "Analytics vendors keep what you send them. Personal data there needs a lawful basis and a processing agreement.",
|
|
99
135
|
extensions: CODE,
|
|
100
136
|
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 +160,12 @@ export const rules = [
|
|
|
124
160
|
note: "MD5 and SHA-1 are fast, so leaked hashes can be cracked quickly.",
|
|
125
161
|
extensions: CODE,
|
|
126
162
|
// Sentences in strings ("the server asked for an MD5 password hash") are messages, not hashing (field test).
|
|
127
|
-
|
|
163
|
+
// The hash must be applied to a password. HMAC, HTTP Digest and fixed vendor formats require the algorithm;
|
|
164
|
+
// they don't store passwords (field test, 139 repos).
|
|
165
|
+
test: (l) => {
|
|
166
|
+
const c = l.replace(/(["'`])(?:(?!\1).)*\s(?:(?!\1).)*\1/g, '""');
|
|
167
|
+
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);
|
|
168
|
+
},
|
|
128
169
|
...DRAFT,
|
|
129
170
|
},
|
|
130
171
|
{
|
|
@@ -153,12 +194,18 @@ export const rules = [
|
|
|
153
194
|
test: (l) => {
|
|
154
195
|
// SQL keywords are written in UPPER or lower case; "Select a plan from..." in a sentence is not SQL.
|
|
155
196
|
// A keyword after a dot or before "(" is a method call (hash.update(...), select(Model) in SQLAlchemy), not SQL text.
|
|
156
|
-
|
|
197
|
+
// A statement's shape: SELECT ... FROM, INSERT INTO, UPDATE x SET, DELETE FROM. "Could not update user ${id} from ..." is a message.
|
|
198
|
+
if (!/(?<![.\w])(SELECT\b(?!\s*\()[^"'`]*\bFROM\b|INSERT\s+INTO\b|UPDATE\s+[\w."`${}]+\s+SET\b|DELETE\s+FROM\b)/i.test(l))
|
|
199
|
+
return false;
|
|
200
|
+
if (/\b(throw|Error|message|msg)\b/.test(l) && !/\.(query|execute|exec|raw|run|prepare|all|get)\s*\(/.test(l))
|
|
157
201
|
return false;
|
|
158
202
|
const parts = [...l.matchAll(SQL_PARTS)].map((m) => m.slice(1).find(Boolean) ?? "");
|
|
159
203
|
if (!parts.length)
|
|
160
204
|
return false;
|
|
161
|
-
|
|
205
|
+
if (parts.some((p) => USER_INPUT.test(p)))
|
|
206
|
+
return true;
|
|
207
|
+
// Table and column names, placeholder lists and CONSTANTS are your own text, not values (field test, 139 repos).
|
|
208
|
+
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
209
|
},
|
|
163
210
|
// Tagged templates from Postgres.js, Drizzle, Prisma and similar send ${} values as parameters, not as SQL text (field test).
|
|
164
211
|
unlessNear: /(?<![.\w])(sql|safeSql|tx|Prisma\.sql)(<[^>`]*>)?\s*`|\$queryRaw\s*`/,
|
|
@@ -173,12 +220,13 @@ export const rules = [
|
|
|
173
220
|
note: "Marked Partial: fine for a public, read-only API. Risky when the API uses cookies or returns user data.",
|
|
174
221
|
extensions: CODE,
|
|
175
222
|
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),
|
|
223
|
+
unlessPath: /(^|\/)(vite|webpack|rollup|next|nuxt|astro)\.config\.|openapi|swagger/i, // dev servers and published API specs (field test)
|
|
176
224
|
...DRAFT,
|
|
177
225
|
},
|
|
178
226
|
{
|
|
179
227
|
id: "session.cookie-insecure",
|
|
180
228
|
title: "Session cookie without Secure or HttpOnly",
|
|
181
|
-
status: "partial", severity: "
|
|
229
|
+
status: "partial", severity: "low",
|
|
182
230
|
controls: [],
|
|
183
231
|
fix: "Set secure: true and httpOnly: true on session cookies.",
|
|
184
232
|
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 +274,9 @@ export const unloggedAiCalls = (lines) => {
|
|
|
226
274
|
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
275
|
/** AI calls in a file that names an image, voice or video model. Pure. */
|
|
228
276
|
export const mediaModelCalls = (lines) => lines.some((l) => MEDIA_MODEL.test(l)) ? lines.flatMap((l, i) => (isAiCall(l) ? [i + 1] : [])) : [];
|
|
229
|
-
|
|
277
|
+
// Whole words only: "banner" is not "ban" (field test, 139 repos).
|
|
278
|
+
// Letters may not touch the word, but underscores may: loan_denied counts, banner doesn't.
|
|
279
|
+
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
280
|
const LOGGED = /\b(logger|log|logging|audit|auditLog|console)\.\w+\s*\(|\binsert\w*\s*\(|\.save\s*\(/;
|
|
231
281
|
rules.push({
|
|
232
282
|
id: "ai.automated-decision",
|
|
@@ -240,7 +290,8 @@ rules.push({
|
|
|
240
290
|
note: "Credit, hiring, admission and similar decisions about people are high-risk under Annex III. Marked Partial: a review step may exist elsewhere.",
|
|
241
291
|
extensions: CODE,
|
|
242
292
|
// A model's output and a decision word on the same line, e.g. status = model.predict(x) > 0.5 ? "approved" : "rejected".
|
|
243
|
-
|
|
293
|
+
// score() and invoke() are too generic: a music score, a memory ranking (field test).
|
|
294
|
+
test: (l) => /\b(predict|predict_proba|classify|generateText|generateObject)\w*\s*\(|\.chat\.completions\.create\s*\(/.test(l) && DECISION.test(l),
|
|
244
295
|
...DRAFT,
|
|
245
296
|
}, {
|
|
246
297
|
id: "ai.call-not-logged",
|
|
@@ -259,12 +310,14 @@ rules.push({
|
|
|
259
310
|
}, {
|
|
260
311
|
id: "ai.hides-being-ai",
|
|
261
312
|
title: "AI told to hide that it is an AI",
|
|
262
|
-
status: "
|
|
313
|
+
status: "partial", severity: "high",
|
|
263
314
|
controls: [{ framework: "eu-ai-act", id: "Art. 50(1)", title: "Transparency for AI interacting with people" }],
|
|
264
315
|
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.",
|
|
316
|
+
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
317
|
extensions: [...CODE, ".md", ".txt", ".yaml", ".yml", ".json"],
|
|
267
|
-
|
|
318
|
+
unlessPath: /(^|\/)(README|CHANGELOG|CONTRIBUTING|SECURITY|LICENSE)[^/]*$|(^|\/)docs?\//i, // text about the rule, not a prompt
|
|
319
|
+
// "Act as a human resources advisor" is a job title, not a disguise.
|
|
320
|
+
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
321
|
...DRAFT,
|
|
269
322
|
}, {
|
|
270
323
|
id: "ai.synthetic-media",
|
|
@@ -281,14 +334,14 @@ rules.push({
|
|
|
281
334
|
}, {
|
|
282
335
|
id: "ai.emotion-or-biometric",
|
|
283
336
|
title: "Emotion recognition or biometric categorisation",
|
|
284
|
-
status: "
|
|
337
|
+
status: "partial", severity: "high",
|
|
285
338
|
controls: [
|
|
286
339
|
{ framework: "eu-ai-act", id: "Art. 5(1)(f)", title: "Prohibited: emotion recognition at work and in education" },
|
|
287
340
|
{ framework: "eu-ai-act", id: "Annex III(1)", title: "High-risk: biometrics" },
|
|
288
341
|
{ framework: "gdpr", id: "Art. 9", title: "Special categories of personal data" },
|
|
289
342
|
],
|
|
290
343
|
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
|
|
344
|
+
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
345
|
extensions: CODE,
|
|
293
346
|
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
347
|
...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],
|
|
@@ -55,17 +78,32 @@ export const owaspRules = [
|
|
|
55
78
|
fix: "Generate a long random secret per environment and load it from an environment variable or secret manager.",
|
|
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
|
-
|
|
59
|
-
|
|
81
|
+
// Key names are matched as written (secret, SECRET_KEY, jwtSecret), not case-insensitively: a field-name enum such as
|
|
82
|
+
// `Secret: 'secret'` or a label `SECRET: "SECRET"` names a field, it doesn't set a key (review P19).
|
|
83
|
+
test: (l) => {
|
|
84
|
+
const m = /\b(SECRET_KEY|JWT_SECRET|SESSION_SECRET|secret|secretKey|jwtSecret|sessionSecret|secret_key|jwt_secret)\s*[:=]\s*["'](django-insecure-|changeme|change-me|secret\b|mysecret|keyboard cat|dev-secret|supersecret)([^"']*)["']?/.exec(l);
|
|
85
|
+
if (m && !(m[1] !== m[1].toLowerCase() && (m[2] + m[3]).toLowerCase() === m[1].toLowerCase()))
|
|
86
|
+
return true;
|
|
87
|
+
return /^\s*(SECRET_KEY|JWT_SECRET|SESSION_SECRET)\s*=\s*(django-insecure-|changeme|change-me|secret\b|mysecret|dev-secret|supersecret)/.test(l) || fallbackSecret(l);
|
|
88
|
+
} }),
|
|
89
|
+
// Python's standard XML parsers don't load external entities (since 3.7.1), so only explicit opt-ins count (field test).
|
|
60
90
|
rule({ id: "xml.external-entities", title: "XML parser may load external entities", status: "partial", severity: "high", controls: [A02],
|
|
61
91
|
fix: "Use defusedxml in Python, or turn off entity resolution and DTD loading in your parser.",
|
|
62
92
|
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
|
|
93
|
+
test: (l) => /resolve_entities\s*=\s*True|\bnoent\s*:\s*true|feature_external_ges\s*,\s*True/.test(l) }),
|
|
64
94
|
// A03 Software Supply Chain Failures
|
|
65
95
|
rule({ id: "deps.unpinned-version", title: "Dependency with no version limit", status: "gap", severity: "medium", controls: [A03],
|
|
66
96
|
fix: "Pin a version or a range in package.json and commit the lockfile, so every install gets the code you tested.",
|
|
67
97
|
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
|
-
|
|
98
|
+
// In a monorepo, "*" pointing at another package in the same repo is a workspace link, not a download (field test).
|
|
99
|
+
sharedContext: true,
|
|
100
|
+
fileTest: (lines, shared = "") => {
|
|
101
|
+
const local = new Set([...shared.matchAll(/^\s*"name"\s*:\s*"([^"]+)"/gm)].map((m) => m[1]));
|
|
102
|
+
return lines.flatMap((l, i) => {
|
|
103
|
+
const m = /^\s*"((?:@[\w.-]+\/)?[\w.-]+)"\s*:\s*"(\*|latest|x)"\s*,?\s*$/.exec(l);
|
|
104
|
+
return m && !local.has(m[1]) && !/^\s*"peerDependencies"/.test(lines.slice(0, i).reverse().find((x) => /"\w*[dD]ependencies"\s*:/.test(x)) ?? "") ? [i + 1] : [];
|
|
105
|
+
});
|
|
106
|
+
} }),
|
|
69
107
|
rule({ id: "deps.install-script", title: "Install script downloads code", status: "partial", severity: "medium", controls: [A03],
|
|
70
108
|
fix: "Avoid downloading and running code in preinstall or postinstall. Vendor the file or document a manual step.",
|
|
71
109
|
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 +116,10 @@ export const owaspRules = [
|
|
|
78
116
|
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
117
|
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
118
|
// A job that only runs once the PR is merged checks out code that is already on the base branch.
|
|
81
|
-
|
|
82
|
-
|
|
119
|
+
// 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).
|
|
120
|
+
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))
|
|
121
|
+
? lines.flatMap((l, i) => (/github\.event\.pull_request\.head\.(sha|ref)|refs\/pull\/.*\/(head|merge)/.test(l)
|
|
122
|
+
&& /^\s*(-\s*)?ref\s*:|\bgit\s+(checkout|fetch|switch)\b|\bgh\s+pr\s+checkout\b/.test(l) ? [i + 1] : [])) : [] }),
|
|
83
123
|
// A04 Cryptographic Failures
|
|
84
124
|
rule({ id: "crypto.weak-random-token", title: "Predictable random numbers used for a secret", status: "gap", severity: "high", controls: [A04],
|
|
85
125
|
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 +138,16 @@ export const owaspRules = [
|
|
|
98
138
|
if (/verify_signature["']?\s*:\s*False|\bverify\s*=\s*False|algorithms\s*[:=]\s*\[\s*["']none["']/i.test(l) && /jwt/i.test(l))
|
|
99
139
|
return true;
|
|
100
140
|
return /\bjwt\.decode\(\s*[\w.]+\s*\)/.test(l) ? "partial" : false; // Node jwt.decode reads a token without verifying it
|
|
101
|
-
}
|
|
141
|
+
},
|
|
142
|
+
// Peeking at a claim before verifying it nearby is fine (field test, 139 repos).
|
|
143
|
+
// Python peek-then-verify: a second decode with a key and an algorithms list nearby (review P21).
|
|
144
|
+
unlessNear: /\bjwt\.verify\(|\bjwtVerify\(|\bverify(Token|Jwt|JWT)\(|\bjwt\.decode\([^)]*\balgorithms\s*=/ }),
|
|
102
145
|
// A05 Injection
|
|
103
146
|
rule({ id: "cmd.shell-built", title: "Shell command built from strings", status: "gap", severity: "high", controls: [A05],
|
|
104
147
|
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
148
|
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
|
-
|
|
149
|
+
// A plain exec() or child_process.exec(), not regex.exec() or db.exec() (field test, 139 repos).
|
|
150
|
+
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
151
|
rule({ id: "code.eval", title: "Code run from a string", status: "gap", severity: "high", controls: [A05],
|
|
108
152
|
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
153
|
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 +155,12 @@ export const owaspRules = [
|
|
|
111
155
|
// "eval" inside a string is text.
|
|
112
156
|
test: (l) => /\b(def|function|async)\s+eval\s*\(|^\s*((public|private|protected|static|override)\s+)*eval\s*\([^)]*\)\s*(:[^{=]+)?\{\s*$/.test(l) ? false
|
|
113
157
|
: /(^|[^.\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: "
|
|
158
|
+
rule({ id: "xss.raw-html", title: "HTML inserted without escaping", status: "partial", severity: "medium", controls: [A05],
|
|
115
159
|
fix: "Set text with textContent, let your framework escape values, or sanitise with DOMPurify before inserting HTML.",
|
|
116
160
|
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
161
|
// Clearing an element, DOMPurify-cleaned HTML and JSON-LD made with JSON.stringify are safe (field test).
|
|
118
162
|
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)
|
|
163
|
+
&& !/innerHTML\s*=\s*(""|''|``)\s*;?\s*$|DOMPurify\.sanitize|\bsanitize(Html)?\(|\b(esc|escape|escapeHtml|htmlEscape|xss)\(|__html:\s*JSON\.stringify\(/.test(l)
|
|
120
164
|
// Fixed markup written in the code, with nothing inserted, can't carry someone else's input.
|
|
121
165
|
&& !/innerHTML\s*=\s*("[^"$]*"|'[^'$]*'|`[^`$]*`)\s*;?\s*$/.test(l) }),
|
|
122
166
|
rule({ id: "template.user-string", title: "Template built from request data", status: "gap", severity: "high", controls: [A05],
|
|
@@ -143,7 +187,11 @@ export const owaspRules = [
|
|
|
143
187
|
unlessPath: /(^|\/)(locales?|i18n|lang|langs|translations?)\//i, // the word "password" in other languages
|
|
144
188
|
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
189
|
// 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)
|
|
190
|
+
&& !/[:=]\s*["'][^"']*(passw|hash|redact|hidden|\bhunter2\b|[^\x00-\x7F])/i.test(l)
|
|
191
|
+
// Validation messages and schema types ({ password: "Required" }, { password: "string" }) are not credentials (field test).
|
|
192
|
+
&& !/[:=]\s*["'](required|string|text|str|number|optional|invalid[^"']*|[A-Z][a-z]+ [^"']*)["']/.test(l)
|
|
193
|
+
// Column types and ALL-CAPS labels (`password: 'String'`, `PASSWORD: "SECRET"`) aren't credentials (review P20).
|
|
194
|
+
&& !/[:=]\s*["'](String|Number|Boolean|Text|varchar(\(\d+\))?|VARCHAR(\(\d+\))?|[A-Z][A-Z_]*)["']/.test(l) }),
|
|
147
195
|
rule({ id: "jwt.no-expiry", title: "JWT signed without an expiry", status: "partial", severity: "medium", controls: [A07],
|
|
148
196
|
fix: "Add expiresIn (Node) or an exp claim (Python), and keep access tokens short-lived.",
|
|
149
197
|
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 +200,15 @@ export const owaspRules = [
|
|
|
152
200
|
rule({ id: "deserialize.unsafe", title: "Unsafe deserialisation", status: "gap", severity: "high", controls: [A08],
|
|
153
201
|
fix: "Use JSON for data from outside. In Python use yaml.safe_load, never pickle or marshal on untrusted data.",
|
|
154
202
|
note: "Deserialising untrusted data with these functions can run attacker code on your server (CWE-502).", extensions: CODE,
|
|
155
|
-
|
|
156
|
-
|
|
203
|
+
// Gap when request data is on the line; otherwise Partial (a model file you made yourself is a different risk).
|
|
204
|
+
// yaml.load is flagged only with an unsafe loader: js-yaml 4 is safe by default, and Safe loaders are safe (field test).
|
|
205
|
+
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()
|
|
206
|
+
rule({ id: "html.script-no-sri", title: "Third-party script loaded without an integrity check", status: "partial", severity: "low", controls: [A08],
|
|
157
207
|
fix: "Add integrity and crossorigin attributes with the file's hash, or host the file yourself.",
|
|
158
208
|
note: "If the CDN or package is compromised, the changed script runs on your site (CWE-353, CWE-829).", extensions: MARKUP,
|
|
159
|
-
|
|
209
|
+
// Services that change their script on purpose and don't support SRI (payments, analytics, captchas, widgets) are left out.
|
|
210
|
+
test: (l) => /<script\b[^>]*\bsrc=["']https?:\/\/(?!localhost|127\.0\.0\.1)[^"']+["'][^>]*>/i.test(l) && !/\bintegrity=/i.test(l)
|
|
211
|
+
&& !/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
212
|
rule({ id: "cookie.trusted-role", title: "Permissions read from a cookie", status: "partial", severity: "high", controls: [A08, A01],
|
|
161
213
|
fix: "Keep roles and permissions on the server, looked up from the authenticated user, not in a cookie the browser can change.",
|
|
162
214
|
note: "Users can edit their own cookies and give themselves admin rights (CWE-565).", extensions: CODE,
|
|
@@ -178,14 +230,16 @@ export const owaspRules = [
|
|
|
178
230
|
note: "Line breaks in user input can forge fake log entries and mislead an investigation (CWE-117).", extensions: CODE,
|
|
179
231
|
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
232
|
// A10 Mishandling of Exceptional Conditions
|
|
181
|
-
|
|
233
|
+
// Partial and low: most ignored errors in practice are deliberate fallbacks (field test, 139 repos: 0 of 6 were real).
|
|
234
|
+
rule({ id: "error.empty-catch", title: "Error caught and ignored", status: "partial", severity: "low", controls: [A10],
|
|
182
235
|
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
236
|
note: "Silent failures hide attacks and bugs, and can leave the app running in a broken or unsafe state (CWE-390).", extensions: CODE,
|
|
184
237
|
test: (l) => /\bcatch\s*(\(\s*\w*\s*\))?\s*\{\s*\}|^\s*except(\s+[\w.,() ]+)?\s*:\s*pass\b/.test(l) }),
|
|
185
238
|
rule({ id: "error.stack-to-client", title: "Error details sent to the user", status: "gap", severity: "medium", controls: [A10, A02],
|
|
186
239
|
fix: "Log the full error on the server and send users a short, generic message with a reference id.",
|
|
187
240
|
note: "Stack traces show file paths, library versions and sometimes data, which helps attackers (CWE-209).", extensions: CODE,
|
|
188
|
-
|
|
241
|
+
// A traceback counts only when it goes into a response, not into logs, a CLI or a prompt (field test, 139 repos).
|
|
242
|
+
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
243
|
];
|
|
190
244
|
/** Existing rules that also relate to an OWASP Top 10:2025 category. Added to their controls at load time. */
|
|
191
245
|
export const owaspForExisting = {
|
|
@@ -1,4 +1,11 @@
|
|
|
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
|
+
}>;
|
|
9
|
+
/** A browser-exposed env name that holds a secret. Pure. */
|
|
10
|
+
export declare function publicSecretName(n: string): boolean;
|
|
4
11
|
export declare const stackRules: Rule[];
|
package/dist/src/rules/stack.js
CHANGED
|
@@ -24,6 +24,43 @@ 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)|Deno\.env\.get\(\s*["'][A-Z_]*(WEBHOOK|CRON|SHARED|SIGNING|CALLBACK|FUNCTION)[A-Z_]*SECRET["']/i;
|
|
29
|
+
// Reading a header is not checking it: the header must be compared, or a request must be turned away with 401/403
|
|
30
|
+
// (review P11: reading Authorization and passing it on, unchecked, is the stock template).
|
|
31
|
+
const HEADER_COMPARED = /headers\.get\([^)]*\)[^;\n]*(!==?|===?)|(!==?|===?)[^;\n]*headers\.get\(/;
|
|
32
|
+
const DENIES = /status\s*:\s*40[13]\b|\b40[13]\s*\)/;
|
|
33
|
+
/** Code with comments removed, so "// TODO: call verifyToken()" doesn't count as a check. Pure. */
|
|
34
|
+
const stripComments = (t) => t.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1");
|
|
35
|
+
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/;
|
|
36
|
+
/** In supabase/config.toml: functions with verify_jwt = false whose code shows no caller check of its own. Pure. */
|
|
37
|
+
export function functionsWithoutAuth(lines, _shared, files = {}) {
|
|
38
|
+
const out = [];
|
|
39
|
+
let fn = "";
|
|
40
|
+
lines.forEach((l, i) => {
|
|
41
|
+
const head = /^\s*\[functions\.([\w-]+)\]/.exec(l);
|
|
42
|
+
if (head) {
|
|
43
|
+
fn = head[1];
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (/^\s*\[/.test(l)) {
|
|
47
|
+
fn = "";
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (!fn || !/^\s*verify_jwt\s*=\s*false\b/.test(l))
|
|
51
|
+
return;
|
|
52
|
+
const own = Object.entries(files).filter(([p]) => p.includes(`supabase/functions/${fn}/`));
|
|
53
|
+
if (!own.length)
|
|
54
|
+
return; // the code isn't in this repo: nothing to judge
|
|
55
|
+
// Follow imports of shared helpers (../_shared/auth.ts), so a check kept in a helper counts.
|
|
56
|
+
const imported = Object.entries(files).filter(([p]) => /\/_shared\//.test(p) && own.some(([, t]) => t.includes(p.split("/").pop().replace(/\.(ts|js|mjs)$/, ""))));
|
|
57
|
+
const text = [...own, ...imported].map(([, t]) => stripComments(t)).join("\n");
|
|
58
|
+
if (CALLER_CHECK.test(text) || HEADER_COMPARED.test(text) || (DENIES.test(text) && /headers\.get\(/.test(text)))
|
|
59
|
+
return;
|
|
60
|
+
out.push({ line: i + 1, status: HIGH_IMPACT.test(own.map(([, t]) => t).join("\n")) ? "gap" : "partial" });
|
|
61
|
+
});
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
27
64
|
// Browser-exposed env prefixes: Next.js, Vite, Expo, Create React App, Nuxt, SvelteKit/Astro (PUBLIC_).
|
|
28
65
|
// No bare PUBLIC_: it matches ordinary constants like PUBLIC_WITH_PRIVATE_AGENT.
|
|
29
66
|
const PUBLIC_ENV = /\b(NEXT_PUBLIC|VITE|EXPO_PUBLIC|REACT_APP|NUXT_PUBLIC)_[A-Z0-9_]*/g;
|
|
@@ -34,6 +71,19 @@ const SECRET_SERVICE = /OPENAI|ANTHROPIC|CLAUDE|GEMINI|GOOGLE_AI|GROQ|MISTRAL|DE
|
|
|
34
71
|
const SUPABASE_DIR = /(^|\/)supabase\//;
|
|
35
72
|
// Keys that are public by design and fine in the browser.
|
|
36
73
|
const PUBLIC_BY_DESIGN = /ANON|PUBLISHABLE|_PK_|PUBLIC_KEY|FIREBASE|MAPS|MAPBOX|POSTHOG|SENTRY_DSN|ALGOLIA_SEARCH|SITE_KEY|MEASUREMENT_ID|URL$|_URL_/;
|
|
74
|
+
// Words that make a name secret whatever service it belongs to. They win over the public list above:
|
|
75
|
+
// NEXT_PUBLIC_FIREBASE_ADMIN_PRIVATE_KEY and VITE_POSTHOG_PERSONAL_API_KEY are secrets (review P14).
|
|
76
|
+
const SECRET_WORD = /SECRET|PRIVATE|SERVICE_ROLE|SB_SECRET|PASSWORD|PERSONAL_(API_KEY|ACCESS_TOKEN|TOKEN)|(DATABASE|POSTGRES|DB|MONGO(DB)?|REDIS)_URL|CONNECTION_STRING/;
|
|
77
|
+
/** A browser-exposed env name that holds a secret. Pure. */
|
|
78
|
+
export function publicSecretName(n) {
|
|
79
|
+
if (/FIREBASE\w*DATABASE_URL/.test(n))
|
|
80
|
+
return false; // Firebase's Realtime Database URL is public config
|
|
81
|
+
if (SECRET_WORD.test(n))
|
|
82
|
+
return true;
|
|
83
|
+
if (PUBLIC_BY_DESIGN.test(n))
|
|
84
|
+
return false;
|
|
85
|
+
return SECRET_SERVICE.test(n) && /KEY|TOKEN/.test(n);
|
|
86
|
+
}
|
|
37
87
|
export const stackRules = [
|
|
38
88
|
rule({ id: "supabase.rls-disabled", title: "Database table without row level security", status: "partial", severity: "high", controls: [GDPR32, A01],
|
|
39
89
|
fix: "Add `alter table <name> enable row level security;` and a policy that limits each row to its owner, for example `using (auth.uid() = user_id)`.",
|
|
@@ -45,15 +95,29 @@ export const stackRules = [
|
|
|
45
95
|
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
96
|
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
97
|
pathMatch: SUPABASE_DIR,
|
|
48
|
-
|
|
98
|
+
// A read-only policy (for select) that is open on purpose, such as published posts, is common and fine;
|
|
99
|
+
// open insert, update, delete or "all" policies are the risk (field test, 139 repos).
|
|
100
|
+
fileTest: (lines) => lines.flatMap((l, i) => {
|
|
101
|
+
if (!/\b(using|with\s+check)\s*\(\s*true\s*\)/i.test(l))
|
|
102
|
+
return [];
|
|
103
|
+
const start = lines.slice(Math.max(0, i - 8), i + 1).join(" ");
|
|
104
|
+
return /\bfor\s+select\b/i.test(start.slice(start.toLowerCase().lastIndexOf("create policy"))) ? [] : [i + 1];
|
|
105
|
+
}) }),
|
|
106
|
+
rule({ id: "supabase.function-no-auth", title: "Supabase Edge Function anyone can call", status: "partial", severity: "high", controls: [GDPR32, A01],
|
|
107
|
+
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.",
|
|
108
|
+
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.",
|
|
109
|
+
extensions: [".toml"], fileName: /^config\.toml$/, pathMatch: SUPABASE_DIR,
|
|
110
|
+
sharedFiles: /(^|\/)supabase\/functions\/.+\.(ts|js|mjs)$/,
|
|
111
|
+
fileTest: functionsWithoutAuth }),
|
|
49
112
|
rule({ id: "secret.public-env", title: "Secret in a variable the browser can see", status: "gap", severity: "high", controls: [GDPR32, A04],
|
|
50
113
|
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
114
|
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
115
|
extensions: [...CODE, ".env"],
|
|
116
|
+
unlessPath: /\.d\.ts$/, // type declarations (env.d.ts) name variables, they don't ship values (field test)
|
|
53
117
|
test: (l) => {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
return
|
|
118
|
+
if (/^\s*(readonly\s+)?[A-Z0-9_]+\??\s*:\s*string\b/.test(l))
|
|
119
|
+
return false; // a typed field, not a value
|
|
120
|
+
return (l.match(PUBLIC_ENV) ?? []).some(publicSecretName);
|
|
57
121
|
} }),
|
|
58
122
|
rule({ id: "supabase.service-key-in-client", title: "Supabase service-role key used in browser code", status: "gap", severity: "high", controls: [GDPR32, A01],
|
|
59
123
|
fix: "Use the service-role key only in server code (API routes, server actions, edge functions). In browser code, use the anon key with row level security, and rotate the service-role key if it was ever shipped.",
|
|
@@ -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.7",
|
|
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",
|