@lintsure/core 0.3.6 → 0.3.8

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.
@@ -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>
@@ -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.6";
15
+ export declare const RULES_VERSION = "0.3.8";
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,8 +41,22 @@ 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;
50
+ export interface Statement {
51
+ start: number;
52
+ end: number;
53
+ text: string;
54
+ prose: boolean;
55
+ }
56
+ /** Groups lines into statements: lines join while a ( or [ or a template literal is open. Joining stops at a function
57
+ * body (`=> {`, `) {`), so a handler passed as an argument stays line by line. `prose` marks a multi-line template
58
+ * literal with no ${} (a prompt or help text), which is text, not code. Lines already blanked as comments are empty. Pure. */
59
+ export declare function statements(lines: string[], py?: boolean): Statement[];
46
60
  /** Marks lines that are only a comment or sit inside a block comment, Python docstring or multi-line string. Pure. */
47
61
  export declare function commentLines(lines: string[], ext: string): boolean[];
48
62
  export declare function scan(root: string, frameworks?: FrameworkId[], opts?: RecordOptions): Promise<Report>;
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.6";
22
+ export const RULES_VERSION = "0.3.8";
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", "config.default-secret-key"]);
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/;
@@ -155,6 +176,74 @@ export function enclosingKey(lines, i) {
155
176
  }
156
177
  const HASH_COMMENTS = new Set([".py", ".rb", ".sh", ".yml", ".yaml", ".toml", ".env"]);
157
178
  const C_LIKE = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".java", ".kt", ".swift", ".go", ".css", ".scss"]);
179
+ // Statement window (review step A): formatters split one call over several lines, and a rule that reads one line
180
+ // never sees `logger.info("signup", {` and `email: user.email` together. These are the files where that happens.
181
+ const JOINABLE = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"]);
182
+ // Rules that read whole statements. Only where it was measured to help without "join artifacts" (words from different
183
+ // parts of one statement matching together). Measured on 139 repos: SQL, shell, secret-in-log, random-token and
184
+ // system-prompt checks gained mostly false alarms when joined (5 of 41 sampled gains real), so they stay line by line.
185
+ const JOIN_RULES = new Set(["pii.logged", "pii.to-analytics", "log.injection", "upload.unrestricted", "mass-assignment",
186
+ "ssrf.user-url", "path.user-input", "redirect.open", "nosql.operator-input", "template.user-string", "error.stack-to-client",
187
+ // Narrow call-plus-value patterns, where unrelated parts of a statement rarely complete a match.
188
+ "transport.plain-http", "transport.tls-verify-off", "jwt.unverified", "crypto.weak-cipher", "fs.world-writable",
189
+ "mobile.token-in-plain-storage", "config.debug-on", "cookie.trusted-role"]);
190
+ const MAX_JOIN_LINES = 25, MAX_JOIN_CHARS = 2000;
191
+ /** Groups lines into statements: lines join while a ( or [ or a template literal is open. Joining stops at a function
192
+ * body (`=> {`, `) {`), so a handler passed as an argument stays line by line. `prose` marks a multi-line template
193
+ * literal with no ${} (a prompt or help text), which is text, not code. Lines already blanked as comments are empty. Pure. */
194
+ export function statements(lines, py = false) {
195
+ // A function body or a Python block starts here: stop joining so the body stays line by line.
196
+ const BODY = py ? /:\s*$/ : /(=>|\))\s*\{\s*$|\bfunction\b[^{]*\{\s*$/;
197
+ const out = [];
198
+ let i = 0;
199
+ while (i < lines.length) {
200
+ let depth = 0, tpl = false, interp = false, j = i;
201
+ for (; j < lines.length && j - i < MAX_JOIN_LINES; j++) {
202
+ const l = lines[j];
203
+ let q = "";
204
+ for (let k = 0; k < l.length; k++) {
205
+ const c = l[k];
206
+ if (tpl) {
207
+ if (c === "\\")
208
+ k++;
209
+ else if (c === "`")
210
+ tpl = false;
211
+ else if (c === "$" && l[k + 1] === "{")
212
+ interp = true;
213
+ continue;
214
+ }
215
+ if (q) {
216
+ if (c === "\\")
217
+ k++;
218
+ else if (c === q)
219
+ q = "";
220
+ continue;
221
+ }
222
+ if (c === '"' || c === "'")
223
+ q = c;
224
+ else if (c === "`")
225
+ tpl = true;
226
+ else if (py ? c === "#" : c === "/" && l[k + 1] === "/")
227
+ break;
228
+ else if (c === "(" || c === "[")
229
+ depth++;
230
+ else if (c === ")" || c === "]")
231
+ depth = Math.max(0, depth - 1);
232
+ }
233
+ if (!depth && !tpl)
234
+ break;
235
+ if (!tpl && BODY.test(l.trim()))
236
+ break;
237
+ }
238
+ const end = Math.min(j, lines.length - 1);
239
+ const text = lines.slice(i, end + 1).map((x) => x.trim()).join(" ").slice(0, MAX_JOIN_CHARS);
240
+ const body = lines.slice(i, end + 1).join("\n");
241
+ // Prose only when the template closes inside this statement: one cut off by the length cap may hold ${} further down.
242
+ out.push({ start: i, end, text, prose: end > i && !tpl && /`[^`]*\n[^`]*`/.test(body) && !interp });
243
+ i = end + 1;
244
+ }
245
+ return out;
246
+ }
158
247
  /** Marks lines that are only a comment or sit inside a block comment, Python docstring or multi-line string. Pure. */
159
248
  export function commentLines(lines, ext) {
160
249
  const hash = HASH_COMMENTS.has(ext), py = ext === ".py", sql = ext === ".sql";
@@ -172,6 +261,8 @@ export function commentLines(lines, ext) {
172
261
  return true;
173
262
  }
174
263
  if (py) {
264
+ if (t.startsWith("#"))
265
+ return true; // a comment that mentions """ opens no string (review P8)
175
266
  const q = t.match(/"""|'''/)?.[0];
176
267
  // An odd number of triple quotes opens a string that runs onto the next lines. A docstring line is text;
177
268
  // `PROMPT = """` is code whose string continues, and its closing quotes must not open a fake docstring (field test).
@@ -253,10 +344,7 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
253
344
  continue; // minified or generated
254
345
  // 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
346
  const lines = raw.map((l) => (l.length > MAX_LINE ? "" : l));
256
- filesChecked++;
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;
347
+ let ran = 0;
260
348
  const add = (r, line, status = r.status) => {
261
349
  const controls = r.controls.filter((c) => frameworks.includes(c.framework));
262
350
  findings.push({
@@ -267,17 +355,33 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
267
355
  };
268
356
  // Tests, fixtures, examples and docs are full of fake tokens and planted examples: only secret rules look at them,
269
357
  // and what they find there is Partial (it may be a throwaway key).
270
- const inTests = NON_SHIPPING.test(file);
358
+ const inTests = isNonShipping(file);
271
359
  const comment = commentLines(lines, ext);
360
+ // Statements are worked out once per file, on lines with comments blanked.
361
+ const stmts = JOINABLE.has(ext) ? statements(lines.map((l, i) => (comment[i] ? "" : l)), ext === ".py") : [];
362
+ const multi = stmts.filter((s) => s.end > s.start);
363
+ const prose = new Array(lines.length).fill(false);
364
+ for (const s of multi)
365
+ if (s.prose)
366
+ for (let i = s.start; i <= s.end; i++)
367
+ prose[i] = true;
272
368
  for (const r of relevant) {
273
369
  const secret = SECRET_RULES.has(r.id);
274
370
  if (inTests && !secret)
275
371
  continue;
372
+ // Count only what actually ran: a file skipped as a test is not a check point (review P1).
373
+ ran++;
374
+ checkPoints++;
375
+ perRule[r.id] = (perRule[r.id] ?? 0) + 1;
276
376
  // Comments describe code, they don't run. A real secret pasted into a comment still counts.
277
377
  const skip = secret ? null : comment;
378
+ // Prompt and help text inside a multi-line template is words, not code (review P9), except for the rule that
379
+ // reads prompts on purpose.
380
+ const readsText = secret || r.id === "ai.hides-being-ai";
381
+ const hitLines = new Set();
278
382
  if (r.test)
279
383
  lines.forEach((text, i) => {
280
- if (skip?.[i])
384
+ if (skip?.[i] || (prose[i] && !readsText))
281
385
  return;
282
386
  const hit = r.test(text);
283
387
  if (!hit || (r.unlessNear && lines.slice(Math.max(0, i - 8), i + 4).some((l) => r.unlessNear.test(l))))
@@ -286,15 +390,43 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
286
390
  return;
287
391
  if (inTests && PLACEHOLDER.test(text))
288
392
  return; // password="test_password", token="xoxb-test-..."
393
+ if (inTests && /PRIVATE KEY/.test(text))
394
+ return; // test keys and certificates are fixtures by design (review P24)
289
395
  if (REVIEWED.test(text) || (!secret && OTHER_LINTER.test(text)))
290
396
  return; // someone already looked at this line and marked it
397
+ hitLines.add(i);
291
398
  add(r, i + 1, hit === "partial" || inTests ? "partial" : r.status);
292
399
  });
400
+ // A statement spread over several lines: test it as one, and report it only when no single line already did,
401
+ // so line-by-line results never shrink (review step A).
402
+ if (r.test && JOIN_RULES.has(r.id))
403
+ for (const s of multi) {
404
+ if (s.prose && !readsText)
405
+ continue;
406
+ let already = false;
407
+ for (let i = s.start; i <= s.end; i++)
408
+ if (hitLines.has(i)) {
409
+ already = true;
410
+ break;
411
+ }
412
+ if (already)
413
+ continue;
414
+ const hit = r.test(s.text);
415
+ if (!hit || (r.unlessNear && lines.slice(Math.max(0, s.start - 8), s.end + 4).some((l) => r.unlessNear.test(l))))
416
+ continue;
417
+ if (r.unlessInKey && r.unlessInKey.test(enclosingKey(lines, s.start)))
418
+ continue;
419
+ if (lines.slice(s.start, s.end + 1).some((l) => REVIEWED.test(l) || OTHER_LINTER.test(l)))
420
+ continue;
421
+ add(r, s.start + 1, hit === "partial" || inTests ? "partial" : r.status);
422
+ }
293
423
  // File rules see comment lines as blank, so "<img> in a comment" or a commented-out call doesn't count (field test).
294
424
  if (r.fileTest)
295
425
  for (const n of r.fileTest(skip ? lines.map((l, i) => (skip[i] ? "" : l)) : lines, shared.get(r.id), sharedFiles.get(r.id)))
296
426
  typeof n === "number" ? add(r, n) : add(r, n.line, n.status);
297
427
  }
428
+ if (ran)
429
+ filesChecked++;
298
430
  }
299
431
  // Auditor: one finding per rule per line; stable order.
300
432
  const seen = new Set();
@@ -320,7 +452,7 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
320
452
  const LABEL = { gap: "Gap", partial: "Partial", met: "Met", outside: "Outside code" };
321
453
  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
454
  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" };
455
+ const RESULT = { finding: "Finding", observation: "Observation", "no issue found": "No issue found", "not checked": "Not checked (no files)" };
324
456
  /** The record block: identification, scope, what applies and why, counts, and results by control. */
325
457
  function recordLines(r) {
326
458
  const c = r.record;
@@ -342,7 +474,7 @@ function recordLines(r) {
342
474
  "### What applies, and why", "",
343
475
  ...c.applies.map((a) => `- **${a.framework}**: ${a.why}`), "",
344
476
  "### 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.", "",
477
+ "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
478
  "| Framework | Control | Rules | Check points | Result | Items |", "|---|---|---|---|---|---|",
347
479
  ...c.byControl.map((b) => `| ${b.framework} | ${b.control} ${b.title} | ${b.rules.join(", ")} | ${b.checkPoints} | ${RESULT[b.result]} | ${b.findingIds.join(", ") || "-"} |`), "",
348
480
  ];
@@ -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;
@@ -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;
@@ -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
- const run = /^(\s*-?\s*)run:\s*(.*)$/.exec(l);
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. */
@@ -7,7 +7,9 @@ const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
7
7
  const DRAFT = { mappedBy: "beta", reviewedAt: "pending" };
8
8
  const LOG_CALL = /\b(console\.(log|info|warn|error|debug)|logger\.\w+|log\.(info|warn|error|debug)|logging\.\w+|print)\s*\(/;
9
9
  // Drops the text of string literals but keeps interpolations, so "email error" is ignored and `${user.email}` or f"{user.email}" is not.
10
- const codeOnly = (l) => l.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
10
+ // [^\\] keeps the two alternatives apart: with "." a run of backslashes could match two ways, which backtracks
11
+ // exponentially on text such as an array of regular expressions (found when statements were joined).
12
+ const codeOnly = (l) => l.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
11
13
  const PII = /\b(e-?mail|phone|ssn|social_?security|passport|date_?of_?birth|dob|password|passwd|credit_?card|card_?number|iban)\b/i;
12
14
  // The arguments of the first log call on a line, up to its matching ")". Other code on the same line is ignored.
13
15
  function logArgs(l) {
@@ -44,6 +46,35 @@ const KEY_FORMATS = new RegExp([
44
46
  ].join("|"));
45
47
  // Example values from provider docs (AKIAIOSFODNN7EXAMPLE and the like) and obvious fill-ins.
46
48
  const DOC_EXAMPLE = /EXAMPLE|X{6,}|x{6,}|0{12,}|1234567890abcdef/;
49
+ // More fixed-prefix secrets this audience leaks: Stripe webhook secrets, Supabase secret keys, Resend keys (review P13).
50
+ 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,}/;
51
+ /** A Supabase (or any) JWT whose payload says role: service_role. Decoded exactly, so near-zero false alarms. Pure. */
52
+ export function serviceRoleJwt(l) {
53
+ for (const m of l.matchAll(/eyJ[\w-]{10,}\.(eyJ[\w-]{10,})\.[\w-]{10,}/g)) {
54
+ try {
55
+ if (/"role"\s*:\s*"service_role"/.test(Buffer.from(m[1], "base64url").toString("utf8")))
56
+ return true;
57
+ }
58
+ catch { /* not a JWT */ }
59
+ }
60
+ return false;
61
+ }
62
+ /** A database connection URL with an inline password that isn't a local default or a placeholder. Pure. */
63
+ export function dbUrlWithPassword(l) {
64
+ if (/placeholder|e\.g\.|for example|format:/i.test(l))
65
+ return false; // documentation of the format, not a value
66
+ const m = /\b(postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|rediss?):\/\/([^:\s"'`/@]+):([^@\s"'`]{4,})@([^/\s"'`:?]+)/.exec(l);
67
+ if (!m)
68
+ return false;
69
+ const [, , user, pass, host] = m;
70
+ // Only internet hosts: single names (db, hoppscotch-db) are containers on a private network; example.com is a sample.
71
+ if (!host.includes(".") || /^(localhost|127\.|0\.0\.0\.0|10\.|192\.168\.)|(^|\.)example\.(com|org|net)$|\.local$|\.internal$/i.test(host))
72
+ return false;
73
+ // Values built at run time ({$pass}, ${pass}, %s) and stand-ins (pass, testpass, changeme) aren't stored passwords (field test, 139 repos).
74
+ if (/[{}$%<>[\]]/.test(user + pass + host))
75
+ return false;
76
+ 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);
77
+ }
47
78
  export const rules = [
48
79
  {
49
80
  id: "pii.logged",
@@ -68,9 +99,16 @@ export const rules = [
68
99
  ],
69
100
  fix: "Move the secret to an environment variable or secrets manager, then rotate it: it is already in your git history.",
70
101
  note: "Anyone with read access to the repo, or a leaked copy of it, can use this key.",
71
- extensions: [...CODE, ".env", ".json", ".yaml", ".yml", ".toml"],
102
+ // Every text format a key ends up in: shell, Terraform, Go, Ruby, PHP, notebooks, Vue and Svelte files, Dockerfiles
103
+ // ("" is extensionless files), not only JavaScript and Python (review P13).
104
+ 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
105
  // 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) => { const m = l.match(KEY_FORMATS); return !!m && !DOC_EXAMPLE.test(m[0]) && !/PRIVATE KEY( BLOCK)?-----(["'`]|\.\.\.)/.test(l); },
106
+ test: (l) => {
107
+ if (/\bplaceholder\s*[=:]/i.test(l))
108
+ return false; // a form's example text (placeholder="sk_live_...")
109
+ const m = l.match(KEY_FORMATS) ?? l.match(MORE_KEYS);
110
+ return (!!m && !DOC_EXAMPLE.test(m[0]) && !/PRIVATE KEY( BLOCK)?-----(["'`]|\.\.\.)/.test(l)) || serviceRoleJwt(l) || dbUrlWithPassword(l);
111
+ },
74
112
  ...DRAFT,
75
113
  },
76
114
  {
@@ -127,7 +165,7 @@ export const rules = [
127
165
  // The hash must be applied to a password. HMAC, HTTP Digest and fixed vendor formats require the algorithm;
128
166
  // they don't store passwords (field test, 139 repos).
129
167
  test: (l) => {
130
- const c = l.replace(/(["'`])(?:(?!\1).)*\s(?:(?!\1).)*\1/g, '""');
168
+ const c = l.replace(/(["'`])(?:(?!\1)\S)*\s(?:(?!\1).)*\1/g, '""');
131
169
  return /\b(md5|sha1)\b[^;\n]{0,60}\bpass(word|wd)?\b/i.test(c) && !/hmac|digest\s*(auth|access)|\brealm\b|\bnonce\b|cookie/i.test(c);
132
170
  },
133
171
  ...DRAFT,
@@ -22,7 +22,7 @@ function logArgs(l) {
22
22
  }
23
23
  return l.slice(i + 1);
24
24
  }
25
- const stripStrings = (l) => l.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
25
+ const stripStrings = (l) => l.replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, (s) => (s.match(/\{[^}]*\}/g) ?? []).join(" "));
26
26
  const rule = (r) => ({ ...r, ...DRAFT });
27
27
  // A signing or encryption secret that falls back to text in the code when the env var is missing, e.g.
28
28
  // os.getenv("JWT_SECRET", "change-me-in-production") or process.env.SESSION_SECRET || "dev-secret". If the variable
@@ -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
- test: (l) => /\b(SECRET_KEY|JWT_SECRET|SESSION_SECRET|secret)\s*[:=]\s*["'](django-insecure-|changeme|change-me|secret\b|mysecret|keyboard cat|dev-secret|supersecret)/i.test(l)
82
- || /^\s*(SECRET_KEY|JWT_SECRET|SESSION_SECRET)\s*=\s*(django-insecure-|changeme|change-me|secret\b|mysecret|dev-secret|supersecret)/i.test(l)
83
- || fallbackSecret(l) }),
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
- unlessNear: /\bjwt\.verify\(|\bjwtVerify\(|\bverify(Token|Jwt|JWT)\(/ }),
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.",
@@ -148,7 +154,7 @@ export const owaspRules = [
148
154
  // A method named eval is a definition, not a call (also TypeScript class methods, field test); $$eval is Playwright's;
149
155
  // "eval" inside a string is text.
150
156
  test: (l) => /\b(def|function|async)\s+eval\s*\(|^\s*((public|private|protected|static|override)\s+)*eval\s*\([^)]*\)\s*(:[^{=]+)?\{\s*$/.test(l) ? false
151
- : /(^|[^.\w$])eval\s*\(|\bnew Function\s*\(/.test(l.replace(/(["'])(?:\\.|(?!\1).)*\1/g, '""')) ? byInput(l) : false }),
157
+ : /(^|[^.\w$])eval\s*\(|\bnew Function\s*\(/.test(l.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, '""')) ? byInput(l) : false }),
152
158
  rule({ id: "xss.raw-html", title: "HTML inserted without escaping", status: "partial", severity: "medium", controls: [A05],
153
159
  fix: "Set text with textContent, let your framework escape values, or sanitise with DOMPurify before inserting HTML.",
154
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,
@@ -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[];
@@ -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)|headers\.get\(\s*["'](authorization|x-[\w-]*(secret|signature|token|key|api-key))["']\s*\)|Deno\.env\.get\(\s*["'][A-Z_]*(WEBHOOK|CRON|SHARED|SIGNING|CALLBACK|FUNCTION)[A-Z_]*SECRET["']/i;
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
- const names = l.match(PUBLIC_ENV) ?? [];
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lintsure/core",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
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",