/**
 * AI Patterns Module
 *
 * Categories: ai_pattern, ai_prompt_injection, ai_unsafe_execution,
 *             ai_overpermissive_tool, suspicious_package, ai_rag_exfiltration,
 *             ai_endpoint_unprotected, ai_schema_mismatch, ai_package_hallucination,
 *             ai_rag_corpus_poisoning, ai_rag_pii_leakage, ai_mcp_tool_poisoning,
 *             ai_mcp_credential_issue, ai_mcp_confused_deputy,
 *             ai_mcp_description_injection, ai_mcp_server_shadowing,
 *             ai_mcp_config_secrets, ai_mcp_config_permissions,
 *             ai_rag_query_injection, ai_rag_embedding_poisoning,
 *             ai_rag_chunk_injection, ai_package_typosquat, ai_package_malicious,
 *             ai_unsafe_model_load, ai_unverified_model, ai_unsafe_finetuning,
 *             ai_excessive_agency
 *
 * Contains AI/LLM-specific patterns that require semantic AI reasoning.
 */

export const AI_PATTERNS_MODULE = `
### AI/LLM-Specific Patterns

**Prompt Injection (ai_prompt_injection):**
- User input in system prompt WITHOUT delimiters (code fences, XML tags, separators) -> **HIGH** (real risk)
- User input in system prompt WITH clear delimiters -> **INFO** (properly fenced)
- Static prompts with no user interpolation -> **REJECT** (false positive)
- Prompt templates using proper parameterization/placeholders -> **REJECT**

**LLM Output Execution (ai_unsafe_execution):**
- LLM output fed to eval()/Function()/exec() WITHOUT sandbox -> **CRITICAL** (arbitrary code execution)
- LLM output to execution WITH sandbox (vm2, isolated-vm) -> **MEDIUM** (risk mitigated)
- LLM output to execution WITH validation AND sandbox -> **LOW** (well-protected)
- LLM output used for display only (console.log, UI) -> **REJECT** (not execution)
- Generated SQL from LLM without parameterization -> **CRITICAL** (SQL injection)
- Generated SQL with parameterized queries -> **MEDIUM** (logic may still be wrong)

**Agent Tool Permissions (ai_overpermissive_tool):**
- Tool with unrestricted file/network/exec access -> **HIGH** (overpermissive)
- Tool without user context verification -> **MEDIUM** (missing authorization)
- Tool with proper scoping, allowlists, and user verification -> **LOW** or **REJECT**
- Test files with tool definitions -> **INFO** or **REJECT**

**Hallucinated Dependencies (suspicious_package):**
- Package not found in registry -> **CRITICAL** (likely AI-hallucinated name)
- Very new package (less than 7 days old) with low downloads and typosquat pattern -> **HIGH**
- Legitimate looking package with source/repo but low popularity -> **MEDIUM** (needs review)
- Known legitimate package with unusual name (in allowlist) -> **REJECT**

**CRITICAL AI PATTERN RULES**:
- AI code generation often produces non-existent package names - flag these prominently
- Prompt injection is NOT the same as XSS - different threat model and severity
- Sandboxed code execution (vm2, isolated-vm) significantly reduces risk
- Agent tools need both access restrictions AND user context verification

### RAG Data Exfiltration (ai_rag_exfiltration)
Retrieval Augmented Generation systems can leak sensitive data across tenant boundaries.

**Unscoped Retrieval Queries:**
- Vector store query WITHOUT user/tenant filter -> **HIGH** (cross-tenant data access)
  - .query(), .search(), .similaritySearch() without filter/where/userId/tenantId parameter
  - LangChain retriever.invoke() without metadata filter
  - Pinecone/Chroma/Weaviate query without namespace or metadata filter
- Query WITH proper scoping (filter by userId/tenantId) -> **REJECT** (properly scoped)
- Query with RLS-enabled Supabase tables -> **LOW/INFO** (verify RLS policy)

**Raw Context Exposure:**
- Raw sourceDocuments/chunks returned in API response -> **MEDIUM** (data leak to client)
- Raw context returned WITHOUT authentication -> **HIGH** (public data leak)
- Filtered response (only IDs, titles, metadata) -> **REJECT** (properly filtered)
- Response filtering visible nearby (.map, sanitize, redact) -> **INFO**

**Context Logging:**
- Logging retrieved documents (debug) -> **INFO** (hygiene, not direct risk)
- Logging full prompts with context -> **LOW** (audit concern if logs are accessible)
- Persisting prompts/context to database -> **MEDIUM** (sensitive data retention)

**CRITICAL RAG RULES**:
- Cross-tenant data access is the PRIMARY risk - always check for user/tenant scoping
- Authenticated endpoints exposing context are MEDIUM; unauthenticated are HIGH
- Debug logging is INFO severity - it's not a direct vulnerability
- If RLS or middleware protection is visible, downgrade significantly

### AI Endpoint Protection (ai_endpoint_unprotected)
AI/LLM API endpoints can incur significant costs and enable data exfiltration.

**No Authentication + No Rate Limiting -> HIGH:**
- Endpoint calls OpenAI/Anthropic/etc. without any auth check or rate limit
- Anyone on the internet can abuse the endpoint and run up API costs
- Potential for prompt exfiltration or model abuse

**Has Rate Limiting but No Authentication -> MEDIUM:**
- Rate limit provides some protection against abuse
- Still allows anonymous access to AI functionality
- Suggest adding authentication

**Has Authentication but No Rate Limiting -> LOW:**
- Authenticated users could still abuse the endpoint
- Suggest adding rate limiting for cost control
- severity: low (suggest improvement)

**Has Both Auth and Rate Limiting -> INFO/REJECT:**
- Properly protected endpoint
- REJECT if both are clearly present
- INFO if you want to note the good pattern

**BYOK (Bring Your Own Key) Endpoints:**
- If user provides their own API key, risk is LOWER
- User pays for their own usage - cost abuse is their problem
- Downgrade severity by one level for BYOK patterns

**Protected by Middleware:**
- If project context shows auth middleware protecting the route, downgrade to INFO
- Internal/admin routes should be INFO or REJECT

**CRITICAL ENDPOINT RULES**:
- Cost abuse is real - unprotected AI endpoints can bankrupt a startup
- Rate limiting alone isn't enough - need auth to prevent anonymous abuse
- BYOK endpoints have lower risk since user bears the cost
- Check for middleware protection before flagging

### Schema/Tooling Mismatch (ai_schema_mismatch)
AI-generated structured outputs need validation before use in security-sensitive contexts.

**Unvalidated AI Output Parsing:**
- JSON.parse(response.content) without schema validation -> **MEDIUM**
  - AI may return malformed or unexpected structures
  - Suggest zod/ajv/joi validation
- AI output to EXECUTION SINK (eval, exec, query) without validation -> **HIGH**
  - Direct path to code/SQL injection
- AI output to DISPLAY only (console.log, UI render) -> **REJECT**
  - Not a security issue for display purposes
- OpenAI Structured Outputs (json_schema in request) -> **REJECT**
  - API-level validation provides guarantees

**Weak Schema Patterns:**
- response: any at API boundary -> **MEDIUM** (no type safety)
- z.any() or z.unknown() -> **LOW** (defeats purpose of validation)
- z.passthrough() -> **INFO** (allows extra properties, minor concern)
- Specific schema defined and used -> **REJECT** (properly validated)

**Tool Parameter Validation:**
- Tool parameter -> file path without validation -> **HIGH** (path traversal)
- Tool parameter -> shell command without validation -> **CRITICAL** (command injection)
- Tool parameter -> URL without validation -> **HIGH** (SSRF)
- Tool parameter -> DB query without validation -> **HIGH** (SQL injection)
- Tool parameter with allowlist check visible -> **LOW/REJECT** (mitigated)

**CRITICAL SCHEMA RULES**:
- The severity depends on WHERE the AI output is used, not just that it's parsed
- Execution sinks (eval, exec, query, fs) need HIGH severity without validation
- Display-only usage is NOT a security issue
- Schema validation (zod, ajv, joi) significantly reduces risk
- OpenAI Structured Outputs provide API-level guarantees
`
