Local detection
Synchronous, in-process prompt injection detection with patterns, payload decoding, and a built-in classifier. No model download.
detect from @zeroleaks/shield/local checks text for prompt injection synchronously, inside your process. detectAsync also runs the asynchronous detectors you configure. The root detect export is asynchronous and calls the hosted API; see the Shield API quickstart.
Run them on everything that reaches the model's context: user messages, retrieved documents, web pages, emails, and tool results. The provider wrappers do this for user messages and tool results automatically.
import { detect, detectAsync } from "@zeroleaks/shield/local";
const result = detect(userInput);
if (result.detected) {
console.log(`Injection detected: ${result.risk} risk, score ${result.score?.toFixed(2)}`);
for (const m of result.matches) {
console.log(` - ${m.category}: ${m.pattern}`);
}
}
// A retrieved document or tool result
const doc = detect(pageText);
// Only report high and critical findings
const strict = detect(userInput, { threshold: "high" });
// Stricter classifier
const fewerFlags = detect(userInput, { classifier: { threshold: 0.8 } });
// Add a custom pattern
const withCustom = detect(userInput, {
customPatterns: [{ category: "internal_marker", regex: /\[internal:\s*.+\]/i, risk: "critical" }],
});
// Let a second check overrule the result
const verified = await detectAsync(userInput, {
secondaryDetector: async (input) => {
const isInjection = await classifyWithLLM(input); // your own check
return isInjection ? null : { detected: false, risk: "none", matches: [] };
},
});Detection scans the whole input, not only a prefix. The built-in classifier is a logistic-regression model over hashed character and word n-grams, trained on public labeled datasets and shipped inside the SDK as 4-bit weights. A short chat message takes about 40µs and an 8KB document about 2ms on a server CPU.
Returns
| Field | Type | Description |
|---|---|---|
detected | boolean | Whether anything at or above the threshold was found |
risk | "none" | "low" | "medium" | "high" | "critical" | Highest risk found, "none" when nothing was |
matches | Array<{ category, pattern, confidence }> | One entry per category found |
score | number | The classifier's injection probability, 0 to 1. 0 when the classifier is off. |
Options
| Option | Type | Default | Description |
|---|---|---|---|
sensitivity | "strict" | "balanced" | "permissive" | "balanced" | Preset for threshold and the classifier threshold. See Set sensitivity. |
threshold | "low" | "medium" | "high" | "critical" | "medium" | Findings below this risk are not reported. |
classifier | false | { threshold?, highThreshold? } | on | A probability at or above threshold is medium risk, and at or above highThreshold high risk. false leaves only patterns and decoding. |
normalization | DetectNormalizationOptions | false | all steps on | What Shield undoes before matching. See Normalization steps. |
denyPhrases | string[] | none | Phrases that are always flagged, as category deny_phrase, high risk. |
customPatterns | Array<{ category, regex, risk }> | none | Extra patterns, matched on the lowercased, normalized views and on the input as written, so case-sensitive patterns work. |
allowPhrases | string[] | [] | Phrases removed from the input before scanning. The rest of the input is still scanned. |
excludeCategories | string[] | [] | Categories to skip, built-in or custom. "classifier" hides classifier findings. |
includeCategories | string[] | every category | Categories to keep. Findings in other categories are dropped. |
secondaryDetector | (input, result) => Promise<DetectResult | null> | none | Called by detectAsync() when something was detected. Return a replacement result, or null to keep the original. |
escalate | { minScore?, detector } | none | Called by detectAsync() when nothing was detected but the classifier's score is at least minScore (default 0.15). |
maxInputLength | number | 1048576 (1MB) | Input longer than this is cut. |
Pattern categories
| Category | Risk | What it covers |
|---|---|---|
instruction_override | critical | "Ignore previous instructions" and its many variants |
authority_exploit | critical | Fake system, developer, or admin markers and override codes |
tool_hijacking | critical | Commands that send out data or run shell code |
protocol_exploit | critical | Fake MCP, tool, and extension messages |
role_hijack | high | Persona and mode switches such as unrestricted or developer modes |
prompt_extraction | high | Attempts to make the model reveal its instructions or secrets |
indirect_injection | high | Hidden-text markers and instructions addressed to an AI inside documents and tool results |
encoding_attack | medium to high | Instructions hidden in encodings, invisible characters, or Unicode tags |
context_manipulation | medium | Claims that earlier instructions were a test or the real ones differ, fake end-of-prompt markers, and references to a discussion that never happened |
output_control | low | Instructions that dictate the exact output |
social_engineering | low | Posing as the developer or owner, and research, testing, or fiction pretexts |
classifier | medium or high | The built-in classifier's verdict |
deny_phrase | high | Your denyPhrases |
Low-risk categories only run when threshold is "low" and the input shows another sign of an attack.
Conversations
detectConversation() scans every user and tool message on its own. It also scans the latest user messages joined together, which catches an instruction split across turns.
import { detectConversation } from "@zeroleaks/shield/local";
const result = detectConversation(messages, { window: 4 });
if (result.detected) {
console.warn("flagged messages:", result.flagged.map((f) => f.index));
console.warn("split across turns:", result.splitAcrossTurns);
}It takes every detect() option, plus:
| Option | Default | Description |
|---|---|---|
roles | ["user", "tool", "function"] | Roles whose messages are scanned |
window | 4 | How many of the latest user messages are also scanned joined together. 0 or 1 turns it off. |
False positives
The classifier can flag benign text. Short imperative requests to the model, such as "from now on, always answer in French", are the most likely to be flagged.
Since the wrappers block by default, try your real traffic with onDetection: "warn" and onInjectionDetected first to review what would be blocked. Then raise classifier.threshold, use excludeCategories or allowPhrases, or add a secondaryDetector for the cases you see.
Customize detection
These options apply to local detect and detectAsync, and to local detection inside provider wrappers.
Set sensitivity
sensitivity controls how readily text is classified as an injection:
detect(text, { sensitivity: "strict" }); // catch more, accept more false positives
detect(text, { sensitivity: "permissive" }); // flag only clear attacks| Value | Reported risk | Classifier threshold |
|---|---|---|
"strict" | low and above | 0.35 |
"balanced" (default) | medium and above | the model's own, 0.5 |
"permissive" | high and above | 0.75 |
threshold and classifier take precedence over the preset.
Add deny phrases
denyPhrases match case-insensitively with any spacing, in the text as written and after normalization. Use customPatterns for anything a phrase list can't express, and allowPhrases for legitimate text that trips detection in your domain:
detect(text, {
denyPhrases: ["enable maintenance override"],
customPatterns: [{ category: "internal_codes", regex: /\bOVR-\d{4}\b/, risk: "high" }],
allowPhrases: ["for research purposes only"],
});Choose categories
excludeCategories drops categories you don't want, and includeCategories keeps only the ones you list:
// Only care about prompt extraction and the classifier's verdict
detect(text, { includeCategories: ["prompt_extraction", "classifier"] });Add your own detector
detectAsync() accepts two hooks. secondaryDetector re-checks text Shield flagged, for example to clear false positives in your domain. escalate sends text Shield didn't flag to a detector you choose. Any async function that returns a DetectResult, or null to keep Shield's result, works.
Shield includes createModelDetector() for a local transformer model, createLlmDetector() for an LLM call, and anyOf() to combine several. Accuracy and latency depend on the artifacts and hardware. With an LLM detector, the text is sent to the LLM's provider, so choose one you would trust with your users' messages and tool results.
Use different rules per source
The provider wrappers take separate options for user messages (detect) and for tool results and documents (scanToolResults), so you can be stricter with content from outside:
shieldOpenAI(client, {
detect: { sensitivity: "balanced" },
scanToolResults: { sensitivity: "strict", denyPhrases: ["send the file to"] },
onDetection: "warn", // report instead of block while you tune
});Limitations
- These local options do not change the hosted API's thresholds or rule layer. It uses its release model and rule configuration.
detect()ignoressecondaryDetectorandescalate. UsedetectAsync()to run them.- A hidden HTML element alone isn't a finding. Shield flags an injection inside one.