/** * RAGGuard (L10) v2 * * Validates RAG (Retrieval Augmented Generation) content before injection. * Protects against supply chain attacks via poisoned documents and embeddings. * * Threat Model: * - ASI04: Agentic Supply Chain Vulnerabilities * - RAG Poisoning: Malicious content in retrieved documents * - Embedding manipulation attacks * - Indirect prompt injection via documents * * Protection Capabilities (v2 Enhanced): * - Retrieved document sanitization * - Source verification and trust scoring * - Injection pattern detection in documents * - Content integrity verification * - Suspicious document quarantine * - Advanced embedding attack detection (backdoor, adversarial) * - Unicode steganography detection * - Markdown/HTML hidden instruction detection * - Cross-document similarity anomaly detection * - Embedding norm and distribution analysis */ export interface RAGGuardConfig { /** Enable injection detection in retrieved content */ detectInjections?: boolean; /** Enable source verification */ verifySource?: boolean; /** Trusted document sources (domains, paths) */ trustedSources?: string[]; /** Blocked document sources */ blockedSources?: string[]; /** Maximum document size in characters */ maxDocumentSize?: number; /** Minimum trust score to allow (0-100) */ minTrustScore?: number; /** Enable content hashing for integrity */ enableContentHashing?: boolean; /** Known good content hashes */ knownGoodHashes?: Set; /** Auto-sanitize dangerous content */ autoSanitize?: boolean; /** Enable advanced embedding attack detection */ detectEmbeddingAttacks?: boolean; /** Embedding dimension for validation */ embeddingDimension?: number; /** Enable Unicode steganography detection */ detectSteganography?: boolean; /** Enable cross-document similarity analysis */ detectClusteringAnomalies?: boolean; /** Expected embedding magnitude range */ embeddingMagnitudeRange?: [number, number]; /** Cosine similarity threshold for anomaly detection */ similarityThreshold?: number; /** Enable indirect prompt injection detection */ detectIndirectInjection?: boolean; } /** Result of embedding attack analysis */ export interface EmbeddingAttackResult { detected: boolean; attack_type: string[]; risk_score: number; details: { magnitude_anomaly?: boolean; distribution_anomaly?: boolean; backdoor_pattern?: boolean; adversarial_perturbation?: boolean; clustering_anomaly?: boolean; }; } export interface RAGDocument { /** Document identifier */ id: string; /** Document content */ content: string; /** Source URL or path */ source: string; /** Document metadata */ metadata?: { title?: string; author?: string; lastModified?: string; contentType?: string; [key: string]: any; }; /** Embedding vector (for detection of manipulation) */ embedding?: number[]; /** Retrieval score from vector DB */ retrievalScore?: number; /** Content hash if pre-computed */ contentHash?: string; } export interface RAGGuardResult { allowed: boolean; reason: string; violations: string[]; request_id: string; document_analysis: { documents_checked: number; documents_blocked: number; documents_sanitized: number; injection_attempts: number; untrusted_sources: string[]; average_trust_score: number; embedding_attacks_detected: number; steganography_detected: number; indirect_injection_attempts: number; }; sanitized_documents?: RAGDocument[]; blocked_document_ids: string[]; recommendations: string[]; embedding_analysis?: EmbeddingAttackResult[]; } export interface SourceTrustResult { trusted: boolean; score: number; reason: string; } export declare class RAGGuard { private config; private contentHashCache; private sourceReputationCache; private readonly RAG_INJECTION_PATTERNS; private readonly SUSPICIOUS_METADATA_PATTERNS; private readonly MALICIOUS_SOURCE_PATTERNS; private readonly INDIRECT_INJECTION_PATTERNS; constructor(config?: RAGGuardConfig); /** * Validate RAG documents before injecting into context */ validate(documents: RAGDocument[], requestId?: string): RAGGuardResult; /** * Validate a single document */ validateSingle(document: RAGDocument, requestId?: string): RAGGuardResult; /** * Verify document source trustworthiness */ verifyDocumentSource(source: string): SourceTrustResult; /** * Add trusted source */ addTrustedSource(source: string): void; /** * Add blocked source */ addBlockedSource(source: string): void; /** * Register known good content hash */ registerKnownGoodHash(content: string): string; /** * Clear source reputation cache */ clearSourceCache(): void; /** * Decoded variants of document content to scan alongside the raw text. * Attackers can wrap an injection payload in URL-encoding \u2014 including * double-encoding (`%2520` \u2192 `%20` \u2192 ` `) \u2014 to slip it past plain regex * matching. Decode up to 3 levels and re-check each before concluding a * document is clean. No `+`-to-space conversion: that's form-encoding * convention, not appropriate for general document prose (it would * corrupt benign content like "10% + 5%"). */ private buildContentVariants; private detectInjections; private checkMetadata; private checkEmbedding; private sanitizeDocument; private hashContent; private generateRecommendations; /** * Detect advanced embedding attacks (backdoor, adversarial perturbation) */ private detectEmbeddingAttacks; /** * Detect indirect prompt injection patterns */ private detectIndirectInjection; /** * Detect steganography (hidden data in content) */ private detectSteganography; /** * Calculate cosine similarity between two vectors */ private cosineSimilarity; /** * Analyze a batch of embeddings for clustering anomalies */ analyzeEmbeddingCluster(embeddings: number[][]): { anomalous: boolean; anomalousIndices: number[]; reason: string; }; }