munesoft/securex
GitHub: munesoft/securex
一个开箱即用的 Node.js 安全中间件,通过一行代码集成智能安全头、自动 CSP 生成、速率限制、爬虫检测、CSRF 防护等全面的安全防护能力。
Stars: 0 | Forks: 0
# @munesoft/securex
[](https://npmjs.com/package/@munesoft/securex)
[](https://opensource.org/licenses/MIT)
[](https://github.com/munesoft/securex)
```
import securex from "@munesoft/securex";
app.use(securex());
```
## 📋 目录
- [securex 是什么?](#what-is-securex)
- [为什么不使用现有工具?](#why-not-existing-tools)
- [功能特性](#features)
- [快速开始](#quick-start)
- [示例](#examples)
- [高级用法](#advanced-usage)
- [安全概念](#security-concepts)
- [CLI](#cli)
- [框架支持](#framework-support)
- [对比](#comparison)
- [API 参考](#api-reference)
- [插件系统](#plugin-system)
- [常见问题](#faq)
## securex 是什么?
**securex** 是一个下一代 Node.js 安全中间件,其功能远超传统的设置请求头工具。它专为希望默认获得强大安全性、且无需编写样板代码的开发者而设计。
与那些需要手动配置数十个选项的工具不同,securex:
- 根据您的环境(`development`、`production`、`testing`)进行**自动配置**
- **分析**您的 HTML 以自动生成精准的 Content-Security-Policy 规则
- 实时**检测**爬虫、异常情况和攻击模式
- 以可操作的、内联的开发模式洞察来**指导**您
- 通过 CLI 为您的安全配置**打分**
securex 的设计目标是成为**每个新 Node.js 项目的默认安全层**。
## 为什么不使用现有工具?
| 问题 | 传统工具 | securex |
|---|---|---|
| 设置时间 | 数小时配置 | 一行代码 |
| CSP 生成 | 手动配置,容易出错 | 从 HTML 自动检测 |
| 环境感知 | 针对每个环境手动配置 | 内置自动模式 |
| 开发反馈 | 静默无提示 | 内联警告 + 建议 |
| 爬虫检测 | 不包含 | 内置 |
| 异常检测 | 不包含 | 内置 |
| 安全评分 | 需要外部工具 | `npx securex analyze` |
| 速率限制 | 需要单独的包 | 内置 |
| CSRF 防护 | 需要单独的包 | 内置 |
| 插件系统 | 有限 | 可扩展 |
## 功能特性
### 🔒 智能安全请求头
自动设置所有现代 HTTP 安全请求头:
- `Content-Security-Policy`(动态或自动生成)
- `Strict-Transport-Security`(仅限生产环境)
- `X-Frame-Options`
- `Referrer-Policy`
- `X-Content-Type-Options`
- `Permissions-Policy`
- `Cross-Origin-Opener-Policy`
- `Cross-Origin-Resource-Policy`
- `Cross-Origin-Embedder-Policy`
### 🧠 类 AI CSP 生成器
杀手级功能。传入 `csp: "auto"`,securex 将分析您发出的 HTML,检测外部脚本、样式表和图像,并自动构建 Content-Security-Policy 规则——随着应用的发展动态更新它们。
### 🌍 环境感知模式
- **Development (开发)** → 宽松规则 + 内联开发者警告
- **Production (生产)** → 严格强制执行,启用 HSTS
- **Testing (测试)** → 静默模式,无输出
### ⚡ 内置速率限制
基于 IP 的速率限制,带有自适应节流和突发保护——无需额外的包。
### 🤖 爬虫与异常检测
检测并阻止已知的安全扫描器(sqlmap、nikto、nmap 等)、路径遍历尝试、SQL 注入探测和 XSS 模式。
### 🛡️ CSRF 防护
基于 Token 的 CSRF 防护,具有自动生成 Cookie 以及请求头/请求体验证功能。
### 🧹 输入净化
对请求体和查询参数进行自动的 XSS 净化处理。
### 📊 安全评分引擎
运行 `npx securex analyze` 以获得直观的安全评分,并为您的配置提供可操作的建议。
### 🔌 插件系统
使用自定义插件扩展 securex 以获取额外功能。
## 快速开始
### 安装
```
npm install @munesoft/securex
```
### 一行设置 (Express)
```
import express from "express";
import securex from "@munesoft/securex";
const app = express();
app.use(securex());
```
就是这样。您现在拥有了:
- 设置的所有安全请求头
- 环境感知默认值
- 控制台中的开发模式洞察
## 示例
### 基本用法
```
import securex from "@munesoft/securex";
// Zero config — auto-detects environment
app.use(securex());
```
### CSP 自动模式
```
app.use(securex({
csp: "auto",
}));
```
securex 拦截发出的 HTML 响应,扫描外部脚本、样式和图像,并自动生成您的 CSP。在开发模式下,它会记录:
```
[securex] ⚠️ External script detected: https://cdn.jsdelivr.net
👉 Add 'https://cdn.jsdelivr.net' to your CSP script-src allowlist
[securex] ⚠️ Inline script detected
👉 Use nonces or hashes in CSP to allow inline scripts safely
```
### 速率限制
```
app.use(securex({
rateLimit: {
windowMs: 60_000, // 1 minute
max: 100, // max 100 requests per IP
burst: 20, // allow 20-request burst
},
}));
```
### CORS 自动配置
```
// Development: auto-learn and warn about new origins
app.use(securex({ cors: "auto" }));
// Production: explicit allowlist
app.use(securex({
cors: {
origins: ["https://app.example.com", "https://admin.example.com"],
credentials: true,
},
}));
```
### 生产环境设置
```
app.use(securex({
mode: "production",
strict: true,
headers: true,
csp: {
directives: {
"default-src": ["'self'"],
"script-src": ["'self'", "https://cdn.example.com"],
"style-src": ["'self'", "https://fonts.googleapis.com"],
},
},
cors: {
origins: ["https://yourapp.com"],
credentials: true,
},
rateLimit: {
windowMs: 60_000,
max: 200,
},
csrf: true,
sanitize: true,
botDetection: true,
anomalyDetection: true,
logging: {
level: "warn",
format: "json",
onEvent: (event) => myLogger.log(event),
},
}));
```
### CSRF 防护
```
app.use(cookieParser()); // required for CSRF cookie reading
app.use(securex({ csrf: true }));
// In your HTML form:
//
// Or in your API client:
// headers: { "x-csrf-token": token }
```
### 完整功能示例
```
app.use(securex({
mode: "auto", // auto-detect environment
strict: false,
silent: false,
headers: true,
csp: "auto",
cors: "auto",
rateLimit: true,
csrf: true,
sanitize: true,
botDetection: true,
anomalyDetection: true,
logging: true,
plugins: [
// require("securex-bot-shield"),
],
}));
```
## 高级用法
### 严格模式
最大程度的安全强制执行。启用带 preload 的 HSTS、DENY 嵌入、严格的 CSP 默认值以及所有检测功能。
```
app.use(securex({ strict: true }));
```
### 静默模式 (CI/CD)
```
app.use(securex({ silent: true }));
```
### 自定义安全请求头
```
app.use(securex({
headers: {
"X-Custom-Security": "enabled",
"Server": false, // remove header
},
}));
```
### 自定义速率限制键
通过 API 密钥而不是 IP 进行速率限制:
```
app.use(securex({
rateLimit: {
max: 1000,
keyGenerator: (req) => req.headers["x-api-key"] ?? req.ip,
},
}));
```
### 日志与监控
```
app.use(securex({
logging: {
level: "warn",
format: "json",
onEvent: (event) => {
// event: { type, timestamp, ip, path, userAgent, detail, severity }
if (event.severity === "critical") {
pagerDuty.trigger(event);
}
datadog.metric("security_event", { type: event.type });
},
},
}));
```
### 信任代理
```
app.use(securex({
trustProxy: true, // use X-Forwarded-For for IP detection
rateLimit: true,
}));
```
## 安全概念
### 内容安全策略 (CSP)
CSP 是一个 HTTP 请求头,它告诉浏览器哪些脚本、样式、图像和其他内容来源是可信的。配置良好的 CSP 是防御 XSS 攻击的最强手段之一。
securex 的 `csp: "auto"` 模式会分析您实际的 HTML 响应以构建精准的 CSP 规则,消除了繁琐的猜测工作。
### HTTP 严格传输安全 (HSTS)
告诉浏览器始终为您的域使用 HTTPS。securex 会在生产环境中自动启用此功能,并将 max-age 设置为 1 年。在严格模式下,它会添加 `preload` 以符合 HSTS 预加载列表的条件。
### CSRF 防护
跨站请求伪造攻击会诱骗已认证的用户提交恶意请求。securex 会为每个会话生成一个加密随机的 Token,并在所有改变状态的请求上对其进行验证。
### 速率限制
防止暴力破解、撞库、数据抓取和 DoS 攻击。securex 使用支持突发流量的内存滑动窗口机制。
### 异常检测
securex 监控请求模式以发现路径遍历、SQL 注入探测、XSS 尝试以及其他常见的攻击签名,并视情况进行阻止或告警。
## CLI
```
# 分析你的 securex 配置并获取安全评分
npx securex analyze
# 使用特定配置文件进行分析
npx securex analyze --config ./myconfig.js
# 输出为 JSON (用于 CI pipelines)
npx securex analyze --json
# 检查实时 URL 的 HTTP headers
npx securex check-headers --url https://yourapp.com
# 生成初始配置文件
npx securex init
```
### 示例输出
```
╔════════════════════════════════════╗
║ @munesoft/securex — Score Report ║
╚════════════════════════════════════╝
Overall Score: 87/100 ██████████████████████████░░░░
✔ Security Headers 20/20
✔ CSP 20/20
✔ CORS 15/15
✔ Rate Limiting 15/15
✖ CSRF Protection 0/10
→ CSRF protection disabled
✔ Input Sanitization 10/10
⚠ Threat Detection 7/10
→ Bot detection not enabled
Recommendations:
💡 Enable CSRF: securex({ csrf: true })
💡 Enable: securex({ botDetection: true, anomalyDetection: true })
```
## 框架支持
### Express
```
import express from "express";
import securex from "@munesoft/securex";
const app = express();
app.use(express.json());
app.use(securex());
```
### Fastify
```
import Fastify from "fastify";
import securex from "@munesoft/securex";
const fastify = Fastify();
fastify.addHook("onRequest", (request, reply, done) => {
securex()(request.raw, reply.raw, done);
});
```
### Next.js (API 路由)
```
// middleware.ts
import { NextResponse } from "next/server";
import securex from "@munesoft/securex";
export function middleware(request) {
const response = NextResponse.next();
// Apply headers manually or use the score engine for config guidance
return response;
}
```
或者包装单个 API 路由:
```
// pages/api/[...].ts
import securex from "@munesoft/securex";
import { createServer } from "http";
const security = securex({ silent: true, headers: true, rateLimit: true });
export default function handler(req, res) {
security(req, res, () => {
// your handler logic
});
}
```
## 对比
| 特性 | securex | helmet | cors | express-rate-limit | csurf |
|---|:---:|:---:|:---:|:---:|:---:|
| 安全请求头 | ✅ | ✅ | ❌ | ❌ | ❌ |
| 自动 CSP 生成 | ✅ | ❌ | ❌ | ❌ | ❌ |
| 环境感知 | ✅ | ❌ | ❌ | ❌ | ❌ |
| 开发模式洞察 | ✅ | ❌ | ❌ | ❌ | ❌ |
| 速率限制 | ✅ | ❌ | ❌ | ✅ | ❌ |
| 爬虫检测 | ✅ | ❌ | ❌ | ❌ | ❌ |
| 异常检测 | ✅ | ❌ | ❌ | ❌ | ❌ |
| CSRF 防护 | ✅ | ❌ | ❌ | ❌ | ✅ |
| 输入净化 | ✅ | ❌ | ❌ | ❌ | ❌ |
| CORS 处理 | ✅ | ❌ | ✅ | ❌ | ❌ |
| 安全评分 CLI | ✅ | ❌ | ❌ | ❌ | ❌ |
| 插件系统 | ✅ | ❌ | ❌ | ❌ | ❌ |
| 零配置 | ✅ | ❌ | ❌ | ❌ | ❌ |
| 所需包数量 | **1** | 1+ | +1 | +1 | +1 |
## API 参考
### `securex(options?)`
返回一个兼容 Express 的中间件函数。
#### 选项
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| `mode` | `"auto" \| "development" \| "production" \| "testing"` | `"auto"` | 安全模式。自动检测 `NODE_ENV`。 |
| `strict` | `boolean` | `false` | 最高安全性:DENY 嵌入,preload HSTS,严格 CSP。 |
| `silent` | `boolean` | `false` | 禁止所有控制台输出。 |
| `headers` | `boolean \| object` | `true` | 安全请求头。传入一个对象以覆盖特定的请求头。 |
| `csp` | `boolean \| "auto" \| CspOptions` | `undefined` | CSP 配置。`"auto"` = HTML 分析模式。 |
| `cors` | `boolean \| "auto" \| CorsOptions` | `undefined` | CORS 配置。 |
| `rateLimit` | `boolean \| RateLimitOptions` | `undefined` | 速率限制。 |
| `csrf` | `boolean \| CsrfOptions` | `undefined` | CSRF 防护。 |
| `sanitize` | `boolean` | `undefined` | 输入净化(请求体 + 查询参数)。 |
| `botDetection` | `boolean` | `undefined` | 阻止已知的扫描器 User-Agent。 |
| `anomalyDetection` | `boolean` | `undefined` | 阻止可疑的请求模式。 |
| `logging` | `boolean \| LoggingOptions` | `undefined` | 安全事件日志记录。 |
| `plugins` | `SecurexPlugin[]` | `[]` | 插件列表。 |
| `trustProxy` | `boolean` | `false` | 信任 `X-Forwarded-For` 用于 IP 检测。 |
## 插件系统
插件允许您使用自定义中间件扩展 securex,并无缝集成到安全管道中。
### 创建插件
```
// securex-my-plugin/index.js
module.exports = {
name: "my-plugin",
version: "1.0.0",
install(options) {
return function(req, res, next) {
// your logic here
next();
};
},
};
```
### 使用插件
```
app.use(securex({
plugins: [
require("securex-my-plugin"),
require("securex-bot-shield"),
],
}));
```
## 常见问题
**问:securex 可以与 TypeScript 一起使用吗?**
答:可以——它是用 TypeScript 编写的,并附带了完整的类型定义。
**问:它会破坏我现有的 Express 中间件吗?**
答:不会。securex 是完全非破坏性的。它只会添加请求头并可能阻止恶意请求,不会干扰正常的请求处理。
**问:`csp: "auto"` 与手动配置 CSP 有何不同?**
答:在自动模式下,securex 会拦截发出的 HTML 响应并扫描其中的外部脚本、样式表和图像,然后动态构建 CSP 请求头。这意味着您永远不会遗漏任何资源——您的 CSP 会自动与您实际的 HTML 保持同步。
**问:我可以在没有 Express 的情况下使用 securex 吗?**
答:securex 返回一个标准的 `(req, res, next)` 中间件,与任何 Node.js HTTP 框架兼容。
**问:速率限制会在服务器重启后持续存在吗?**
答:内置的速率限制器使用内存存储,并在重启后重置。对于分布式系统中的持久化速率限制,请实现一个由 Redis 支持的自定义 `keyGenerator`。
**问:securex 可以在生产环境中使用吗?**
答:可以。设置 `mode: "production"`(或使用 `NODE_ENV=production`)以启用全面强制执行,包括 HSTS、严格的 CORS 以及所有检测功能。
**问:如何禁用特定的请求头?**
答:在 headers 对象中将其设为 `false`:
```
securex({ headers: { "X-Frame-Options": false } })
```
## 许可证
MIT © [munesoft](https://github.com/munesoft)
## 关键词
node.js security, express security middleware, HTTP security headers, CSP generator, API protection, web security, CSRF protection, XSS prevention, rate limiting, bot detection, anomaly detection, HSTS, CORS, helmet alternative
标签:CISA项目, CSP, GNU通用公共许可证, HTTP安全头, MITM代理, Node.js, NPM包, OSV-Scalibr, SEO, Web安全, XSS防护, 中间件, 内容安全策略, 安全中间件, 安全标准, 开发框架, 异常检测, 暗色界面, 机器人检测, 爬虫拦截, 网络安全, 网络调试, 自动化, 自动化攻击, 自动配置, 蓝队分析, 规则仓库, 请求头, 隐私保护, 零配置