@lintsure/core 0.3.3 → 0.3.4

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.
@@ -0,0 +1,72 @@
1
+ import { isAiCall } from "./index.js";
2
+ const DRAFT = { mappedBy: "beta", reviewedAt: "pending" };
3
+ const c = (framework) => (id, title) => ({ framework, id, title });
4
+ const LLM = c("owasp-llm"), CWE = c("cwe-top25");
5
+ const W = (n, title) => CWE(`CWE-${n}`, title);
6
+ const LLM01 = LLM("LLM01:2025", "Prompt Injection"), LLM02 = LLM("LLM02:2025", "Sensitive Information Disclosure"), LLM03 = LLM("LLM03:2025", "Supply Chain"), LLM05 = LLM("LLM05:2025", "Improper Output Handling"), LLM07 = LLM("LLM07:2025", "System Prompt Leakage"), LLM10 = LLM("LLM10:2025", "Unbounded Consumption");
7
+ const GDPR32 = { framework: "gdpr", id: "Art. 32", title: "Security of processing" };
8
+ const OW = (n, title) => ({ framework: "owasp-top10", id: `A${n}:2025`, title });
9
+ const A04 = OW("04", "Cryptographic Failures"), A06 = OW("06", "Insecure Design");
10
+ /** LLM and CWE controls for rules that already exist. Merged by id in rules/index.ts. */
11
+ export const standardsForExisting = {
12
+ "secret.in-source": [LLM02], "secret.public-env": [LLM02, W(200, "Exposure of Sensitive Information")], "pii.logged": [LLM02, W(200, "Exposure of Sensitive Information")],
13
+ "log.secret": [LLM02, W(200, "Exposure of Sensitive Information")], "deps.unpinned-version": [LLM03], "deps.install-script": [LLM03],
14
+ "xss.raw-html": [W(79, "Cross-site Scripting")], "template.user-string": [W(79, "Cross-site Scripting"), W(94, "Code Injection")],
15
+ "sql.string-built": [W(89, "SQL Injection")], "nosql.operator-input": [W(20, "Improper Input Validation")],
16
+ "csrf.disabled": [W(352, "Cross-Site Request Forgery")], "path.user-input": [W(22, "Path Traversal")],
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")], "upload.unrestricted": [W(434, "Unrestricted Upload of File with Dangerous Type")],
19
+ "deserialize.unsafe": [W(502, "Deserialization of Untrusted Data")], "ssrf.user-url": [W(918, "Server-Side Request Forgery")],
20
+ "supabase.rls-disabled": [W(862, "Missing Authorization")], "supabase.policy-allows-all": [W(284, "Improper Access Control")],
21
+ "supabase.service-key-in-client": [W(284, "Improper Access Control")], "cookie.trusted-role": [W(863, "Incorrect Authorization")],
22
+ "fs.world-writable": [W(284, "Improper Access Control")], "mass-assignment": [W(20, "Improper Input Validation"), W(639, "Authorization Bypass Through User-Controlled Key")],
23
+ "pii.in-url": [W(200, "Exposure of Sensitive Information")], "error.stack-to-client": [W(200, "Exposure of Sensitive Information")],
24
+ "build.sourcemaps-public": [W(200, "Exposure of Sensitive Information")], "llm.no-output-limit": [W(770, "Allocation of Resources Without Limits or Throttling")],
25
+ "ai.call-not-logged": [LLM10],
26
+ };
27
+ const CODE = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py"];
28
+ // Words for what a model sends back, so its output can be followed to a dangerous place on the same line.
29
+ const MODEL_OUTPUT = /\b(completion|response|result|output|reply|answer|generation|llmResponse|aiResponse)\b[\w.?[\]]*\.(choices|content|text|output_text|message)\b|\.output_text\b|\bresult\.text\b/;
30
+ const SINKS = /\b(eval|exec|execSync|spawn|new Function)\s*\(|\.innerHTML\s*=|dangerouslySetInnerHTML|\.(query|execute|raw)\s*\(|\bsubprocess\.|\bos\.system\(/;
31
+ // User input inside a system prompt: the model can't tell the app's instructions from the user's text.
32
+ const USER_TEXT = /\$\{[^}]*\b(req\.(body|query|params)|request\.(json|form|args)|input|userInput|message|prompt|query|body)\b[^}]*\}|\{(user_input|user_message|query|message)\}/;
33
+ const rule = (r) => ({ ...r, ...DRAFT });
34
+ export const standardsRules = [
35
+ // OWASP Top 10 for LLM Applications
36
+ rule({ id: "llm.user-input-in-system-prompt", title: "User text placed inside the AI's system instructions", status: "partial", severity: "high", controls: [LLM01, LLM07],
37
+ fix: "Keep the system prompt fixed. Send what the user typed as a separate user message, and never put it inside the system instructions.",
38
+ note: "Text in the system prompt is treated as the app's own instructions. If user text goes there, a user can rewrite the rules the AI follows (prompt injection). Marked Partial: the inserted value may be safe text your app controls.",
39
+ extensions: CODE,
40
+ test: (l) => /\b(role\s*:\s*["']system["']|system(Prompt|_prompt|Message|_message|Instruction)?\s*[:=]|["']system["']\s*,)/.test(l) && USER_TEXT.test(l) }),
41
+ rule({ id: "llm.output-to-sink", title: "AI output run as code, a command, a query or page HTML", status: "gap", severity: "high", controls: [LLM05],
42
+ 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
+ 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
+ extensions: CODE,
45
+ test: (l) => MODEL_OUTPUT.test(l) && SINKS.test(l) }),
46
+ rule({ id: "llm.no-output-limit", title: "AI call with no limit on how much it may generate", status: "partial", severity: "low", controls: [LLM10],
47
+ 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
+ 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.",
49
+ extensions: CODE,
50
+ fileTest: (lines) => lines.flatMap((l, i) => isAiCall(l) && !lines.slice(Math.max(0, i - 15), i + 20).some((x) => /max_?(output_?)?tokens|maxOutputTokens|max_completion_tokens|maxTokens/i.test(x)) ? [i + 1] : []).slice(0, 1) }),
51
+ // Mobile apps (React Native, Expo, Android, iOS)
52
+ rule({ id: "mobile.token-in-plain-storage", title: "Token or password saved in the phone's plain storage", status: "gap", severity: "high", controls: [GDPR32, A04],
53
+ fix: "Store tokens and passwords in the platform's secure storage: expo-secure-store, react-native-keychain, the Android Keystore or the iOS Keychain.",
54
+ note: "AsyncStorage and SharedPreferences aren't encrypted. Other apps on a rooted phone, or a device backup, can read what's saved there.",
55
+ extensions: [".ts", ".tsx", ".js", ".jsx", ".kt", ".java"],
56
+ test: (l) => /\b(AsyncStorage\.(setItem|multiSet)|MMKV\(\)\.set|\.putString)\s*\(/.test(l) && /token|password|secret|session|jwt|api_?key/i.test(l) }),
57
+ rule({ id: "mobile.cleartext-traffic", title: "App allows unencrypted network traffic", status: "gap", severity: "high", controls: [GDPR32, A04],
58
+ 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
+ note: "With cleartext allowed, anyone on the same Wi-Fi can read and change what the app sends and receives.",
60
+ extensions: [".xml", ".plist", ".json"], fileName: /^(AndroidManifest\.xml|network_security_config\.xml|Info\.plist|app\.json|app\.config\.json)$/,
61
+ test: (l) => /usesCleartextTraffic["']?\s*[=:]\s*["']?true|cleartextTrafficPermitted\s*=\s*"true"|<key>NSAllowsArbitraryLoads<\/key>/.test(l) }),
62
+ rule({ id: "mobile.backup-allowed", title: "App data included in device backups", status: "partial", severity: "low", controls: [GDPR32],
63
+ fix: "Set android:allowBackup=\"false\", or limit what's backed up with backup rules that leave out tokens and personal data.",
64
+ note: "Backups can be copied off the phone and read elsewhere. Marked Partial: backing up non-sensitive settings is fine.",
65
+ extensions: [".xml", ".json"], fileName: /^(AndroidManifest\.xml|app\.json|app\.config\.json)$/,
66
+ test: (l) => /allowBackup["']?\s*[=:]\s*["']?true/.test(l) }),
67
+ rule({ id: "mobile.webview-any-origin", title: "In-app browser that loads any website", status: "partial", severity: "medium", controls: [A06],
68
+ fix: "List only the sites the WebView should open in originWhitelist, and open other links in the phone's browser.",
69
+ note: "A WebView that accepts any origin can be sent to a page that abuses the bridge between the web page and your app. Marked Partial: it may only ever load your own content.",
70
+ extensions: [".tsx", ".jsx", ".ts", ".js"],
71
+ test: (l) => /originWhitelist\s*=\s*\{\s*\[\s*["']\*["']\s*\]\s*\}/.test(l) }),
72
+ ];
@@ -1,6 +1,8 @@
1
1
  export type Status = "met" | "partial" | "gap" | "outside";
2
2
  export type Severity = "high" | "medium" | "low";
3
- export type FrameworkId = "gdpr" | "soc2" | "iso-27001" | "eu-ai-act" | "owasp-top10";
3
+ /** Built-in frameworks. Rule packs can add more, so FrameworkId is open to other strings. */
4
+ export type BuiltinFrameworkId = "gdpr" | "eu-ai-act" | "owasp-top10" | "cra" | "owasp-llm" | "cwe-top25";
5
+ export type FrameworkId = BuiltinFrameworkId | (string & {});
4
6
  export interface Control {
5
7
  framework: FrameworkId;
6
8
  id: string;
@@ -19,6 +21,10 @@ export interface Rule {
19
21
  extensions: string[];
20
22
  /** Optional: only files whose name matches, e.g. /^package\.json$/ so lockfiles are skipped. */
21
23
  fileName?: RegExp;
24
+ /** Optional: only files whose path (relative to the scanned folder) matches, e.g. /(^|\/)supabase\//. */
25
+ pathMatch?: RegExp;
26
+ /** Optional: skip files whose relative path matches, e.g. example folders or library adapters. */
27
+ unlessPath?: RegExp;
22
28
  /** Optional: a line hit is dropped when this appears within 8 lines above or 3 below
23
29
  * (e.g. an exp claim set in the payload just before jwt.encode). */
24
30
  unlessNear?: RegExp;
@@ -29,7 +35,13 @@ export interface Rule {
29
35
  test?(line: string): boolean | "partial";
30
36
  /** File rule, for checks that need context (e.g. "an AI call with no logging in this file").
31
37
  * Returns 1-based line numbers to flag. Must be pure. */
32
- fileTest?(lines: string[]): number[];
38
+ fileTest?(lines: string[], shared?: string): number[];
39
+ /** Optional: fileTest also gets the text of every file this rule reads, joined (for example all Supabase
40
+ * migrations, so row level security switched on in a later file counts). */
41
+ sharedContext?: boolean;
42
+ /** Repository check: returns the path of a file the repo should have but doesn't (e.g. "SECURITY.md"),
43
+ * or null. Gets every file path relative to the scanned folder, "/"-separated. Must be pure. */
44
+ repoTest?(files: string[]): string | null;
33
45
  mappedBy: string;
34
46
  reviewedAt: string;
35
47
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lintsure/core",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
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,9 +29,7 @@
29
29
  },
30
30
  "keywords": [
31
31
  "compliance",
32
- "gdpr",
33
- "soc2",
34
- "iso27001",
32
+ "gdpr",
35
33
  "eu-ai-act",
36
34
  "mcp",
37
35
  "static-analysis",
@@ -1,2 +0,0 @@
1
- import type { FrameworkKnowledge } from "./types.js";
2
- export declare const iso27001: FrameworkKnowledge;
@@ -1,63 +0,0 @@
1
- // Own-words summary of ISO/IEC 27001:2022 (with Amendment 1:2024). The standard is licensed:
2
- // we reference clause and Annex A control numbers only and describe intent in our own words.
3
- export const iso27001 = {
4
- id: "iso-27001",
5
- name: "ISO/IEC 27001",
6
- kind: "standard",
7
- summary: "An international standard for running an information security management system: a repeatable way to find security risks, pick controls, and keep improving. You get certified by an accredited body after an audit. Annex A lists 93 controls in four groups: organizational, people, physical and technological. You choose which apply and explain why.",
8
- whoItAppliesTo: "Any organization that wants to prove to customers, often in Europe and Asia, that it manages information security in a structured way.",
9
- applies(p) {
10
- if (p.wantsCertification)
11
- return "Customers or partners ask for an ISO 27001 certificate.";
12
- if (p.b2bCustomers && !p.usMarket)
13
- return "Business customers outside the US often expect ISO 27001.";
14
- return null;
15
- },
16
- obligations: [
17
- { ref: "Clauses 4–10", title: "The management system", inCode: "no",
18
- plain: "Define scope, get leadership commitment, assess and treat risks, set objectives, run internal audits and management reviews, and fix nonconformities. Amendment 1 adds that you consider climate change in your context.",
19
- evidence: "Scope, risk assessment, Statement of Applicability, internal audit and management review records." },
20
- { ref: "A.5", title: "Organizational controls (37)", inCode: "no",
21
- plain: "Policies, roles, asset inventory, supplier security, incident handling, legal duties and privacy.",
22
- evidence: "Policies, supplier agreements and incident records." },
23
- { ref: "A.5.34", title: "Privacy and protection of personal data", inCode: "partly", rules: ["pii.to-analytics"],
24
- plain: "Meet the privacy laws and contracts that apply to personal data you hold.",
25
- evidence: "Privacy compliance records." },
26
- { ref: "A.6", title: "People controls (8)", inCode: "no",
27
- plain: "Screening, terms of employment, awareness training, discipline and remote work.",
28
- evidence: "Training and screening records." },
29
- { ref: "A.7", title: "Physical controls (14)", inCode: "no",
30
- plain: "Protect offices, equipment and media. Often inherited from your cloud provider.",
31
- evidence: "Cloud provider reports and office measures." },
32
- { ref: "A.8.5", title: "Secure authentication", inCode: "yes", rules: ["session.cookie-insecure"],
33
- plain: "Log-in and sessions are built so they can't easily be stolen or bypassed.",
34
- evidence: "Authentication and session settings." },
35
- { ref: "A.8.9", title: "Configuration management", inCode: "yes", rules: ["config.debug-on"],
36
- plain: "Systems are set up securely and settings are controlled.",
37
- evidence: "Baseline configurations." },
38
- { ref: "A.8.11", title: "Data masking", inCode: "yes", rules: ["pii.logged", "pii.in-url"],
39
- plain: "Hide or reduce sensitive data where full values aren't needed, such as in logs.",
40
- evidence: "Masking in logs and test data." },
41
- { ref: "A.8.15–8.16", title: "Logging and monitoring", inCode: "partly", rules: ["ai.call-not-logged"],
42
- plain: "Record important events, protect the logs and watch them for problems.",
43
- evidence: "Log setup and alert rules." },
44
- { ref: "A.8.20", title: "Network security", inCode: "yes", rules: ["transport.plain-http", "transport.tls-verify-off", "cors.any-origin"],
45
- plain: "Networks and connections are protected and controlled.",
46
- evidence: "Network and TLS settings." },
47
- { ref: "A.8.24", title: "Use of cryptography", inCode: "yes", rules: ["secret.in-source", "crypto.weak-password-hash"],
48
- plain: "Use strong cryptography correctly and manage keys safely, not in source code.",
49
- evidence: "Crypto and key management rules." },
50
- { ref: "A.8.25–8.29", title: "Secure development", inCode: "yes", rules: ["sql.string-built"],
51
- plain: "Build software securely: secure design, coding, testing and separation of environments.",
52
- evidence: "Secure coding guidelines and test results." },
53
- { ref: "A.8.32", title: "Change management", inCode: "partly",
54
- plain: "Changes to systems are controlled and reviewed.",
55
- evidence: "Change records." },
56
- ],
57
- watchOut: [
58
- "Certification is for the management system, not the product. Code findings feed into it but don't replace it.",
59
- "Your Statement of Applicability must explain every Annex A control you include or exclude.",
60
- "Certificates to the 2013 version expired in October 2025. Use the 2022 version.",
61
- ],
62
- checkedOn: "2026-11-07",
63
- };
@@ -1,65 +0,0 @@
1
- // Own-words summary of SOC 2 (AICPA Trust Services Criteria). The criteria text is licensed:
2
- // we reference criterion IDs only and describe their intent in our own words.
3
- export const soc2 = {
4
- id: "soc2",
5
- name: "SOC 2",
6
- kind: "attestation",
7
- summary: "SOC 2 is not a law. It's a report from an independent CPA firm saying your controls for security (and optionally availability, confidentiality, processing integrity and privacy) are designed well, and in a Type II, that they worked over a period of months. Business customers ask for it before they trust you with their data.",
8
- whoItAppliesTo: "Any company that stores or processes customer data and sells to businesses, mostly in the US but also worldwide.",
9
- applies(p) {
10
- if (p.b2bCustomers)
11
- return "Your business customers will likely ask for a SOC 2 report.";
12
- return null;
13
- },
14
- obligations: [
15
- { ref: "CC1", title: "Control environment", inCode: "no",
16
- plain: "Leadership sets the tone: ethics, clear roles, hiring and training.",
17
- evidence: "Org chart, code of conduct, background checks, training records." },
18
- { ref: "CC2", title: "Communication", inCode: "no",
19
- plain: "People inside and outside know their security duties and how to report problems.",
20
- evidence: "Policies shared with staff and a way for customers to report issues." },
21
- { ref: "CC3", title: "Risk assessment", inCode: "no",
22
- plain: "You regularly look for risks to your goals, including fraud and changes, and decide how to handle them.",
23
- evidence: "A yearly risk assessment." },
24
- { ref: "CC4", title: "Monitoring of controls", inCode: "no",
25
- plain: "You check that your controls keep working and fix gaps you find.",
26
- evidence: "Internal reviews and how gaps were tracked." },
27
- { ref: "CC5", title: "Control activities", inCode: "no",
28
- plain: "You turn policies into concrete controls, including controls over technology.",
29
- evidence: "Written policies mapped to controls." },
30
- { ref: "CC6.1", title: "Logical access", inCode: "yes", rules: ["secret.in-source", "pii.logged", "crypto.weak-password-hash", "session.cookie-insecure", "pii.in-url"],
31
- plain: "Only the right people and systems can reach data. Secrets are protected, passwords are stored safely.",
32
- evidence: "Access settings, secret storage and password hashing." },
33
- { ref: "CC6.2–6.3", title: "Granting and removing access", inCode: "no",
34
- plain: "Access is approved before it's given, reviewed regularly and removed quickly when people leave.",
35
- evidence: "Access requests and quarterly access reviews." },
36
- { ref: "CC6.6", title: "Boundary protection", inCode: "yes", rules: ["cors.any-origin"],
37
- plain: "Systems are protected from outside threats at their edges.",
38
- evidence: "Network and API access settings." },
39
- { ref: "CC6.7", title: "Data in transit", inCode: "yes", rules: ["transport.plain-http", "transport.tls-verify-off"],
40
- plain: "Data moving between systems is protected, usually with properly verified TLS.",
41
- evidence: "TLS settings and certificate checks." },
42
- { ref: "CC7.1", title: "Finding vulnerabilities", inCode: "yes", rules: ["sql.string-built"],
43
- plain: "You look for weaknesses and misconfigurations and fix them.",
44
- evidence: "Scan results and fix history." },
45
- { ref: "CC7.2–7.5", title: "Monitoring and incidents", inCode: "partly", rules: ["ai.call-not-logged"],
46
- plain: "You watch for unusual activity, respond to incidents and recover.",
47
- evidence: "Logs, alerts and an incident response plan." },
48
- { ref: "CC8.1", title: "Change management", inCode: "partly", rules: ["config.debug-on"],
49
- plain: "Changes are reviewed, tested and approved before they reach production.",
50
- evidence: "Pull request reviews and deploy records." },
51
- { ref: "CC9", title: "Vendor and business risk", inCode: "no",
52
- plain: "You manage risks from vendors and business disruption.",
53
- evidence: "Vendor list with reviews, and a continuity plan." },
54
- { ref: "P-series", title: "Privacy criteria (optional)", inCode: "partly", rules: ["pii.to-analytics"],
55
- plain: "If privacy is in scope: notice, choice, collection limits, use, retention, disclosure and quality of personal data.",
56
- evidence: "Privacy notice and data flow records." },
57
- ],
58
- watchOut: [
59
- "A SOC 2 report is about your controls, not a pass or fail certificate. Exceptions are normal and get described.",
60
- "Type I looks at one day. Type II covers a period, often 3 to 12 months, so start collecting evidence early.",
61
- "Using AI in your service can bring AI-specific risks into scope. Auditors may ask how you oversee it.",
62
- "The AICPA published a draft of updated criteria in October 2026. It is open for comment until 15 January 2027 and, if approved, would apply from engagements starting on or after 31 December 2027. The criterion numbers in Lintsure follow the current criteria. Check which version your auditor uses.",
63
- ],
64
- checkedOn: "2026-11-09",
65
- };