How sharma-open-source/opensentry works
Purpose and public surface
opensentry is a TypeScript prompt-injection validation library with a synchronous, zero-dependency Tier 0 and optional asynchronous semantic tiers. The principal API is createGuard, exposing single-text, message, stream, wrapper, and tool-call checks. Package entry/export wiring begins at src/index.ts; public contracts live in src/types.ts; orchestration is centered in src/guard.ts.
Guard orchestration and policy
A guard instance applies configured modes (enforce, soft, shadow), per-source rules, thresholds, hard blocks, cache behavior, metrics, and fail-open/closed decisions. It selects escalation based on source, flag-band status, and high-risk actions, then re-decides verdicts as evidence arrives. Relevant paths: src/guard.ts, src/config.ts, src/cache.ts.
Tier 0 synchronous detection pipeline
The edge-safe hot path first bounds input and detects flooding, then maintains separate model-facing and matching representations. It normalizes Unicode/invisible/confusable content, performs entropy-gated decoding and rescanning, and applies structural injection patterns. Stage implementations are organized in src/tiers/l0.ts, src/normalize/normalize.ts, src/tiers/l2.ts, and src/tiers/l3.ts. This tier avoids Node built-ins and is intended for Node, Deno, Bun, and Worker runtimes.
Evidence aggregation and decisions
Detectors emit typed reasons with weights and spans. Scores are combined through noisy-OR, mapped through source-specific thresholds and operating mode, and returned with sanitized/normalized copies, tier, latency, and degradation state. This evidence boundary is represented by src/scoring.ts, src/reason.ts, and src/types.ts. Hard-block rules can override normal threshold behavior.
Optional semantic escalation
Tier 1 invokes a local classifier only under escalation policy; it chunks long content, loads a singleton runner, applies timeout/circuit-breaker behavior, and folds classifier output into existing evidence. Core ML control code is in src/ml/chunker.ts, src/ml/circuit-breaker.ts, and src/ml/singleton.ts. Runtime-specific model integrations are split between Node ONNX (src/onnx/index.ts) and WASM/web ONNX (src/wasm/index.ts), using optional Transformers/ONNX dependencies.
Tier 2 can run an embedding-corpus signal and/or a caller-provided remote guard. Remote content is spotlight-delimited before transmission, and failures surface as degraded results rather than silently changing the decision. Paths: src/embedding/index.ts, src/remote/index.ts, src/spotlight/index.ts.
Integration and privileged-action boundaries
Framework adapters structurally integrate guard checks into Express, Hono, and Next request flows: src/middleware/express.ts, src/middleware/hono.ts, src/middleware/next.ts. checkToolCall is a pre-execution boundary: it enforces an allowlist, scans serialized arguments as high risk, and can reject tainted untrusted data entering privileged actions. Provenance tracking is in src/taint/index.ts.
Defense-in-depth companions and state
Independent subpath modules address boundaries outside stateless input scanning: prompt assembly and spotlighting (src/prompt/index.ts, src/spotlight/index.ts), outbound URL/secret/PII filtering (src/egress/index.ts), system-prompt leak canaries (src/canary/index.ts), and multi-turn risk accumulation with pluggable session storage (src/session/index.ts). These are opt-in layers around LLM input, output, and agent execution paths rather than prerequisites for the core guard.
Quality and distribution
The package is bundled from TypeScript via tsup.config.ts, with runtime compatibility and zero-Node-core guarantees architecturally important to Tier 0. Seed corpora and evaluation gates reside in corpus/ and eval/corpora.test.ts; larger real-corpus benchmarking and optional external model comparisons live in bench/. CI, release, and package distribution are defined by .github/workflows/ci.yml, .github/workflows/release.yml, and package.json.
Main entry points: guard.ts Guard orchestrator · l0.ts Tier 0 detector · scoring.ts Evidence scoring · singleton.ts Tier 1 classifier control
Components 20
Core validation
Synchronous guard orchestration and evidence decisions.
- Public API · Exports createGuard and public checks.
src/index.ts - Public contracts · Typed inputs, verdicts, reasons, and results.
src/types.ts - Guard orchestrator · Selects tiers and re-decides as evidence arrives.
src/guard.ts - Policy, cache and modes · Controls source rules, thresholds, cache, metrics, and failure behavior.
src/config.ts - Tier 0 detector · Bounds input, detects flooding, decodes, rescans, and matches injection structure.
src/tiers/l0.ts - Normalization · Maintains safe matching forms across Unicode and invisible content.
src/normalize/normalize.ts - Structural detectors · Additional pattern stages used by the synchronous pipeline.
src/tiers/l2.ts - Evidence scoring · Aggregates weighted reasons, hard blocks, thresholds, and verdict metadata.
src/scoring.ts - Typed reasons · Detector reason weights and spans.
src/reason.ts
Semantic escalation
Optional asynchronous detection tiers.
- Tier 1 classifier control · Chunks content and manages singleton, timeout, and circuit-breaker execution.
src/ml/singleton.ts - Node ONNX runtime · Optional Node model integration.
src/onnx/index.ts - WASM ONNX runtime · Optional web and Worker model integration.
src/wasm/index.ts - Tier 2 signals · Optional embedding corpus and caller-provided remote guard.
src/embedding/index.ts - Spotlight delimiter · Delimits content sent to remote semantic checks.
src/spotlight/index.ts
Integration boundaries
Request, agent, and LLM companion protections.
- Framework middleware · Express, Hono, and Next request-flow integration.
src/middleware/express.ts - Tool-call boundary · Allowlists tools and scans serialized high-risk arguments before execution.
src/taint/index.ts - Opt-in companion layers · Prompt assembly, egress filtering, canaries, and session risk accumulation.
src/prompt/index.ts
Distribution and quality
Build, evaluation, and release controls.
- Package build · Bundles TypeScript while preserving Tier 0 runtime compatibility.
tsup.config.ts - Evaluation corpora · Seed corpora and evaluation gates validate detection quality.
eval/corpora.test.ts - CI and release · Build, test, publish, and package distribution controls.
.github/workflows/ci.yml
Connections 24
- Public API → Public contracts: exports
- Public API → Guard orchestrator: creates
- Guard orchestrator → Policy, cache and modes: applies
- Guard orchestrator → Tier 0 detector: runs first
- Tier 0 detector → Normalization: normalizes
- Tier 0 detector → Structural detectors: rescans
- Tier 0 detector → Typed reasons: emits
- Typed reasons → Evidence scoring: weighted evidence
- Policy, cache and modes → Evidence scoring: thresholds and hard blocks
- Evidence scoring → Guard orchestrator: verdict updates
- Guard orchestrator → Tier 1 classifier control: policy escalation
- Tier 1 classifier control → Node ONNX runtime: Node runtime
- Tier 1 classifier control → WASM ONNX runtime: web runtime
- Tier 1 classifier control → Evidence scoring: classifier evidence
- Guard orchestrator → Tier 2 signals: optional escalation
- Spotlight delimiter → Tier 2 signals: delimited content
- Tier 2 signals → Evidence scoring: signal or degradation
- Framework middleware → Guard orchestrator: checks requests
- Tool-call boundary → Guard orchestrator: checks arguments
- Opt-in companion layers → Guard orchestrator: protects surrounding flows
- Package build → Public API: bundles
- Evaluation corpora → Tier 0 detector: tests detection
- CI and release → Package build: runs
- CI and release → Evaluation corpora: gates