@lintsure/core 0.3.6 → 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 +5 -1
- package/dist/src/index.js +38 -10
- package/dist/src/record.d.ts +1 -1
- package/dist/src/record.js +4 -0
- package/dist/src/rules/cra.js +2 -1
- package/dist/src/rules/index.d.ts +4 -0
- package/dist/src/rules/index.js +38 -2
- package/dist/src/rules/owasp.js +13 -5
- package/dist/src/rules/stack.d.ts +2 -0
- package/dist/src/rules/stack.js +23 -6
- package/package.json +1 -1
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. */
|
|
@@ -41,6 +41,10 @@ export declare function extOf(abs: string): string;
|
|
|
41
41
|
/** Scout: list files to check, sorted so output order never depends on the file system. */
|
|
42
42
|
export declare function listFiles(root: string, ignore?: string[]): Promise<string[]>;
|
|
43
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;
|
|
44
48
|
/** The JSON object key that opens the block a line sits in, e.g. "peerDependencies". Pure. */
|
|
45
49
|
export declare function enclosingKey(lines: string[], i: number): string;
|
|
46
50
|
/** Marks lines that are only a comment or sit inside a block comment, Python docstring or multi-line string. Pure. */
|
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. " +
|
|
@@ -133,9 +133,30 @@ export async function listFiles(root, ignore = []) {
|
|
|
133
133
|
}
|
|
134
134
|
// Code that doesn't ship: tests, fixtures, examples, docs, demos, stories and seed data. Most false alarms in the
|
|
135
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;
|
|
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
|
+
}
|
|
137
158
|
// Rules that also read test files. Not auth.hardcoded-password: test logins are fake by design (field test, 50 repos).
|
|
138
|
-
const SECRET_RULES = new Set(["secret.in-source"
|
|
159
|
+
const SECRET_RULES = new Set(["secret.in-source"]); // not config.default-secret-key: a test secret is a test value (review P19)
|
|
139
160
|
// Lines a person already reviewed. lintsure-ignore and the secret allowlist pragma count only in a comment and apply
|
|
140
161
|
// to every rule. Other linters' markers (noqa, nosec, NOSONAR) don't hide secrets: `# noqa: E501` is about line length.
|
|
141
162
|
const REVIEWED = /(#|\/\/|\/\*|--)\s*(lintsure-ignore|pragma:\s*allowlist secret)\b/;
|
|
@@ -172,6 +193,8 @@ export function commentLines(lines, ext) {
|
|
|
172
193
|
return true;
|
|
173
194
|
}
|
|
174
195
|
if (py) {
|
|
196
|
+
if (t.startsWith("#"))
|
|
197
|
+
return true; // a comment that mentions """ opens no string (review P8)
|
|
175
198
|
const q = t.match(/"""|'''/)?.[0];
|
|
176
199
|
// An odd number of triple quotes opens a string that runs onto the next lines. A docstring line is text;
|
|
177
200
|
// `PROMPT = """` is code whose string continues, and its closing quotes must not open a fake docstring (field test).
|
|
@@ -253,10 +276,7 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
253
276
|
continue; // minified or generated
|
|
254
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.
|
|
255
278
|
const lines = raw.map((l) => (l.length > MAX_LINE ? "" : l));
|
|
256
|
-
|
|
257
|
-
checkPoints += relevant.length; // one rule applied to one file is one check point
|
|
258
|
-
for (const r of relevant)
|
|
259
|
-
perRule[r.id] = (perRule[r.id] ?? 0) + 1;
|
|
279
|
+
let ran = 0;
|
|
260
280
|
const add = (r, line, status = r.status) => {
|
|
261
281
|
const controls = r.controls.filter((c) => frameworks.includes(c.framework));
|
|
262
282
|
findings.push({
|
|
@@ -267,12 +287,16 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
267
287
|
};
|
|
268
288
|
// Tests, fixtures, examples and docs are full of fake tokens and planted examples: only secret rules look at them,
|
|
269
289
|
// and what they find there is Partial (it may be a throwaway key).
|
|
270
|
-
const inTests =
|
|
290
|
+
const inTests = isNonShipping(file);
|
|
271
291
|
const comment = commentLines(lines, ext);
|
|
272
292
|
for (const r of relevant) {
|
|
273
293
|
const secret = SECRET_RULES.has(r.id);
|
|
274
294
|
if (inTests && !secret)
|
|
275
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;
|
|
276
300
|
// Comments describe code, they don't run. A real secret pasted into a comment still counts.
|
|
277
301
|
const skip = secret ? null : comment;
|
|
278
302
|
if (r.test)
|
|
@@ -286,6 +310,8 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
286
310
|
return;
|
|
287
311
|
if (inTests && PLACEHOLDER.test(text))
|
|
288
312
|
return; // password="test_password", token="xoxb-test-..."
|
|
313
|
+
if (inTests && /PRIVATE KEY/.test(text))
|
|
314
|
+
return; // test keys and certificates are fixtures by design (review P24)
|
|
289
315
|
if (REVIEWED.test(text) || (!secret && OTHER_LINTER.test(text)))
|
|
290
316
|
return; // someone already looked at this line and marked it
|
|
291
317
|
add(r, i + 1, hit === "partial" || inTests ? "partial" : r.status);
|
|
@@ -295,6 +321,8 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
295
321
|
for (const n of r.fileTest(skip ? lines.map((l, i) => (skip[i] ? "" : l)) : lines, shared.get(r.id), sharedFiles.get(r.id)))
|
|
296
322
|
typeof n === "number" ? add(r, n) : add(r, n.line, n.status);
|
|
297
323
|
}
|
|
324
|
+
if (ran)
|
|
325
|
+
filesChecked++;
|
|
298
326
|
}
|
|
299
327
|
// Auditor: one finding per rule per line; stable order.
|
|
300
328
|
const seen = new Set();
|
|
@@ -320,7 +348,7 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
|
|
|
320
348
|
const LABEL = { gap: "Gap", partial: "Partial", met: "Met", outside: "Outside code" };
|
|
321
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})` : "");
|
|
322
350
|
const ctl = (c) => c.map((x) => `${x.framework.toUpperCase()} ${x.id}`).join(" · ");
|
|
323
|
-
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)" };
|
|
324
352
|
/** The record block: identification, scope, what applies and why, counts, and results by control. */
|
|
325
353
|
function recordLines(r) {
|
|
326
354
|
const c = r.record;
|
|
@@ -342,7 +370,7 @@ function recordLines(r) {
|
|
|
342
370
|
"### What applies, and why", "",
|
|
343
371
|
...c.applies.map((a) => `- **${a.framework}**: ${a.why}`), "",
|
|
344
372
|
"### Results by control", "",
|
|
345
|
-
"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.", "",
|
|
346
374
|
"| Framework | Control | Rules | Check points | Result | Items |", "|---|---|---|---|---|---|",
|
|
347
375
|
...c.byControl.map((b) => `| ${b.framework} | ${b.control} ${b.title} | ${b.rules.join(", ")} | ${b.checkPoints} | ${RESULT[b.result]} | ${b.findingIds.join(", ") || "-"} |`), "",
|
|
348
376
|
];
|
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
|
@@ -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
|
{
|
package/dist/src/rules/owasp.js
CHANGED
|
@@ -78,9 +78,14 @@ export const owaspRules = [
|
|
|
78
78
|
fix: "Generate a long random secret per environment and load it from an environment variable or secret manager.",
|
|
79
79
|
note: "With a known secret key, attackers can forge sessions, cookies or signed tokens (CWE-1394).", extensions: [...CODE, ".env"],
|
|
80
80
|
// The value must be a quoted literal, or an env-style KEY=value line: `self.secret = secret` is a variable.
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
+
} }),
|
|
84
89
|
// Python's standard XML parsers don't load external entities (since 3.7.1), so only explicit opt-ins count (field test).
|
|
85
90
|
rule({ id: "xml.external-entities", title: "XML parser may load external entities", status: "partial", severity: "high", controls: [A02],
|
|
86
91
|
fix: "Use defusedxml in Python, or turn off entity resolution and DTD loading in your parser.",
|
|
@@ -135,7 +140,8 @@ export const owaspRules = [
|
|
|
135
140
|
return /\bjwt\.decode\(\s*[\w.]+\s*\)/.test(l) ? "partial" : false; // Node jwt.decode reads a token without verifying it
|
|
136
141
|
},
|
|
137
142
|
// Peeking at a claim before verifying it nearby is fine (field test, 139 repos).
|
|
138
|
-
|
|
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*=/ }),
|
|
139
145
|
// A05 Injection
|
|
140
146
|
rule({ id: "cmd.shell-built", title: "Shell command built from strings", status: "gap", severity: "high", controls: [A05],
|
|
141
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.",
|
|
@@ -183,7 +189,9 @@ export const owaspRules = [
|
|
|
183
189
|
// Translations ("Парола", "Passwort") and obvious stand-ins ("new-password", "hashed-password", "hunter2") are not credentials (field test).
|
|
184
190
|
&& !/[:=]\s*["'][^"']*(passw|hash|redact|hidden|\bhunter2\b|[^\x00-\x7F])/i.test(l)
|
|
185
191
|
// 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)
|
|
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) }),
|
|
187
195
|
rule({ id: "jwt.no-expiry", title: "JWT signed without an expiry", status: "partial", severity: "medium", controls: [A07],
|
|
188
196
|
fix: "Add expiresIn (Node) or an exp claim (Python), and keep access tokens short-lived.",
|
|
189
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,
|
|
@@ -6,4 +6,6 @@ export declare function functionsWithoutAuth(lines: string[], _shared?: string,
|
|
|
6
6
|
line: number;
|
|
7
7
|
status: "gap" | "partial";
|
|
8
8
|
}>;
|
|
9
|
+
/** A browser-exposed env name that holds a secret. Pure. */
|
|
10
|
+
export declare function publicSecretName(n: string): boolean;
|
|
9
11
|
export declare const stackRules: Rule[];
|
package/dist/src/rules/stack.js
CHANGED
|
@@ -25,7 +25,13 @@ export function tablesWithoutRls(lines, shared) {
|
|
|
25
25
|
return out;
|
|
26
26
|
}
|
|
27
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)|
|
|
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");
|
|
29
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/;
|
|
30
36
|
/** In supabase/config.toml: functions with verify_jwt = false whose code shows no caller check of its own. Pure. */
|
|
31
37
|
export function functionsWithoutAuth(lines, _shared, files = {}) {
|
|
@@ -48,8 +54,8 @@ export function functionsWithoutAuth(lines, _shared, files = {}) {
|
|
|
48
54
|
return; // the code isn't in this repo: nothing to judge
|
|
49
55
|
// Follow imports of shared helpers (../_shared/auth.ts), so a check kept in a helper counts.
|
|
50
56
|
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))
|
|
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)))
|
|
53
59
|
return;
|
|
54
60
|
out.push({ line: i + 1, status: HIGH_IMPACT.test(own.map(([, t]) => t).join("\n")) ? "gap" : "partial" });
|
|
55
61
|
});
|
|
@@ -65,6 +71,19 @@ const SECRET_SERVICE = /OPENAI|ANTHROPIC|CLAUDE|GEMINI|GOOGLE_AI|GROQ|MISTRAL|DE
|
|
|
65
71
|
const SUPABASE_DIR = /(^|\/)supabase\//;
|
|
66
72
|
// Keys that are public by design and fine in the browser.
|
|
67
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
|
+
}
|
|
68
87
|
export const stackRules = [
|
|
69
88
|
rule({ id: "supabase.rls-disabled", title: "Database table without row level security", status: "partial", severity: "high", controls: [GDPR32, A01],
|
|
70
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)`.",
|
|
@@ -98,9 +117,7 @@ export const stackRules = [
|
|
|
98
117
|
test: (l) => {
|
|
99
118
|
if (/^\s*(readonly\s+)?[A-Z0-9_]+\??\s*:\s*string\b/.test(l))
|
|
100
119
|
return false; // a typed field, not a value
|
|
101
|
-
|
|
102
|
-
const risky = names.filter((n) => !PUBLIC_BY_DESIGN.test(n));
|
|
103
|
-
return risky.some((n) => /SECRET|PRIVATE|SERVICE_ROLE|PASSWORD|SB_SECRET/.test(n) || (SECRET_SERVICE.test(n) && /KEY|TOKEN/.test(n)));
|
|
120
|
+
return (l.match(PUBLIC_ENV) ?? []).some(publicSecretName);
|
|
104
121
|
} }),
|
|
105
122
|
rule({ id: "supabase.service-key-in-client", title: "Supabase service-role key used in browser code", status: "gap", severity: "high", controls: [GDPR32, A01],
|
|
106
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.",
|
package/package.json
CHANGED