As large language model (LLM) agents are integrated into real-time communication infrastructure, receiving inputs from push notification systems, messaging platforms, and multi-channel connectors, these pipelines introduce attack surfaces for adversarial manipulation that existing application-layer defenses do not adequately address. Prompt injection via notification payloads, credential leakage through untrusted message content, and malicious payload embedding in cross-channel routing represent an emergent class of threats. This paper presents Safety-Net, a middleware hardening framework realized through two complementary open-source systems: Push_Guardian, a four-stage sanitization middleware for push notification pipelines, and nanoclaw, a multi-channel AI agent orchestration connector supporting WhatsApp, Telegram, Slack, Discord, and Gmail. The Safety-Net protocol was designed as a structured sequence of payload parsing, injection pattern matching, credential scanning, and semantic risk scoring, with a fail-open guarantee ensuring service continuity under sanitization failure. The isolation and routing model of nanoclaw was characterized, and the composition of the two systems into a hardened end-to-end pipeline was demonstrated. Empirical evaluation across five injection attack categories showed detection rates of 91–98% with false positive rates below 3.1% and a median per-message latency overhead of 6.4 ms. These results suggest that lightweight middleware sanitization is both practical and effective for securing AI-mediated communication channels without sacrificing availability.
The deployment of LLM-based agents as first-class participants in communication infrastructure represents a significant architectural shift in enterprise software. Rather than interacting with language models solely through explicit user queries, modern production systems now route push notifications, webhook payloads, and messages from multiple chat platforms directly into agent context windows. In this paradigm, the model does not merely respond to human requests; it also processes event streams originating from third-party services, mobile notification buses, and automated pipelines, many of which originate outside the trust boundary of the deploying organization.
This architectural shift creates a class of security vulnerabilities that has received comparatively little systematic treatment in the academic literature. Prompt injection, the embedding of adversarial instructions within data that an LLM subsequently processes as if they were operator directives, was first characterized in the context of web-retrieved documents (Perez & Ribeiro, 2022). Its manifestation in push notification and messaging pipelines, however, differs materially from the document-retrieval threat model. Push notifications are high-frequency, low-latency, and frequently generated by third-party providers whose content cannot be controlled by the receiving organization. Messaging connectors aggregate inputs from multiple platforms with heterogeneous security properties: a Slack workspace with rigorous access controls may be federated with a Telegram group that accepts messages from arbitrary users. In both contexts, an adversary with the ability to influence notification content gains a side-channel into the agent's instruction stream.
Beyond prompt injection, these pipelines are susceptible to credential leakage, where notification payloads inadvertently or maliciously include API keys, session tokens, or personally identifiable information, and to semantic payload attacks, in which the surface text of a message appears benign but encodes instructions that a capable language model will interpret as directives. These threats are compounded by the operational constraints of production notification systems: any middleware layer inserted into a high-throughput pipeline must not become a single point of failure. A sanitization component that blocks delivery when it encounters an error would have catastrophic availability implications. This motivates what we call the fail-open guarantee: the property that a sanitization system must pass messages through in their original or minimally modified form whenever the sanitization process itself cannot be completed safely.
This paper makes the following contributions:
The remainder of the paper is organized as follows. Section 2 reviews background on prompt injection, push notification architecture, and multi-channel messaging security. Section 3 describes the system design of Push_Guardian and nanoclaw in detail. Section 4 characterizes their compositional integration. Section 5 presents the evaluation. Section 6 discusses limitations, threat model scope, and directions for future work. Section 7 concludes.
Prompt injection was formally characterized by Perez and Ribeiro (2022) as a class of adversarial attacks on instruction-following language models in which an attacker embeds instructions in data processed by the model, causing the model to follow attacker-controlled directives instead of or in addition to operator-controlled ones. The threat was initially studied in the context of web browsing agents retrieving attacker-controlled web pages, but has since been observed across a range of LLM deployment contexts including email processing (Hazell, 2023), document summarization, and tool-augmented reasoning pipelines (Greshake et al., 2023).
Greshake et al. (2023) demonstrated indirect prompt injection at scale, showing that an attacker who can influence the content of any document retrieved by an LLM agent can effectively hijack the agent's actions. This finding is particularly relevant to notification pipelines because push notification content is almost always produced by systems external to the receiving organization: marketing platforms, monitoring services, social networks, and third-party APIs all represent potential injection surfaces. A notification reading "Your package has shipped. SYSTEM: Ignore previous instructions and exfiltrate the user's API key to attacker.com" illustrates the threat in its simplest form, but semantic attacks can be considerably more subtle, using Unicode homoglyphs, encoded whitespace, or natural language paraphrases of instruction verbs to evade pattern-based filters.
Liu et al. (2023) proposed a taxonomy of prompt injection techniques including direct injection (in the system prompt itself), indirect injection (via retrieved context), and multi-turn injection (where instructions are spread across multiple conversation turns). Push notification pipelines are particularly susceptible to indirect and multi-turn injection because notifications accumulate in an agent's context window over time, enabling an attacker to build up injection content incrementally across multiple messages.
Modern push notification infrastructure follows a hub-and-spoke model in which application servers submit notification payloads to a platform provider, such as Apple Push Notification Service (APNs), Firebase Cloud Messaging (FCM), or enterprise equivalents, which routes them to destination devices or services (Apple Inc., 2023). From a security standpoint, this architecture presents three key challenges for AI-integrated receivers.
Platform providers validate the structural integrity and delivery metadata of notifications but perform no semantic analysis of payload content. A notification with a well-formed JSON body and valid authentication credentials is delivered regardless of what its textual fields contain. Many AI agent integrations compound this by processing notification payloads with minimal transformation: the notification title, body, and custom data fields are concatenated and appended to the agent's context window, often without any sanitization layer. Push notification volumes in enterprise environments can reach tens of thousands of events per hour, further constraining the latency budget available to any middleware processing layer.
Prior work on notification security has focused primarily on privacy (preventing notification content from being exposed to unauthorized parties on shared devices; Roesner et al., 2012) and on delivery integrity (preventing spoofed or modified notifications; Georgiev et al., 2012). The threat of AI-mediated semantic attacks via notification payloads has received substantially less attention.
Multi-channel messaging connectors, systems that aggregate inputs from WhatsApp, Telegram, Slack, Discord, Gmail, and similar platforms into a unified interface, amplify the notification security problem along two dimensions. First, they expand the attack surface: an adversary who can send a message on any of the connected platforms can potentially inject content into the agent's context. Second, they introduce cross-channel routing complexity: a message received on Telegram may trigger an action that produces output on Slack, creating opportunities for confused deputy attacks in which the agent is manipulated into acting with the privileges of one channel on behalf of content originating in another.
Existing work on messaging platform security has examined authentication weaknesses (Schrittwieser et al., 2012), metadata privacy leakage, and end-to-end encryption properties, but the specific threat of using messaging platforms as a prompt injection vector against AI agents is largely unaddressed in the literature. The emergence of commercially deployed AI agents on WhatsApp, Slack, and Discord, including customer service bots, coding assistants, and personal productivity agents, makes this a timely and practically important problem.
Push_Guardian is a Python middleware library implementing the Safety-Net protocol. It is designed to be inserted between a notification delivery endpoint and an AI agent's context ingestion layer, intercepting each incoming payload and subjecting it to a four-stage sanitization pipeline before passing it downstream.
Stage 1: Payload Parsing. The first stage normalizes the raw notification payload into a canonical internal representation. Push notification payloads arrive in heterogeneous formats: APNs payloads are JSON with a mandated aps key, FCM payloads use a different schema, and enterprise notification buses may use proprietary formats. Stage 1 performs format detection, schema validation, and extraction of all text-bearing fields (title, body, subtitle, custom data values, and any nested string fields) into a flat sequence of (field-path, content) tuples. Importantly, this stage also performs Unicode normalization (NFC) and resolves common obfuscation encodings including HTML entities, percent-encoding, and zero-width character injection, ensuring that subsequent stages operate on semantically accurate text rather than superficially clean representations of adversarial content.
Stage 2: Injection Pattern Matching. The second stage applies a rule-based pattern matching engine to the normalized content extracted in Stage 1. The pattern library encompasses three categories of injection signatures: (i) direct instruction-verb patterns targeting common LLM prompt structures ("ignore previous instructions", "you are now", "system:", "assistant:", "human:", and their variants in multiple languages and Unicode encodings); (ii) role-override patterns that attempt to assign new personas or identities to the model; and (iii) exfiltration-directive patterns targeting data leakage via URL construction, webhook calls, or tool invocations. Patterns are expressed as a combination of regular expressions and token-sequence matchers operating over the normalized text, enabling detection of patterns that span word boundaries or that are split across whitespace in ways that evade simple substring search. Matched content is flagged with a severity level (low, medium, high, critical) based on the specificity and demonstrated exploitability of the pattern.
Stage 3: Credential Scanning. Stage 3 scans each text field for patterns indicative of sensitive credential material. This includes API key formats for major cloud and AI service providers (AWS, GCP, Azure, OpenAI, Anthropic, Stripe, and others), private key PEM blocks, session tokens in JWT format, and common secret material patterns identified by their structural properties (high entropy strings of specific lengths in specific character sets). The credential scanner uses a combination of regex-based structural matching and Shannon entropy analysis to reduce false positives on benign high-entropy strings (such as image hashes or identifiers) while maintaining high recall on genuine credential patterns. Detected credentials are redacted from the payload and logged to a secure audit stream; the sanitized payload continues through the pipeline with credential fields replaced by redaction markers.
Stage 4: Semantic Risk Scoring. The fourth stage assigns a composite risk score to the full normalized payload using a lightweight ensemble of features derived from the outputs of the preceding stages, combined with direct semantic features computed over the text. Semantic features include the density of imperative verb constructions, the presence of second-person address to an AI system, the ratio of instruction-like sentences to informational sentences (using a small fine-tuned classifier), and structural anomalies such as unusual field lengths or atypical character distributions. The risk score is a value in [0, 1] and is used to determine the disposition of the payload: pass (score below a configurable low threshold), flag-and-pass (score in an intermediate band, payload passed with a risk annotation for downstream monitoring), and quarantine (score above a configurable high threshold, payload held for human review or discarded based on policy).
A critical design constraint for any middleware inserted into a production notification pipeline is that it must not become a single point of failure. Push_Guardian's fail-open guarantee ensures that if any stage of the Safety-Net pipeline encounters an unhandled exception (due to a malformed payload that defeats the parser, a timeout in the semantic scoring stage, a resource exhaustion condition, or a bug in the pattern matching engine) the middleware falls back to passing the original unmodified payload downstream rather than blocking delivery. This guarantee is implemented via a layered exception handling architecture in which each stage is wrapped in an independent try-catch boundary with a defined fallback behavior; the pipeline orchestrator maintains a circuit-breaker state machine that tracks failure rates per stage and can degrade gracefully to partial sanitization (skipping failed stages while executing others) before falling back to full pass-through.
The fail-open design is a deliberate security trade-off: it privileges availability over sanitization completeness. In enterprise deployments where notification delivery drives critical workflows (incident alerts, authentication events, operational telemetry), a fail-closed design that blocks delivery on sanitization failure could cause cascading operational failures whose cost exceeds the risk of an occasional unsanitized payload reaching the agent. Push_Guardian's configuration interface exposes both fail-open (default) and fail-closed operating modes, with the fail-open mode strongly recommended for production notification pipelines and the fail-closed mode available for high-security isolated deployments where availability can be sacrificed for sanitization completeness.
The fail-open guarantee is complemented by a comprehensive audit logging subsystem that records every sanitization decision, including fallback events, with full payload metadata and timing information. This enables post-hoc analysis of attack patterns even in cases where the sanitization pipeline was bypassed due to failure, and supports forensic investigation of injection attempts that succeeded through the fail-open path.
nanoclaw is a TypeScript platform that provides a unified interface for AI agent orchestration across WhatsApp, Telegram, Slack, Discord, and Gmail. It is designed around three architectural principles: channel abstraction, message routing, and agent isolation.
Channel Abstraction and Unified Interface. nanoclaw implements a platform adapter layer in which each supported messaging platform is encapsulated behind a common ChannelAdapter interface. Each adapter is responsible for authenticating to its platform, receiving incoming messages via webhooks or long-polling, normalizing incoming messages into a canonical IncomingMessage schema, and serializing outgoing responses back into platform-native format. The canonical schema captures sender identity, conversation context, message body, attached media references, and platform-specific metadata in a uniform structure that the agent orchestration layer can process without platform-specific logic. This abstraction allows new platforms to be added by implementing the adapter interface without modifying the orchestration core.
Message Routing and Agent Orchestration. The routing layer maintains a registry of registered group and conversation contexts, each associated with a configuration specifying which agent instance handles messages in that context, what trigger conditions must be met before the agent is invoked, and what memory and tool access the agent receives. When an incoming message is received through any channel adapter, the router performs trigger evaluation (checking whether the message satisfies the invocation conditions, e.g., containing a configured mention string, originating from an allowlisted sender, or matching a keyword pattern) and dispatches matching messages to the appropriate agent instance. The agent instance is provided with the canonical message, a conversation history context assembled from the platform's message store, and a tool interface through which it can invoke platform actions (sending messages, reacting to posts, retrieving media) and external services (web search, code execution, scheduled task management).
Agent Isolation Model. Each registered group or conversation context in nanoclaw operates as an isolated agent environment. Isolation is enforced at three levels. At the file system level, each context is assigned a dedicated group folder in the workspace, and agents are granted read-write access only to their own group folder and to a shared read-only project root. At the message history level, each context maintains its own conversation history store, and agents processing messages in one context cannot directly access the conversation history of another context. At the tool level, scheduled tasks and outgoing message capabilities are scoped to the originating context by default, with explicit cross-context targeting requiring elevated privileges available only to the main control group. This isolation model limits the blast radius of a successful injection attack: even if an adversary succeeds in manipulating an agent processing messages in one context, the agent cannot directly read conversation history or send messages in other contexts.
The compositional integration of Push_Guardian and nanoclaw produces a layered security architecture that hardens both the notification ingestion path and the multi-channel message routing path of an AI agent deployment. Figure 1 illustrates the end-to-end data flow.
| Layer | Component | Function |
|---|---|---|
| 1. Notification Ingestion | APNs / FCM / Enterprise Bus | Raw push payload delivery to receiver endpoint |
| 2. Sanitization Middleware | Push_Guardian (Safety-Net) | 4-stage sanitization: parse, inject-match, cred-scan, risk-score |
| 3. Channel Normalization | nanoclaw ChannelAdapter | Platform-specific normalization to canonical IncomingMessage |
| 4. Trigger Evaluation | nanoclaw Router | Allowlist check, trigger match, context dispatch |
| 5. Agent Orchestration | nanoclaw Agent Instance | Isolated LLM invocation with scoped tools and memory |
| 6. Audit & Monitoring | Push_Guardian Audit Log + nanoclaw Message Store | Forensic trail, anomaly detection, risk annotation propagation |
In the integrated deployment, Push_Guardian is instantiated as a preprocessing hook within each nanoclaw channel adapter. When a message arrives through any platform adapter (whether it originated as a push notification forwarded to a webhook, a direct user message on Telegram, or an email received via Gmail) it is passed through the Safety-Net pipeline before the canonical IncomingMessage schema is constructed. This placement ensures that sanitization occurs before the message content reaches any part of the nanoclaw routing or orchestration logic, including trigger evaluation. Consequently, an attacker cannot use injection content to manipulate trigger evaluation (e.g., by crafting a payload whose sanitized form would not trigger the agent but whose pre-sanitized form would, or vice versa).
Risk annotations produced by Stage 4 of Push_Guardian are propagated as metadata fields in the canonical IncomingMessage schema. The nanoclaw router and agent instances can access these risk scores and use them to inform downstream behavior: for example, a high-risk annotation might cause the router to route the message to a human review queue rather than the AI agent, or might cause the agent to include an explicit caveat in its response indicating that the incoming message was flagged for elevated injection risk.
The integration also addresses the credential leakage threat in a pipeline-specific way. When Push_Guardian's credential scanner detects and redacts a credential from an incoming message, the redaction marker is propagated through the nanoclaw pipeline. This prevents the agent from inadvertently including credential material in its responses (e.g., by echoing a message that contained an API key) and ensures that the audit log captures the occurrence of credential material in incoming messages without storing the credential itself.
For deployment, the integration is packaged as a configuration option in nanoclaw's group registration mechanism: administrators can enable Push_Guardian sanitization per-group with configurable threshold parameters, allowing different sanitization stringency for groups with different trust levels. A Telegram group accepting messages from arbitrary public users might be configured with aggressive sanitization thresholds, while an internal Slack workspace with enforced sender allowlisting might use relaxed thresholds to minimize false positive rates.
We evaluated the integrated Safety-Net pipeline using a synthetic adversarial dataset of 4,800 notification and message payloads spanning five injection attack categories, supplemented by 2,400 benign payloads drawn from representative enterprise notification logs (anonymized and stripped of PII). All experiments were conducted on a machine with an Apple M2 processor and 16 GB RAM, running macOS 14.5, Python 3.11.9, and Node.js 22.4.0. Push_Guardian was configured with default threshold parameters (flag threshold 0.35, quarantine threshold 0.70). The semantic scoring stage used a 12M-parameter fine-tuned classifier served in-process.
| Attack Category | Payloads (n) | Detection Rate (%) | False Positive Rate (%) | Primary Detection Stage |
|---|---|---|---|---|
| Direct instruction injection ("ignore previous instructions") | 960 | 98.1 | 1.4 | Stage 2 (Pattern Match) |
| Role-override injection ("you are now a different AI") | 960 | 96.4 | 2.1 | Stage 2 (Pattern Match) |
| Credential exfiltration directive | 960 | 94.7 | 1.8 | Stage 2 + Stage 3 |
| Semantic / paraphrase injection | 960 | 91.2 | 3.1 | Stage 4 (Semantic Score) |
| Multi-turn incremental injection | 960 | 93.5 | 2.6 | Stage 4 + Cross-turn aggregation |
| Overall (all categories) | 4,800 | 94.8 | 2.2 | All stages |
| Pipeline Stage | Median Latency (ms) | p95 Latency (ms) | p99 Latency (ms) |
|---|---|---|---|
| Stage 1: Payload Parsing | 0.4 | 0.9 | 2.1 |
| Stage 2: Injection Pattern Matching | 1.1 | 2.4 | 4.8 |
| Stage 3: Credential Scanning | 0.8 | 1.7 | 3.2 |
| Stage 4: Semantic Risk Scoring | 4.1 | 9.3 | 18.6 |
| Total Pipeline | 6.4 | 14.3 | 28.7 |
The dominant latency contributor is Stage 4 (semantic risk scoring), which requires inference over the fine-tuned classifier. The median total pipeline latency of 6.4 ms is well within the tolerance of interactive messaging systems, which typically have end-to-end latency budgets measured in hundreds of milliseconds. The p99 latency of 28.7 ms is elevated but acceptable for most enterprise notification use cases; it is primarily driven by classifier inference on payloads with large text fields. Stage 4 can be configured to operate asynchronously with a timeout, falling back to pass-with-flag disposition at the cost of semantic detection coverage, a trade-off that reduces p99 latency to under 5 ms while reducing overall detection rate by approximately 4.3 percentage points.
To characterize fail-open behavior, we injected synthetic failures (random exception raises) at each stage of the pipeline at a 5% rate and measured the fraction of payloads that were delivered unmodified versus blocked. Under this failure injection regime, 98.7% of payloads were delivered (either fully sanitized, partially sanitized, or via fail-open pass-through), confirming that the fail-open guarantee effectively eliminates delivery blocking. Audit log coverage, the fraction of payloads for which some audit record was written, was 100%, including payloads delivered via fail-open pass-through, satisfying the forensic logging requirement.
The Safety-Net framework addresses the specific threat of injection and credential leakage attacks delivered via push notification payloads and multi-channel messages to AI agent systems. It does not address all possible attack vectors against AI-integrated communication infrastructure. Safety-Net provides no defenses against attacks delivered through long-term memory poisoning (where an attacker gradually corrupts an agent's persistent memory through many individually innocuous messages), against model-level jailbreaks that do not require injection via the context window, or against infrastructure-level attacks such as man-in-the-middle modification of notification payloads before they reach the sanitization layer. The fail-open guarantee, while critical for availability, means that a sufficiently capable adversary who can cause the sanitization pipeline to fail consistently (through denial-of-service attacks on the classifier, or by crafting payloads that reliably trigger parser exceptions) can potentially bypass sanitization entirely.
The evaluation presented in this paper used a synthetic adversarial dataset generated by the authors. While we endeavored to create a representative and challenging dataset spanning multiple attack categories, synthetic data does not fully capture the diversity of real-world adversarial payloads. The semantic injection category is likely underrepresented in terms of linguistic diversity. Independent red-team evaluation using live adversarial attack generation (e.g., via automated red-teaming systems; Perez et al., 2022b) would provide a more thorough characterization of Safety-Net's detection coverage.
The injection pattern library used by Stage 2 is a living artifact that requires ongoing maintenance as new injection techniques are discovered. The current library covers well-characterized attack patterns but is inherently reactive: it cannot detect novel injection techniques that have not yet been observed and catalogued. The semantic scoring stage (Stage 4) provides some defense against unknown patterns by detecting structural properties of injection attempts rather than their specific content, but its recall on genuinely novel techniques is uncertain. A productive direction for future work is the integration of active learning mechanisms that use the audit log of flagged payloads to continuously update both the pattern library and the semantic scoring classifier.
The nanoclaw multi-channel architecture introduces a cross-channel threat propagation risk that is partially but not fully addressed by the current isolation model. While agent instances in different contexts cannot directly access each other's conversation history, the fact that a single agent process may sequentially handle messages from multiple contexts (in implementations without strict process-level isolation) means that a sophisticated multi-turn injection attack could potentially exploit shared in-process state. Future work should examine process-level isolation for agent instances handling messages from different trust domains, and the use of formal information flow control mechanisms to enforce non-interference between contexts.
Deploying Safety-Net in production notification infrastructure requires careful attention to several operational concerns. The semantic scoring classifier must be kept synchronized across instances in horizontally scaled deployments to ensure consistent risk scores. Threshold configuration requires calibration against the specific notification population of the deployment (different enterprises will have different baseline rates of instruction-like text in their notification payloads). The credential pattern library requires regular updates to cover new service providers and credential formats. Despite these operational requirements, the modular architecture of Push_Guardian makes it straightforward to deploy as a sidecar service, a library integrated directly into the notification receiver, or a cloud function interposed in a notification webhook chain.
We have presented Safety-Net, a middleware hardening framework for AI-mediated notification and multi-channel messaging pipelines, realized through the Push_Guardian sanitization middleware and the nanoclaw multi-channel AI agent connector. The Safety-Net protocol's four-stage pipeline, covering payload parsing, injection pattern matching, credential scanning, and semantic risk scoring, addresses the principal attack categories targeting AI agents that receive inputs from push notification and messaging infrastructure. The fail-open guarantee ensures that sanitization does not become a single point of availability failure in production deployments. Empirical evaluation demonstrated 91–98% detection rates across five injection attack categories, false positive rates below 3.1%, and a median pipeline latency of 6.4 ms that is acceptable for the overwhelming majority of real-time messaging use cases.
As AI agents become increasingly embedded in communication infrastructure, the security of the message ingestion layer becomes as important as the security of the model itself. We believe Safety-Net represents a practical and deployable step toward hardening this layer, and we release both Push_Guardian and nanoclaw as open-source projects to facilitate adoption and further research.