Skip to Content
ZeroLeaksDocs
Shield SDK

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

FieldTypeDescription
detectedbooleanWhether anything at or above the threshold was found
risk"none" | "low" | "medium" | "high" | "critical"Highest risk found, "none" when nothing was
matchesArray<{ category, pattern, confidence }>One entry per category found
scorenumberThe classifier's injection probability, 0 to 1. 0 when the classifier is off.

Options

OptionTypeDefaultDescription
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.
classifierfalse | { threshold?, highThreshold? }onA probability at or above threshold is medium risk, and at or above highThreshold high risk. false leaves only patterns and decoding.
normalizationDetectNormalizationOptions | falseall steps onWhat Shield undoes before matching. See Normalization steps.
denyPhrasesstring[]nonePhrases that are always flagged, as category deny_phrase, high risk.
customPatternsArray<{ category, regex, risk }>noneExtra patterns, matched on the lowercased, normalized views and on the input as written, so case-sensitive patterns work.
allowPhrasesstring[][]Phrases removed from the input before scanning. The rest of the input is still scanned.
excludeCategoriesstring[][]Categories to skip, built-in or custom. "classifier" hides classifier findings.
includeCategoriesstring[]every categoryCategories to keep. Findings in other categories are dropped.
secondaryDetector(input, result) => Promise<DetectResult | null>noneCalled by detectAsync() when something was detected. Return a replacement result, or null to keep the original.
escalate{ minScore?, detector }noneCalled by detectAsync() when nothing was detected but the classifier's score is at least minScore (default 0.15).
maxInputLengthnumber1048576 (1MB)Input longer than this is cut.

Pattern categories

CategoryRiskWhat it covers
instruction_overridecritical"Ignore previous instructions" and its many variants
authority_exploitcriticalFake system, developer, or admin markers and override codes
tool_hijackingcriticalCommands that send out data or run shell code
protocol_exploitcriticalFake MCP, tool, and extension messages
role_hijackhighPersona and mode switches such as unrestricted or developer modes
prompt_extractionhighAttempts to make the model reveal its instructions or secrets
indirect_injectionhighHidden-text markers and instructions addressed to an AI inside documents and tool results
encoding_attackmedium to highInstructions hidden in encodings, invisible characters, or Unicode tags
context_manipulationmediumClaims 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_controllowInstructions that dictate the exact output
social_engineeringlowPosing as the developer or owner, and research, testing, or fiction pretexts
classifiermedium or highThe built-in classifier's verdict
deny_phrasehighYour 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:

OptionDefaultDescription
roles["user", "tool", "function"]Roles whose messages are scanned
window4How 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
ValueReported riskClassifier threshold
"strict"low and above0.35
"balanced" (default)medium and abovethe model's own, 0.5
"permissive"high and above0.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
});

See provider wrapper options.

Limitations

  • These local options do not change the hosted API's thresholds or rule layer. It uses its release model and rule configuration.
  • detect() ignores secondaryDetector and escalate. Use detectAsync() to run them.
  • A hidden HTML element alone isn't a finding. Shield flags an injection inside one.

On this page