# Nextjs (TypeScript) Security Security vulnerabilities and detection rules for nextjs framework. 33 rules across 24 CWE categories. - Total rules: 33 - CWE categories: 24 - Critical rules: 5 ## CWEs - **CWE-639**: Authorization Bypass Through User-Controlled Key - **CWE-20**: Improper Input Validation - **CWE-601**: URL Redirection to Untrusted Site ('Open Redirect') - **CWE-93**: Improper Neutralization of CRLF Sequences ('CRLF Injection') - **CWE-176**: Improper Handling of Unicode Encoding - **CWE-200**: Exposure of Sensitive Information to an Unauthorized Actor - **CWE-201**: Insertion of Sensitive Information Into Sent Data - **CWE-209**: Generation of Error Message Containing Sensitive Information - **CWE-252**: Unchecked Return Value - **CWE-327**: Use of a Broken or Risky Cryptographic Algorithm - **CWE-362**: Concurrent Execution Using Shared Resource with Improper Synchronization ('Race Condition') - **CWE-390**: Detection of Error Condition Without Action - **CWE-391**: Unchecked Error Condition - **CWE-400**: Uncontrolled Resource Consumption - **CWE-502**: Deserialization of Untrusted Data - **CWE-521**: Weak Password Requirements - **CWE-636**: Not Failing Securely ('Failing Open') - **CWE-670**: Always-Incorrect Control Flow Implementation - **CWE-755**: Improper Handling of Exceptional Conditions - **CWE-840**: Business Logic Errors - **CWE-916**: Use of Password Hash With Insufficient Computational Effort - **CWE-918**: Server-Side Request Forgery (SSRF) - **CWE-1069**: Empty Exception Block - **CWE-1321**: Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') ## Rules - **Business Logic Bypass** [HIGH]: Detects client-controlled prices or amounts flowing to payment operations without server-side validation. - **Business Logic Input Validation** [MEDIUM]: Detects business-critical values (discount, refund, quantity) used without validation. - **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 - **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. - **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 - **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. - **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.** - **Incomplete Error Handling** [MEDIUM]: Detects empty catch blocks and incomplete error handling patterns that silently swallow errors. - **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. - **Next.js Open Redirect** [MEDIUM]: Detects user-controlled input flowing into redirect targets in Next.js middleware. - **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. - **SSRF in Next.js Server Actions** [HIGH]: Detects user-controlled input flowing into HTTP request URLs in Server Actions. - **Open Redirect via Untrusted URLs** [MEDIUM]: Detects user input flowing into redirect functions without URL validation. - **Prototype Pollution Gadget - Unsafe Property Trust** [MEDIUM]: Detects authorization checks that trust properties without verifying they are own properties. - **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) - **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. - **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) - **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. - **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.). - **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 - **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. - **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. - **Unsafe Deserialization** [CRITICAL]: Detects user input flowing to unsafe deserialization functions like node-serialize or yaml.load(). - **Unvalidated Business-Critical Values** [HIGH]: Detects business-critical values from user input used without validation. - **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 - **Weak Password Policy** [HIGH]: Detects password validation that lacks proper complexity requirements, making accounts vulnerable to brute force attacks. - **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. - **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.