"""Cheap heuristic prompt-injection detector for inbound untrusted text (Phase 15). It is a SIGNAL, never a control: * it never grants a permission and never removes one - the gateway's Cedar policy, taint checks and approvals decide every side effect whatever this says; * it is recorded (``security_signals``, the run span, ``RunState["signals"]``) so graphs may route a flagged message to a human sooner, and so the alert sweep can see spikes; * false negatives are expected (paraphrases, other languages, encodings); the defense is the quarantine extractor having no tools, not this list. Rules are regexes over a lower-cased, whitespace-collapsed copy of the text, in English and Roman Urdu, plus structural tells (fake role tags, our own prompt delimiters). """ from __future__ import annotations import re from dataclasses import dataclass RULES: dict[str, re.Pattern[str]] = { "ignore_instructions": re.compile( r"\b(ignore|disregard|forget|override|bypass)\b.{0,40}\b(previous|prior|above|earlier|" r"all|any|your|the)\b.{0,20}\b(instructions?|rules?|prompts?|guidelines?|directions?)" ), "role_override": re.compile( r"\b(you are now|from now on you|act as|pretend to be|roleplay as|new persona|" r"developer mode|dan mode|jailbreak)\b" ), "system_prompt_probe": re.compile( r"\b(system prompt|hidden instructions?|initial instructions?|reveal your (prompt|" r"instructions|rules)|print your (prompt|instructions))\b" ), "fake_role_tag": re.compile( r"(<\s*/?\s*(system|assistant|developer|instructions?)\s*>|\[\s*(system|inst)\s*\]|" r"^\s*(system|assistant)\s*:|###\s*(system|instruction))", re.MULTILINE, ), "delimiter_escape": re.compile(r" bool: return self.score > 0 def as_dict(self) -> dict[str, object]: return {"score": self.score, "rules": list(self.rules), "flagged": self.flagged} MAX_SCAN_CHARS = 20_000 def detect(text: str | None) -> InjectionSignal: if not text: return InjectionSignal(0, ()) t = re.sub(r"\s+", " ", text[:MAX_SCAN_CHARS].lower()) raw = text[:MAX_SCAN_CHARS].lower() hits = tuple( name for name, rx in RULES.items() if rx.search(raw if name == "fake_role_tag" else t) ) return InjectionSignal(len(hits), hits)