muneebs/csrf-armor

GitHub: muneebs/csrf-armor

提供五种可配置安全策略的现代 CSRF 防护库,框架无关、零依赖,支持 Next.js 和 Express 等主流运行时。

Stars: 4 | Forks: 1

# CSRF-Armor CSRF Armor [![CodeQL](https://static.pigsec.cn/wp-content/uploads/repos/2026/04/025e319af2211800.svg)](https://github.com/muneebs/csrf-armor/actions/workflows/codeql-analysis.yml) [![CI](https://static.pigsec.cn/wp-content/uploads/repos/2026/04/7fb5a4a148211801.svg)](https://github.com/muneebs/csrf-armor/actions/workflows/ci.yml) [![npm 版本](https://badge.fury.io/js/%40csrf-armor%2Fcore.svg)](https://badge.fury.io/js/%40csrf-armor%2Fcore) [![许可证: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 现代、与框架无关的 CSRF 防护库,提供多种安全策略。 * ✅ **与框架无关**:支持 Next.js、Node.js/Express、Vite 等 * 🔐 **多种策略**:签名令牌、双重提交 Cookie、签名双重提交、Origin 检查、混合模式 * 🚀 **兼容 Edge Runtime**:使用 Web Crypto API,适配现代环境 * 📦 **零依赖**:安全且轻量的核心库 * 🔧 **高度可配置**:可自定义令牌、Cookie、路径和验证逻辑 * ✅ **经过充分测试**:全面的测试覆盖 * 📦 **仅支持 ESM**:现代 ESM 包并提供 TypeScript 支持 * 🔒 **自动化安全扫描**:包含 CodeQL 分析和自定义安全检查 ## 📦 包 ### 特定框架的包 | 包 | 描述 | 安装 | |----------------------------------------------|----------------------------------|-----------------------------| | **[@csrf-armor/nextjs](./packages/nextjs)** | Next.js App Router 中间件 | `npm i @csrf-armor/nextjs` | | **[@csrf-armor/express](./packages/express)** | Express.js 中间件 | `npm i @csrf-armor/express` | ### 核心包 | 包 | 描述 | 安装 | |---------|-------------|---------| | **[@csrf-armor/core](./packages/core)** | 与框架无关的核心包 | `npm i @csrf-armor/core` | ## 🛡️ 安全策略 ### 1. 签名令牌策略 ``` { strategy: 'signed-token', secret: process.env.CSRF_SECRET!, token: { expiry: 3600 } } ``` - **工作原理**:生成带有过期时间的 HMAC 签名令牌 - **适用场景**:无状态应用、微服务 - **安全性**:高(加密保护 + 过期机制) ### 2. 双重提交 Cookie 策略 ``` { strategy: 'double-submit' } ``` - **工作原理**:在 Cookie 和请求头中使用相同的令牌 - **适用场景**:本地开发 - **安全性**:非常低(不推荐用于生产环境) ### 3. 签名双重提交 Cookie 策略 ⭐ ``` { strategy: 'signed-double-submit', secret: process.env.CSRF_SECRET! } ``` - **工作原理**:在客户端可访问的 Cookie 和请求头中使用未签名令牌,在仅限服务器的 Cookie 中使用签名令牌进行验证 - **适用场景**:高安全性应用、金融服务 - **安全性**:非常高(结合了加密签名和双重提交模式) ### 4. Origin 检查策略 ``` { strategy: 'origin-check', allowedOrigins: ['https://yourdomain.com'] } ``` - **工作原理**:验证 Origin/Referer 请求头 - **适用场景**:具有已知客户端来源的 API - **安全性**:中(可能会被某些代理绕过) ### 5. 混合策略 ``` { strategy: 'hybrid', secret: process.env.CSRF_SECRET!, allowedOrigins: ['https://yourdomain.com'] } ``` - **工作原理**:结合签名令牌和 Origin 验证 - **适用场景**:最高安全要求 - **安全性**:最高(多重验证层) ## 🔒 安全建议 ### 策略选择指南 | 使用场景 | 推荐策略 | 原因 | |----------|---------------------|-----| | **银行/金融** | `signed-double-submit` | 加密保护 + 双重验证 | | **电子商务** | `signed-double-submit` 或 `hybrid` | 为交易提供强力保护 | | **常规 Web 应用** | `double-submit` | 安全性与简洁性的良好平衡 | | **公共 API** | `origin-check` + `signed-token` | 控制访问来源 | | **微服务** | `signed-token` | 无状态,可跨服务使用 | | **高流量站点** | `double-submit` | 开销最小 | | **企业/管理后台** | `hybrid` | 最高级别的安全层 | ### 安全最佳实践 1. **始终使用 HTTPS** 在生产环境中 (`cookie.secure: true`) 2. **使用强密钥**(32 个以上的随机字符,定期轮换) 3. **设置适当的 Cookie 属性**: - `sameSite: 'strict'` 以获得最大保护 - `httpOnly: false` 仅在需要客户端访问时使用 - 在生产环境中 `secure: true` 4. **监控攻击** - 记录验证失败日志 5. **设置较短的令牌过期时间**(1-4 小时)用于敏感操作 **⚠️ 重要安全提示:** - 切勿在生产环境中使用默认密钥 - `signed-double-submit` 策略需要 `httpOnly: false` 以便客户端访问 Cookie - 始终验证你的 CSRF 密钥是否已正确设置:`process.env.CSRF_SECRET` ## ⚙️ 配置选项 所有包共享相同的核心配置接口: ``` interface CsrfConfig { strategy?: 'double-submit' | 'signed-double-submit' | 'signed-token' | 'origin-check' | 'hybrid'; secret?: string; token?: { expiry?: number; // Token expiry in seconds (default: 3600) headerName?: string; // Header name (default: 'X-CSRF-Token') fieldName?: string; // Form field name (default: 'csrf_token') }; cookie?: { name?: string; // Cookie name (default: 'csrf-token') secure?: boolean; // Secure flag (default: true) httpOnly?: boolean; // HttpOnly flag (default: false) sameSite?: 'strict' | 'lax' | 'none'; // SameSite (default: 'lax') path?: string; // Path (default: '/') domain?: string; // Domain (optional) maxAge?: number; // Max age in seconds (optional) }; allowedOrigins?: string[]; // Allowed origins for origin-check excludePaths?: string[]; // Paths to exclude from CSRF protection skipContentTypes?: string[]; // Content types to skip } ``` ## 🔒 安全与分析 ### 自动化安全扫描 CSRF-Armor 包含全面的安全分析: - **CodeQL 分析**:在每次 PR 和 push 时进行自动扫描 - **每周安全扫描**:定时漏洞检测 - **自定义安全检查**:针对 CSRF 特定漏洞的检测 ### 本地安全测试 ``` # 运行全面的安全检查 pnpm run security:check # 检查特定问题 pnpm run security:secrets # Hardcoded secrets pnpm run security:timing # Timing attack vulnerabilities pnpm run security:random # Weak random generation ``` ## 📚 框架文档 - **[Next.js 包](./packages/nextjs/README.md)** - App Router 中间件,React hooks - **[核心包](./packages/core/README.md)** - 与框架无关的实现 ## ⚡ 性能特征 **策略性能(相对比较):** | 策略 | 计算开销 | 内存使用 | 安全级别 | 最佳用例 | |----------|------------------------|---------------|----------------|---------------| | **origin-check** | 最低(请求头验证) | 最低 | 中 | 已知客户端来源 | | **double-submit** | 非常低(无加密) | 低 | 中 | 常规 Web 应用 | | **signed-double-submit** | 低(1 次 HMAC 操作) | 低 | 高 | 高安全性应用 | | **signed-token** | 低(1 次 HMAC 操作) | 低 | 高 | 无状态 API | | **hybrid** | 中(HMAC + 请求头) | 低 | 最高 | 最高安全需求 | **性能说明:** - Origin 检查和双重提交的 CPU 开销最小 - 签名策略需要 HMAC 操作(Web Crypto API) - 混合策略结合了多个验证步骤 - 实际性能取决于硬件、请求量和实现细节 ## 🛠️ 开发 ### 设置 ``` git clone https://github.com/muneebs/csrf-armor.git cd csrf-armor pnpm install ``` ### 命令 ``` pnpm build # Build all packages pnpm test # Run all tests pnpm lint # Lint all packages pnpm security:check # Run security analysis pnpm audit # Check for vulnerable dependencies pnpm clean # Clean build artifacts ``` ### 包结构 ``` csrf-armor/ ├── packages/ │ ├── core/ # Framework-agnostic core │ └── nextjs/ # Next.js adapter ├── package.json # Root package └── pnpm-workspace.yaml ``` ## 🧪 测试你的实现 ### 快速安全检查 ``` // Test CSRF protection is working const testCsrf = async () => { // This should fail without proper CSRF token try { await fetch('/api/protected', { method: 'POST' }); } catch (error) { console.log('✅ CSRF protection is working'); } // This should succeed with proper token const response = await csrfFetch('/api/protected', { method: 'POST' }); console.log('✅ Legitimate requests work'); }; ``` ### 策略验证 ``` // Verify your strategy is correctly configured const config = { strategy: 'signed-double-submit', secret: process.env.CSRF_SECRET, }; // Check secret is set if (!config.secret) { throw new Error('❌ CSRF secret not properly configured!'); } console.log('✅ CSRF configuration looks good'); ``` ## 📄 许可证 MIT © [Muneeb Samuels](https://github.com/muneebs) ## 🔗 链接 - [📚 文档](https://github.com/muneebs/csrf-armor#readme) - [🐛 问题追踪](https://github.com/muneebs/csrf-armor/issues) - [📦 NPM 包](https://www.npmjs.com/search?q=%40csrf-armor) - [🔒 安全策略](./SECURITY.md)
标签:CISA项目, CSRF防护, Edge Computing, ESM, Express, GNU通用公共许可证, MITM代理, Node.js, npm包, TypeScript, Vite, Web Crypto API, Web安全, 中间件, 前端安全, 双提交Cookie, 同步令牌, 安全插件, 安全策略, 开源库, 提示词设计, 搜索引擎爬虫, 无框架依赖, 自动化攻击, 蓝队分析, 跨站请求伪造, 边缘计算, 零依赖