naveenkumar-chandrasekar/LLM-guardrails-middleware

GitHub: naveenkumar-chandrasekar/LLM-guardrails-middleware

一个 Express 中间件库,为自有 LLM 路由提供 PII 脱敏、Prompt 注入检测、毒性过滤等安全护栏,策略存储在 S3 并通过内置 UI 管理。

Stars: 0 | Forks: 0

# llm-guardrails LLM guardrails middleware — 在现有的 LLM 路由上清理请求和响应,通过内置 UI 管理策略,并将规则存储在 S3 中。 ## 演示 一个使用此包的可用示例应用 — Express 后端配合 Ollama、Vue 前端,以及用于本地 S3 的 LocalStack: **[LLM Guardrails 演示聊天应用](https://github.com/naveenkumar-chandrasekar/LLM-guardrails-Demo-Chat-app)** 展示了在真实聊天路由上的 `guardrailsMiddleware`,位于 `/guardrails/` 的策略编辑器 UI,以及 S3 中的策略存储。 ## 安装 ``` npm install llm-guardrails ``` ## 工作原理 ``` Incoming request │ ▼ guardrailsMiddleware() ← checks input, blocks/redacts if needed │ ▼ Your route handler ← you own the LLM call │ ▼ guardrailsMiddleware() ← checks output before it leaves │ ▼ Response sent ``` ## 快速开始 ``` import express from "express"; import { guardrailsMiddleware, createGuardrailsRouter } from "llm-guardrails"; const app = express(); app.use(express.json()); // Policy editor UI + API app.use("/guardrails", createGuardrailsRouter()); // Your LLM route — middleware sanitizes input and output app.post("/chat", guardrailsMiddleware({ policyFile: "default.yaml" }), async (req, res) => { const reply = await yourLLM(req.body.messages); // messages already sanitized res.json({ content: reply }); // output checked before sending }); app.listen(3000); ``` 设置 S3 环境变量 — 策略将从您的 S3 存储桶读取并保存: ``` GUARDRAILS_S3_BUCKET=my-policies-bucket GUARDRAILS_S3_FOLDER=policies GUARDRAILS_S3_REGION=us-east-1 GUARDRAILS_S3_ENDPOINT=http://localhost:4566 # optional — for LocalStack ``` ## `guardrailsMiddleware(options?)` 挂载到任何 Express 路由上。在调用 LLM 之前运行输入检查,并在响应到达客户端之前拦截响应以运行输出检查。 ``` guardrailsMiddleware({ policyFile: "default.yaml", // optional — which S3 policy to enforce onBlocked: (violations, req) => {}, // optional — callback when request is blocked guardrails: { // optional — fine-tune built-in checks injection: { enabled: true }, sentiment: { enabled: true, action: "warn" }, outputPII: { enabled: true, action: "redact" }, }, }) ``` 在 middleware 运行之后,您的处理器中将可以使用 `req.guardrails`: ``` req.guardrails.inputViolations // violations found on input req.guardrails.outputViolations // violations found on output req.guardrails.blocked // true if request was blocked req.guardrails.sanitizedMessages // PII-redacted messages ``` ## `createGuardrailsRouter()` 挂载策略编辑器 UI 和 REST API。自动从环境变量中读取 S3 配置。 ``` app.use("/guardrails", createGuardrailsRouter()); ``` | 方法 | 路径 | 描述 | |--------|------|-------------| | `GET` | `/` | 内置策略编辑器 UI | | `GET` | `/v1/policies` | 列出 S3 中的策略文件 | | `GET` | `/v1/policies/:filename` | 获取策略的原始 YAML | | `PUT` | `/v1/policies/:filename` | 将策略保存到 S3 | | `GET` | `/v1/logs` | 请求历史记录 | | `GET` | `/v1/logs/stats` | 汇总违规统计信息 | ## 策略配置 策略是存储在 S3 中的 YAML 文件。middleware 会在首次使用时加载它们,并将其缓存在内存中(默认 60 秒 TTL)。 ``` GUARDRAILS_S3_BUCKET=my-bucket # required GUARDRAILS_S3_FOLDER=policies # optional GUARDRAILS_S3_REGION=us-east-1 # optional GUARDRAILS_S3_ENDPOINT=... # optional — S3-compatible storage ``` ### 策略文件结构 ``` rules: - id: no_financial_advice type: input_semantic action: block enabled: true threshold: 0.64 examples: - which stocks should I buy - give me financial advice - where should I put my money message: Financial advice requests are blocked - id: no_pii_in_output type: output_topic action: warn enabled: true keywords: - your SSN is - your credit card number message: Output may contain PII ``` ### 规则类型 | 类型 | 评估对象 | 方法 | |------|-----------|--------| | `input_topic` | 用户输入 | 关键词或正则表达式 | | `input_semantic` | 用户输入 | AI 相似度 — 捕获改写内容 | | `input_required` | 用户输入 | 必须包含特定短语 | | `output_topic` | LLM 输出 | 关键词或正则表达式 | | `output_semantic` | LLM 输出 | AI 相似度 — 捕获改写内容 | | `output_contains` | LLM 输出 | 必须包含特定短语 | | `output_required` | LLM 输出 | 必须包含特定短语 | ### 操作 | 操作 | 行为 | |--------|-----------| | `block` | 拒绝 — 立即返回 400,不调用 LLM | | `warn` | 记录违规,放行响应 | | `redact` | 从响应中剥离匹配的内容 | ### 语义匹配 需要 `@xenova/transformers` 来进行 AI 相似度匹配: ``` npm install @xenova/transformers ``` 模型完全在本地运行 — 无需外部 API。 ## 策略缓存 策略从 S3 加载一次并缓存在内存中。默认 TTL 为 60 秒。通过 UI 保存策略会立即使缓存失效。 ``` import { setPolicyTTL, clearPolicyCache } from "llm-guardrails"; setPolicyTTL(30_000); // 30 seconds setPolicyTTL(0); // always fetch from S3 clearPolicyCache(); // force immediate re-fetch ``` ## 内置 Guardrails 在每个请求上始终处于活动状态 — 无需策略文件。 **输入:** | Guardrail | 捕获内容 | |-----------|-----------------| | PII 检测 | 电子邮件、SSN、信用卡、API 密钥 — 自动进行脱敏 | | Prompt 注入 | 越狱、角色覆盖、指令覆盖 | | 代码 / SQL 安全性 | `DROP TABLE`、`rm -rf`、反向 shell | | 情感 | 威胁、敌意、人肉搜索 | | URL 安全性 | 原始 IP、`javascript:`、SSRF 目标 | **输出:** | Guardrail | 捕获内容 | |-----------|-----------------| | 毒性 | 仇恨言论、自残指导 | | 密钥 | 私钥、AWS 凭证、JWT | | PII | LLM 响应中的 PII — 默认进行脱敏 | | 代码安全性 | `eval()`、危险的 shell 模式 | ## 单独的 Guardrail 函数 直接使用检查功能,而无需 middleware: ``` import { checkPII, checkInjection, checkToxicity, evaluateInputSemanticRules, evaluateOutputSemanticRules, } from "llm-guardrails"; const { violations, sanitized } = checkPII(text, "redact"); const { violations } = checkInjection(text); const { violations } = checkToxicity(llmResponse); const violations = await evaluateInputSemanticRules(text, policy); ``` ## 策略 API ``` import { listPolicies, loadPolicy, savePolicy } from "llm-guardrails"; const s3 = { bucket: "my-bucket", folder: "policies" }; const files = await listPolicies(s3); const policy = await loadPolicy("default.yaml", s3); await savePolicy(yamlString, "custom.yaml", s3); ``` ## 许可证 MIT
标签:DLL 劫持, GNU通用公共许可证, MITM代理, Node.js, 中间件, 人工智能, 大语言模型, 数据脱敏, 用户模式Hook绕过, 自动化攻击