* Sanitize user input to prevent prompt injection attacks
(input: string, maxLength: number)
| 22 | * Sanitize user input to prevent prompt injection attacks |
| 23 | */ |
| 24 | function sanitizePromptInput(input: string, maxLength: number): string { |
| 25 | if (!input) { |
| 26 | return ""; |
| 27 | } |
| 28 | |
| 29 | // Truncate to maximum length |
| 30 | let sanitized = input.substring(0, maxLength); |
| 31 | |
| 32 | // Remove potential prompt injection patterns |
| 33 | const dangerousPatterns = [ |
| 34 | /ignore\s+(all\s+)?(previous|above|prior)\s+instructions?/gi, |
| 35 | /disregard\s+(all\s+)?(previous|above|prior)\s+instructions?/gi, |
| 36 | /forget\s+(all\s+)?(previous|above|prior)\s+instructions?/gi, |
| 37 | /new\s+instructions?:/gi, |
| 38 | /system\s*:/gi, |
| 39 | /assistant\s*:/gi, |
| 40 | /\[SYSTEM\]/gi, |
| 41 | /\[ASSISTANT\]/gi, |
| 42 | /\<\|im_start\|\>/gi, |
| 43 | /\<\|im_end\|\>/gi, |
| 44 | ]; |
| 45 | |
| 46 | for (const pattern of dangerousPatterns) { |
| 47 | sanitized = sanitized.replace(pattern, "[REDACTED]"); |
| 48 | } |
| 49 | |
| 50 | // Escape backticks that could break JSON formatting |
| 51 | sanitized = sanitized.replace(/`/g, "'"); |
| 52 | |
| 53 | // Remove excessive newlines that could break prompt structure |
| 54 | sanitized = sanitized.replace(/\n{4,}/g, "\n\n\n"); |
| 55 | |
| 56 | // Add truncation notice if content was cut |
| 57 | if (input.length > maxLength) { |
| 58 | sanitized += "\n\n[Content truncated for security]"; |
| 59 | } |
| 60 | |
| 61 | return sanitized; |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Initialize Bedrock client with AWS credentials |
no outgoing calls
no test coverage detected