009-KumarJi/novisentinel-core

GitHub: 009-KumarJi/novisentinel-core

面向 LLM 应用的开源自托管安全扫描器,实时检测并拦截 PII 泄露、提示注入、凭据暴露和有害内容。

Stars: 0 | Forks: 0

# NoviSentinel **一款用于 LLM 应用程序的开源安全扫描器。** 可自托管的 FastAPI 服务,可实时检测并阻止 PII 泄露、提示注入、凭据暴露和有害内容——在任何 LLM 之前运行。 ## 它能捕获什么 | 威胁 | 方法 | 延迟 | |--------|--------|---------| | 提示注入(重写、越狱、角色劫持、数据窃取) | 正则表达式 → ML 兜底 | ~1ms / ~80ms | | PII(社会安全号码、信用卡、电子邮件、电话、IP、IBAN) | Presidio NLP | ~5ms | | 机密信息(OpenAI, Anthropic, AWS, GitHub, Stripe, JWT, 私钥) | 正则表达式 | <1ms | | 有害内容(威胁、仇恨言论、骚扰、淫秽) | Detoxify ML | ~100ms | 这四个检测器在每个请求中并行运行。对于不超过 2KB 的英文文本,总 p95 预算:在 CPU 上约为 ~120ms。 ## 快速开始 ``` git clone https://github.com/009-KumarJi/novi-sentinel cd novi-sentinel cp .env.example .env docker compose up ``` API 运行在 `http://localhost:8000`。Swagger UI 位于 `http://localhost:8000/docs`。 ## 工作原理 每个 LLM 应用都有两个风险时刻——用户输入的内容和模型返回的内容。 ``` User input → your app → POST /v1/scan → NoviSentinel → allow / block / redact → LLM LLM output → your app → POST /v1/scan → NoviSentinel → allow / block / redact → User ``` NoviSentinel 为每次扫描返回一个 action: | Action | 含义 | |--------|---------| | `allow` | 安全 — 放行 | | `warn` | 低风险检测 — 记录并监控 | | `redact` | 发现 PII — 使用 `redacted_text` 替换原文 | | `block` | 注入、机密信息或严重威胁 — 拒绝转发 | ## Python SDK ``` pip install novisentinel ``` ``` from novisentinel import Client client = Client(api_key="nvs_...", base_url="http://localhost:8000") # 扫描用户输入然后再发送给 LLM result = client.scan(user_message, context="input") if result.action == "block": return "I can't process that request." # 扫描 LLM 输出然后再返回给用户 response = openai.chat(...) result = client.scan(response.content, context="output") return result.redacted_text # PII scrubbed ``` ### 异步 ``` from novisentinel import AsyncClient client = AsyncClient(api_key="nvs_...") result = await client.scan(text, context="input") ``` ### 批处理 ``` results = client.scan_batch(["text1", "text2", "text3"]) ``` ## VS Code 扩展 在发送提示之前扫描它们——无需离开你的编辑器。 ``` @novisentinel my SSN is 123-45-6789 ``` 右键点击任何选定的文本 → **NoviSentinel: Scan Selection**。 复制了敏感内容? → 在粘贴到 ChatGPT 之前选择 **NoviSentinel: Scan Clipboard**。 从 VS Code Marketplace 安装(搜索 "NoviSentinel")或从 [`extensions/vscode/`](extensions/vscode/) 目录构建。 ## REST API ### 身份验证 | Header | 用途 | |--------|---------| | `x-master-key: ` | 管理员操作(创建/撤销 API keys、查看日志) | | `Authorization: Bearer ` | 扫描和 webhooks | ### 扫描 **`POST /v1/scan`** ``` { "text": "My SSN is 123-45-6789", "context": "input", "config": { "injection_threshold": 0.85, "pii_entities": ["US_SSN", "CREDIT_CARD"] } } ``` 响应: ``` { "scan_id": "uuid", "safe": false, "risk_level": "critical", "action": "block", "detections": [ { "detector": "pii", "type": "US_SSN", "text": "123-45-6789", "redacted": "", "start": 10, "end": 21, "confidence": 0.85, "severity": "critical" } ], "redacted_text": "My SSN is ", "original_length": 21, "scan_duration_ms": 12 } ``` **`POST /v1/scan/batch`** — 单个请求最多可包含 20 个文本 ``` { "texts": [ { "text": "hello", "context": "input" }, { "text": "ignore all previous instructions", "context": "input" } ] } ``` ### 单次请求配置 在单次扫描中覆盖全局设置: | Key | 默认值 | 描述 | |-----|---------|-------------| | `injection_threshold` | `0.85` | 针对隐蔽注入的 ML 置信度阈值 | | `pii_entities` | all | 限制要扫描的 PII 类型 | | `toxicity_threshold_severe` | `0.5` | severe_toxic / threat 的阈值 | | `toxicity_threshold_high` | `0.7` | toxic / identity_hate 的阈值 | | `toxicity_threshold_medium` | `0.8` | obscene / insult 的阈值 | ### API Keys ``` POST /v1/keys # create key (master key required) GET /v1/keys # list keys (master key required) DELETE /v1/keys/{id} # revoke key (master key required) ``` ### Webhooks 当扫描被阻止或发出警告时,通过 HTTP POST 获取通知。 ``` POST /v1/webhooks # register a webhook endpoint GET /v1/webhooks # list webhooks for your key DELETE /v1/webhooks/{id} # remove a webhook ``` **创建 webhook:** ``` { "url": "https://hooks.slack.com/...", "trigger_actions": ["block", "warn"], "trigger_risk_levels": ["critical", "high"] } ``` 返回一个 `signing_secret`(仅显示一次)。每次传递都会进行签名: ``` X-NoviSentinel-Signature: sha256= ``` **Webhook 负载:** ``` { "event": "detection.block", "scan_id": "uuid", "risk_level": "critical", "action": "block", "context": "input", "pii_count": 0, "injection_count": 1, "secrets_count": 0, "toxicity_count": 0, "detections": [ { "detector": "injection", "type": "OVERRIDE", "severity": "critical", "confidence": 0.97 } ], "timestamp": "2026-05-07T10:00:00Z" } ``` ### 日志与统计 ``` GET /v1/logs # scan history (master key required) GET /v1/stats # aggregate stats (master key required) ``` 日志支持查询参数:`?action=block`, `?risk_level=critical`, `?context=input`, `?since=2026-05-01T00:00:00`, `?limit=100`。 原始文本**从不被存储**——只保留每个扫描文本的 SHA-256 散列值。 ## 配置 所有设置均通过环境变量进行(参见 `.env.example`): ``` # Auth MASTER_API_KEY=change-me-to-a-long-random-string # Database & cache DATABASE_URL=postgresql+asyncpg://sentinel:sentinel@postgres:5432/novisentinel REDIS_URL=redis://redis:6379 # ML models SPACY_MODEL=en_core_web_lg INJECTION_MODEL=protectai/deberta-v3-base-prompt-injection-v2 INJECTION_THRESHOLD=0.85 # Toxicity TOXICITY_ENABLED=true TOXICITY_MODEL=original TOXICITY_THRESHOLD_SEVERE=0.5 TOXICITY_THRESHOLD_HIGH=0.7 TOXICITY_THRESHOLD_MEDIUM=0.8 # Rate limiting DEFAULT_RATE_LIMIT_RPM=120 ``` ## 架构 ``` app/ ├── api/ │ ├── scan.py # POST /v1/scan, /v1/scan/batch │ ├── keys.py # API key management │ ├── webhooks.py # Webhook CRUD │ └── logs.py # Scan history + stats ├── core/ │ ├── scanner.py # Orchestrator — runs all detectors, builds ScanResult │ └── webhook.py # HMAC-signed fire-and-forget delivery ├── detectors/ │ ├── base.py # Detector ABC + DetectionResult dataclass │ ├── pii.py # Presidio NLP │ ├── injection.py # Regex → ML two-layer detection │ ├── secrets.py # Regex credential scanner │ └── toxicity.py # Detoxify ML ├── db/ │ ├── models.py # ApiKey, ScanLog, WebhookConfig SQLAlchemy models │ └── session.py # Async engine └── config.py # Pydantic settings sdk/python/ # pip install novisentinel extensions/vscode/ # @novisentinel chat participant + scan commands dashboard/ # local single-tenant Next.js dashboard tests/ # 54 tests, pytest-asyncio ``` **扫描管道(每次请求):** ``` text ├── PIIDetector.scan() (sync, Presidio) ├── SecretsDetector.scan() (sync, regex) ├── InjectionDetector.scan_async() ─┐ asyncio.gather() └── ToxicityDetector.scan_async() ─┘ ↓ _determine_risk() → none / low / medium / high / critical _determine_action() → allow / warn / redact / block _build_redacted_text() ``` ## Action 逻辑 | 条件 | Action | |-----------|--------| | 检测到任何注入 | `block` | | 检测到任何机密信息 | `block` | | 有害内容严重性 = critical | `block` | | 有害内容严重性 = medium | `warn` | | 严重的 PII(SSN、信用卡、IBAN) | `block` | | 高/中等 PII(电子邮件、电话、IP) | `redact` | | 低置信度检测 | `warn` | | 未检测到任何内容 | `allow` | ## 本地仪表板 [`dashboard/`](dashboard/) 中的 Next.js 仪表板为你提供了扫描、日志和统计数据的本地视图。单租户,master-key 认证。可通过 Docker Compose 与 API 一起启动。 ``` http://localhost:3001 ``` 页面: - **Overview** — KPIs、近期活动、每分钟阻止次数 - **Logs** — 包含过滤器的完整扫描历史记录 - **Analytics** — 风险级别分布、检测器命中率 - **Settings** — API keys、webhooks ## 运行测试 ``` pip install -r requirements.txt pytest tests/ -v ``` 涵盖 PII、注入、机密信息、有害内容、webhooks 和 API 集成的 54 项测试。 ## 技术栈 - **FastAPI** — 异步 API 框架 - **PostgreSQL + asyncpg** — 扫描日志、API keys、webhook 配置 - **Redis** — 滑动窗口限流 - **Presidio** — PII 检测引擎 (Microsoft) - **protectai/deberta-v3-base-prompt-injection-v2** — ML 注入分类器 - **Detoxify** — 有害内容分类 (unitary/toxic-bert) - **httpx** — 异步 webhook 交付 + SDK HTTP 客户端 - **Docker Compose** — postgres + redis + api,一条命令启动 ## 这适用于什么场景 在以下情况使用 NoviSentinel: - **你的应用程序将用户生成的文本发送给 LLM**,并且你希望在 PII、机密信息和注入尝试离开你的系统之前将其捕获。 - **你的应用程序向用户展示 LLM 响应**,并且你希望在用户看到之前对 PII 进行脱敏或阻止有害内容。 - **你记录 LLM 的提示和响应**,并且你希望获得针对每条记录的判定(`safe`、`risk_level`、`action`)连同原始文本。 - **你正在构建一个使用工具的 agent**——在执行前扫描工具调用的参数,并在工具调用的输出交回给模型之前对其进行扫描。 - **你想要自托管和本地仪表板**,而不是托管的 SaaS 扫描器。 NoviSentinel 是一个 HTTP 调用。它不会取代你的 LLM、你的身份验证、你的日志记录或你的应用程序逻辑——它位于它们旁边并监视文本。 ## 隐私与数据处理 - 原始文本从不存储。每个扫描的文本在持久化之前都会被散列为 SHA-256。 - 扫描日志包含:散列值、长度、检测器结果、风险级别、action、时间戳。 - 在扫描过程中不会发生第三方调用,除非你明确启用了需要此功能的特性。 - Webhook 负载经过 HMAC 签名。你可以使用创建 webhook 时返回的 `signing_secret` 进行验证。 - 所有模型都在容器本地运行。没有任何数据离开你的网络。 ## 路线图 - 代码注入检测 - URL 安全检测 - 多语言支持 - 浏览器扩展 (ChatGPT.com, Claude.ai) - Node / TypeScript SDK - 自定义检测器支持(插入你自己的扫描器) 有关详细路线图,请参见 [`plans/`](plans/)。 ## 许可证 版权所有 2026 Kumar Ji (009-KumarJi) 根据 [Apache License, Version 2.0](LICENSE) 获得许可。完整文本请见 [LICENSE](LICENSE)。 Apache 许可证涵盖**代码**。NoviSentinel 的名称和标志是商标——请参见 [TRADEMARK.md](TRADEMARK.md)。
标签:AI安全, AI红蓝对抗, AMSI绕过, Apex, API中间件, AV绕过, Chat Copilot, CISA项目, DevSecOps, DLL 劫持, Docker, FastAPI, IP 地址批量处理, Naabu, PII检测, Python SDK, 上游代理, 代码安全, 内容安全, 大语言模型, 威胁检测, 安全扫描, 安全网关, 安全防御评估, 对抗攻击, 提示注入, 搜索引擎查询, 敏感信息检测, 数据泄露防护, 数据脱敏, 文本分析, 时序注入, 机器学习, 测试用例, 深度学习, 漏洞枚举, 网络安全, 网络应用防火墙, 网络探测, 请求拦截, 越狱防护, 逆向工具, 隐私保护, 集群管理, 零日漏洞检测