@lintsure/core 0.3.7 → 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.
@@ -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.7";
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. */
@@ -47,6 +47,16 @@ export declare const NON_SHIPPING: RegExp;
47
47
  export declare function isNonShipping(file: string): boolean;
48
48
  /** The JSON object key that opens the block a line sits in, e.g. "peerDependencies". Pure. */
49
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[];
50
60
  /** Marks lines that are only a comment or sit inside a block comment, Python docstring or multi-line string. Pure. */
51
61
  export declare function commentLines(lines: string[], ext: string): boolean[];
52
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.7";
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. " +
@@ -176,6 +176,74 @@ export function enclosingKey(lines, i) {
176
176
  }
177
177
  const HASH_COMMENTS = new Set([".py", ".rb", ".sh", ".yml", ".yaml", ".toml", ".env"]);
178
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
+ }
179
247
  /** Marks lines that are only a comment or sit inside a block comment, Python docstring or multi-line string. Pure. */
180
248
  export function commentLines(lines, ext) {
181
249
  const hash = HASH_COMMENTS.has(ext), py = ext === ".py", sql = ext === ".sql";
@@ -289,6 +357,14 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
289
357
  // and what they find there is Partial (it may be a throwaway key).
290
358
  const inTests = isNonShipping(file);
291
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;
292
368
  for (const r of relevant) {
293
369
  const secret = SECRET_RULES.has(r.id);
294
370
  if (inTests && !secret)
@@ -299,9 +375,13 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
299
375
  perRule[r.id] = (perRule[r.id] ?? 0) + 1;
300
376
  // Comments describe code, they don't run. A real secret pasted into a comment still counts.
301
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();
302
382
  if (r.test)
303
383
  lines.forEach((text, i) => {
304
- if (skip?.[i])
384
+ if (skip?.[i] || (prose[i] && !readsText))
305
385
  return;
306
386
  const hit = r.test(text);
307
387
  if (!hit || (r.unlessNear && lines.slice(Math.max(0, i - 8), i + 4).some((l) => r.unlessNear.test(l))))
@@ -314,8 +394,32 @@ export async function scan(root, frameworks = ALL_FRAMEWORKS, opts = {}) {
314
394
  return; // test keys and certificates are fixtures by design (review P24)
315
395
  if (REVIEWED.test(text) || (!secret && OTHER_LINTER.test(text)))
316
396
  return; // someone already looked at this line and marked it
397
+ hitLines.add(i);
317
398
  add(r, i + 1, hit === "partial" || inTests ? "partial" : r.status);
318
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
+ }
319
423
  // File rules see comment lines as blank, so "<img> in a comment" or a commented-out call doesn't count (field test).
320
424
  if (r.fileTest)
321
425
  for (const n of r.fileTest(skip ? lines.map((l, i) => (skip[i] ? "" : l)) : lines, shared.get(r.id), sharedFiles.get(r.id)))
@@ -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) {
@@ -163,7 +165,7 @@ export const rules = [
163
165
  // The hash must be applied to a password. HMAC, HTTP Digest and fixed vendor formats require the algorithm;
164
166
  // they don't store passwords (field test, 139 repos).
165
167
  test: (l) => {
166
- const c = l.replace(/(["'`])(?:(?!\1).)*\s(?:(?!\1).)*\1/g, '""');
168
+ const c = l.replace(/(["'`])(?:(?!\1)\S)*\s(?:(?!\1).)*\1/g, '""');
167
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);
168
170
  },
169
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
@@ -154,7 +154,7 @@ export const owaspRules = [
154
154
  // A method named eval is a definition, not a call (also TypeScript class methods, field test); $$eval is Playwright's;
155
155
  // "eval" inside a string is text.
156
156
  test: (l) => /\b(def|function|async)\s+eval\s*\(|^\s*((public|private|protected|static|override)\s+)*eval\s*\([^)]*\)\s*(:[^{=]+)?\{\s*$/.test(l) ? false
157
- : /(^|[^.\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 }),
158
158
  rule({ id: "xss.raw-html", title: "HTML inserted without escaping", status: "partial", severity: "medium", controls: [A05],
159
159
  fix: "Set text with textContent, let your framework escape values, or sanitise with DOMPurify before inserting HTML.",
160
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,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lintsure/core",
3
- "version": "0.3.7",
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",