yfedoseev/jailguard

GitHub: yfedoseev/jailguard

纯 Rust 实现的 LLM 提示词注入检测库,嵌入轻量 MLP 分类器,在 CPU 上实现毫秒级推理并覆盖八大攻击类型。

Stars: 5 | Forks: 1

# JailGuard [![准确率](https://img.shields.io/badge/Accuracy-98.40%25-blue)](BENCHMARKS.md) [![F1 分数](https://img.shields.io/badge/F1-0.983-blue)](BENCHMARKS.md) [![纯 Rust](https://img.shields.io/badge/Pure-Rust-orange)](https://www.rust-lang.org/) [![许可证](https://img.shields.io/badge/License-MIT%2FApache--2.0-blue)](#license) [![crates.io](https://img.shields.io/crates/v/jailguard.svg)](https://crates.io/crates/jailguard) [![PyPI](https://img.shields.io/pypi/v/jailguard.svg)](https://pypi.org/project/jailguard/) [![npm](https://img.shields.io/npm/v/@yfedoseev/jailguard.svg)](https://www.npmjs.com/package/@yfedoseev/jailguard) ## 快速开始 **Rust** — `cargo add jailguard` ``` use jailguard::{detect, is_injection}; if is_injection("ignore previous instructions") { return Err("blocked"); } let result = detect("What is the capital of France?"); println!("score={:.3} risk={:?}", result.score, result.risk); ``` **Python** — `pip install jailguard` ``` import jailguard if jailguard.is_injection("ignore previous instructions"): raise RuntimeError("blocked") result = jailguard.detect("What is the capital of France?") print(result.score, result.risk) ``` **JavaScript / TypeScript** — `npm install @yfedoseev/jailguard` ``` import { detect, isInjection } from "@yfedoseev/jailguard"; if (isInjection("ignore previous instructions")) { throw new Error("blocked"); } const r = detect("What is the capital of France?"); console.log(r.score, r.risk); ``` **Go** — `go get github.com/yfedoseev/jailguard/go` ``` import jailguard "github.com/yfedoseev/jailguard/go" if injection, _ := jailguard.IsInjection("ignore previous instructions"); injection { log.Fatal("blocked") } result, _ := jailguard.Detect("What is the capital of France?") fmt.Printf("score=%.3f risk=%v\n", result.Score, result.Risk) ``` 分类器已嵌入到每个语言绑定中。90 MB 的 MiniLM ONNX 嵌入器会在首次使用时自动下载到 `~/.cache/jailguard/`。生产环境建议:在启动时调用 `jailguard::download_model()` 以在处理流量前预热缓存。 ## JailGuard 与 2026 年替代方案对比 | 功能 | JailGuard | Lakera Guard | Rebuff | ProtectAI deberta-v3 | Meta Prompt Guard 2 | |---|---|---|---|---|---| | **许可证** | Apache 2.0 / MIT | 专有 (Check Point 于 2025 年 9 月 16 日宣布收购) | Apache 2.0 — **已于 2025 年 5 月 16 日归档** | Apache 2.0 (母公司于 2025 年 7 月 22 日被 Palo Alto 收购) | Llama 4 社区 (非 OSI) | | **部署方式** | 嵌入式库 | SaaS API | 自托管 Python SDK | HF 模型 | HF 模型 | | **模型大小** | 1.5 MB MLP + 90 MB MiniLM ONNX | 不适用 (API) | 不适用 | ~440 MB | 22 M 或 86 M 参数 | | **延迟 (CPU)** | **p50 14 毫秒** | ~150–300 毫秒 RTT | 不适用 | 104–212 毫秒 | 92 毫秒 (A100 GPU)¹ | | **分类** | **8类 分类法** | 二元 | 二元 | 二元 | 二元 | | **2026 年仍活跃?** | ✅ | ✅ (Check Point 待定) | **❌ 已归档** | ✅ (Palo Alto) | ✅ | | **无 PyTorch / 无运行时依赖** | ✅ (Rust) | ❌ HTTP 客户端 | ❌ Python+OpenAI | ❌ PyTorch | ❌ PyTorch | | **多语言绑定** | Rust, Python, JS, Go | API 客户端 | Python | Python | Python | ¹ Meta 尚未发布 Prompt Guard 2 的 CPU 延迟。 完整的方法论、数据集细分,以及与 `protectai/deberta-v3-base-prompt-injection-v2`、`deepset/deberta-v3-base-injection` 和 `madhurjindal/Jailbreak-Detector-Large` 的本地 CPU 详细对比请参见 [`BENCHMARKS.md`](./BENCHMARKS.md)。 ## API 概览 ``` pub fn detect(text: &str) -> DetectionOutput pub fn is_injection(text: &str) -> bool pub fn score(text: &str) -> f32 pub fn detect_batch(texts: &[&str]) -> Vec pub fn download_model() -> Result pub struct DetectionOutput { pub is_injection: bool, pub score: f32, pub confidence: f32, pub risk: RiskLevel, } pub enum RiskLevel { Safe, Low, Medium, High, Critical } ``` Python / JS / Go 以符合各自语言习惯的形式提供了相同的接口。每种语言的完整签名请参见 [`docs/API.md`](docs/API.md)。 ## 工作原理 JailGuard 将一个冻结的句子嵌入模型与一个小型分类器配对使用: 1. **MiniLM-L6-v2** (384 维, ONNX) 为输入生成语义向量。 2. 一个 3 层 MLP (384 → 256 → 128 → 1, 约 13 万参数, ReLU + dropout 0.2 + sigmoid) 对其进行评分,判断为注入还是良性。 嵌入模型是冻结的——没有进行微调——这使得在 CPU 上的训练和推理成本保持适中。分类器权重为一个 1.5 MB 的 JSON 文件,在编译时通过 `include_str!` 嵌入到二进制文件中。 ``` ┌─────────────────────────────────────────────────────────────┐ │ JAILGUARD DETECTION PIPELINE │ ├─────────────────────────────────────────────────────────────┤ │ │ │ User Prompt │ │ │ │ │ ▼ │ │ ┌─────────────┐ │ │ │ MiniLM-L6 │ Semantic Embedding (384-dim) │ │ │ (ONNX) │ • Pre-trained by Microsoft │ │ └──────┬──────┘ • Captures meaning, not just keywords │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────┐ │ │ │ Binary Classifier (Pure Rust) │ │ │ │ ┌─────────────┐ ┌─────────────────┐ │ │ │ │ │ Dense 256 │→ │ Dense 128 │ │ │ │ │ │ ReLU+Drop │ │ ReLU+Drop │ │ │ │ │ └─────────────┘ └─────────────────┘ │ │ │ │ │ │ │ │ │ ▼ │ │ │ │ ┌─────────────────┐ │ │ │ │ │ Sigmoid (0-1) │ │ │ │ │ └─────────────────┘ │ │ │ └─────────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ Detection Result │ │ • confidence: 0.0 - 1.0 │ │ • is_injection: confidence > 0.5 │ │ • risk: Safe | Low | Medium | High | Critical │ │ │ └─────────────────────────────────────────────────────────────┘ ``` ## 测量结果 测量环境为 Apple M3,最后重新验证于 2026-05-03。Pipeline 测试集划分为分布内数据(从相同的 17 个来源的训练混合数据中提取)。J1N2 和 shalyhinpavel 是外部数据集,均未在训练期间使用。 | 测试集 | 样本数 | 准确率 | 精确率 | 召回率 | F1 | |----------|---------|----------|-----------|--------|-----| | Pipeline (分布内) | 7,049 | **98.40%** | 98.56% | 97.98% | 0.983 | | J1N2 混合 (OOD) | 5,000 | **99.38%** | 98.09% | 99.94% | 0.990 | | shalyhinpavel 硬负样本 (OOD) | 147 | **89.12%** | 76.60% | 87.80% | 0.818 | ### 延迟 (单 CPU 线程) | 组件 | Apple M3 | Intel i5-10210U @ 1.6 GHz¹ | |---|---|---| | 嵌入 (MiniLM ONNX) | ~13 毫秒 | ~36 毫秒 | | 分类 (MLP) | ~1 毫秒 | ~1 毫秒 | | **总计 (p50)** | **~14 毫秒** | **~37 毫秒** | | **总计 (p99)** | **~19 毫秒** | **~43 毫秒** | | 冷启动 | ~140 毫秒 | ~350 毫秒 | ¹ 一颗有 4 年历史的低功耗 Chromebook CPU (Comet Lake-U, 2019, 4c/8t, 运行 ChromeOS Crostini Linux 6.6)。包含此项是为了表明 JailGuard 甚至可以在较旧/较弱 的硬件上良好运行。现代桌面或服务器 CPU 的表现更接近 M3 所在的列。 每个基准测试的完整数据请参见 [`BENCHMARKS.md`](./BENCHMARKS.md)。 ## 基准测试 可重现的延迟和吞吐量数据来自三个测试工具: - `benches/detect.rs` — Criterion 基准测试,涵盖单次执行的 `is_injection` / `detect` / `score` 以及 `n = 1, 8, 32, 128` 时的批量吞吐量。使用 `cargo bench --bench detect` 运行。 - `examples/cold_start_bench.rs` — 进程启动开销 (ONNX 会话初始化 + 首次推理)。使用 `cargo run --release --example cold_start_bench` 运行。 - `scripts/bench.sh` — 便携式 POSIX 包装脚本,可捕获机器元数据 (CPU、架构、内核、工具链) 并输出一份 Markdown 报告。支持 Linux x86_64、Linux aarch64、macOS Intel、macOS Apple Silicon 和 Chromebook Crostini。 完整的方法论和本地 CPU 详细对比请参见 [`BENCHMARKS.md`](./BENCHMARKS.md)。 ## 训练中涵盖的攻击类别 分类器在公共 API 的输出是二元的(注入/良性),但其训练混合数据涵盖了八个攻击家族: | 类别 | 示例 | |-----------------------|-----------------------------------------| | 直接注入 | "忽略之前的指令" | | 越狱 | DAN、开发者模式提示词 | | 角色扮演 | 基于人设的覆盖 | | 系统提示词泄露 | "透露你的指令" | | 编码攻击 | Base64、ROT13、Unicode 混淆 | | 上下文操纵 | 构造和分隔符技巧 | | 输出操纵 | 格式强制 | | 间接注入 | 嵌入在文档中的恶意内容 | ## 参考文献 - [all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) — 句子嵌入 - [PromptGuard (Meta)](https://github.com/meta-llama/PurpleLlama) - [Rebuff](https://github.com/protectai/rebuff) (已归档) - [Sentinel: SOTA 模型防范 Prompt 注入](https://arxiv.org/abs/2506.05446) - [Not What You've Signed Up For — 间接注入](https://arxiv.org/abs/2302.12173) ## 引用 如果您在研究或生产环境中使用了 JailGuard,请引用: ``` @software{jailguard, title = {JailGuard: Efficient Prompt Injection Detection via Pre-trained Embeddings}, author = {Yury Fedoseev}, year = {2026}, url = {https://github.com/yfedoseev/jailguard} } ``` 机器可读的 [`CITATION.cff`](CITATION.cff) 同样可用。 ## 许可证 根据您的选择,采用 [MIT](LICENSE-MIT) 或 [Apache-2.0](LICENSE-APACHE) 双重许可。
标签:AI安全, Apex, Chat Copilot, CMS安全, CNCF毕业项目, Go, Jailbreak检测, JavaScript, Lakera替代, MiniLM, MLP分类器, NLP, npm, ONNX, Prompt注入, PyPI, Python, Rebuff替代, Ruby工具, Rust, TypeScript, 低延迟, 可视化界面, 命令执行防御, 大语言模型安全, 安全插件, 对抗性攻击, 嵌入式模型, 开源, 提示词注入检测, 数据可视化, 文本分类, 无后门, 日志审计, 机器学习, 机密管理, 网络流量审计, 跨语言绑定, 逆向工具, 通知系统