"""输入防护(F-03 最小实现)。""" from __future__ import annotations import re from app.utils.exceptions import AppError _INJECTION_PATTERNS = ( re.compile(r"(?i)ignore\s+previous\s+instructions"), re.compile(r"(?i)system\s*:\s*"), re.compile(r"(?is)(drop|delete|update|insert|alter|truncate)\s+"), ) def validate_user_message(message: str, *, max_len: int = 8000) -> str: text = message.strip() if not text: raise AppError(400, "消息不能为空", error_code="INPUT_EMPTY") if len(text) > max_len: raise AppError(400, "消息过长", error_code="INPUT_OVERSIZE", audit_event="input_guard") for pattern in _INJECTION_PATTERNS: if pattern.search(text): raise AppError(400, "输入包含不允许的内容", error_code="INPUT_BLOCKED", audit_event="input_guard") return text