alikesk222/prompt-injection-guard

GitHub: alikesk222/prompt-injection-guard

该库为 Node.js/TypeScript 环境下的 LLM 应用提供实时的提示词注入攻击检测与拦截能力。

Stars: 0 | Forks: 0

# prompt-injection-guard [![CI](https://static.pigsec.cn/wp-content/uploads/repos/cas/ad/ad5834178f7599af9fdda11629d49cae07f2997beec49821b2920eff5bfd50e7.svg)](https://github.com/alikesk222/prompt-injection-guard/actions/workflows/ci.yml) [![npm](https://img.shields.io/npm/v/prompt-injection-guard.svg)](https://www.npmjs.com/package/prompt-injection-guard) [![License: MIT](https://img.shields.io/badge/License-MIT-green?style=flat-square)](LICENSE) [![零依赖](https://img.shields.io/badge/Dependencies-zero-brightgreen?style=flat-square)](#) **prompt-injection-guard** 位于您的用户与 LLM 之间。它使用多层分析(模式匹配 + 启发式异常评分)实时检测提示词注入攻击,并在其触及模型之前予以拦截。 这是 [prompt-shield](https://github.com/alikesk222/prompt-shield)(Python 版)的 TypeScript/npm 对应版本——采用相同的检测引擎和测试语料库,专为 Node.js / Next.js / LangChain.js 生态系统进行了移植。 ## 安装 ``` npm install prompt-injection-guard ``` ## 快速开始 ``` import { isSafe, detect, Shield } from "prompt-injection-guard"; // One-liner guard if (!isSafe(userInput)) { return "I cannot process that request."; } // Detailed result const result = detect(userInput); console.log(result.score); // 0.0 - 1.0 console.log(result.threatLevel); // 'none' | 'low' | 'medium' | 'high' | 'critical' console.log(result.categories); // ['direct_override', 'role_confusion'] console.log(result.isInjection); // true / false ``` ## 检测层 ### 1. 基于规则的模式匹配 涵盖 8 种攻击类别的 30 多个正则表达式模式: | 类别 | 示例 | |----------|---------| | `direct_override` | “忽略之前的指令”、“无视所有规则” | | `role_confusion` | DAN 越狱、“扮演”、“你现在是”、邪恶模式 | | `prompt_extraction` | “复述你的系统提示词”、“你的指令是什么” | | `delimiter_injection` | `[INST]`、`<\|im_start\|>`、``、JSON 角色注入 | | `encoding` | 零宽字符、西里尔字母形似字、base64 指令 | | `indirect_injection` | HTML 注释注入、隐藏的指令标记 | | `data_exfiltration` | URL 参数窃取、“总结并发送” | | `goal_hijacking` | 任务替换、“你的真正目的是” | ### 2. 启发式异常评分 - **指令密度** —— 命令动词与总词数的比例 - **分隔符密度** —— 可疑的 `###`、`===` 及 XML 标签频率 - **特殊字符比例** —— 控制/不可见字符的滥用 - **香农熵** —— 检测编码/混淆的 payload - **长度惩罚** —— 异常冗长的输入 最终得分 = `patternScore × 0.7 + heuristicScore × 0.3` ## Shield 类 ``` import { Shield } from "prompt-injection-guard"; const shield = new Shield({ threshold: 0.5, // score threshold (default 0.5) strict: false, // if true, throws InjectionDetected instead of returning sanitize: true, // auto-sanitize input before scanning log: true, // console.warn on detections }); const result = shield.scan(userInput); // Sanitize + scan in one step const [clean, scanned] = shield.sanitizeAndScan(userInput); if (!scanned.isInjection) { callLLM(clean); } // Strict mode — throws try { const strictShield = new Shield({ strict: true }); strictShield.scan(userInput); } catch (e) { if (e instanceof InjectionDetected) console.log(e.result.score); } ``` ## Express 中间件 ``` import express from "express"; import { expressMiddleware } from "prompt-injection-guard/express"; const app = express(); app.use(express.json()); app.use(expressMiddleware()); // scans "message", "prompt", "query", "input" fields app.post("/chat", (req, res) => { res.json({ response: callLLM(req.body.message) }); }); ``` ## Next.js API 路由 ``` import { Shield } from "prompt-injection-guard"; const shield = new Shield(); export async function POST(req: Request) { const { message } = await req.json(); const result = shield.scan(message); if (result.isInjection) { return Response.json({ error: "Rejected: potential prompt injection" }, { status: 400 }); } return Response.json({ response: await callLLM(message) }); } ``` ## 输入清理器 ``` import { sanitize } from "prompt-injection-guard"; const clean = sanitize(userInput, { removeInvisible: true, // strip zero-width chars removeControl: true, // strip control characters removeDelimiters: true, // strip [INST], <|im_start|>, etc. normalize: true, // Unicode NFC normalization collapseNewlines: true, // collapse 3+ newlines to 2 maxLength: 4096, // hard truncate }); ``` ## 自定义模式 ``` import { Detector } from "prompt-injection-guard"; const detector = new Detector({ customPatterns: [ { name: "my_secret_keyword", regex: /ACME_INTERNAL_BYPASS/i, category: "custom", weight: 1.0, description: "Internal bypass keyword", }, ], }); ``` ## 检测结果 ``` const result = detect(text); result.isInjection; // boolean result.score; // number 0.0-1.0 result.threatLevel; // 'none' | 'low' | 'medium' | 'high' | 'critical' result.categories; // string[] — attack categories found result.matchedRules; // MatchedRule[] — detailed rule matches result.heuristicScore; // number — anomaly component result.inputLength; // number — input character count result.sanitized; // string | null — sanitized text (if sanitize=true) ``` ## 对比 prompt-shield (Python) | | prompt-injection-guard (本项目) | prompt-shield | |--|---|---| | **运行时** | Node.js / TypeScript | Python | | **安装** | `npm install prompt-injection-guard` | `pip install prompt-injection-shield` | | **框架** | Express, Next.js | FastAPI, Flask | | **检测引擎** | 相同的模式 + 启发式算法,1:1 移植 | 原始版本 | 相同的检测引擎,不同的运行时——请根据您的技术栈选择合适的版本。 ## 许可证 MIT —— 详见 [LICENSE](LICENSE)
标签:DLL 劫持, MITM代理, TypeScript, Web安全, 人工智能, 大语言模型, 安全插件, 用户模式Hook绕过, 自动化攻击, 蓝队分析, 默认DNS解析器