security-operations-deployment

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Security Operations & Deployment

安全运营与部署

When to Apply Each Middleware - Decision Guide

各中间件适用场景 - 决策指南

withRateLimit() - Apply to:

withRateLimit() - 适用于:

Always apply to:
  • Any route that could be abused (spam, brute force)
  • Login-like operations (even if Clerk handles auth)
  • Data creation/modification endpoints
  • Contact/support form endpoints
  • Webhooks (to prevent DoS)
  • File upload endpoints
  • Search endpoints
  • Data export endpoints
  • Any expensive AI/API operations
  • Report generation
  • Bulk operations
Usually not needed for:
  • Static asset requests (handled by CDN)
  • Simple GET endpoints that only read public data
  • Health check endpoints
  • Endpoints already protected by authentication rate limits
始终适用场景:
  • 所有可能被滥用的路由( spam、暴力破解)
  • 登录类操作(即便Clerk已经处理了鉴权)
  • 数据创建/修改接口
  • 联系/支持表单接口
  • Webhooks(防止DoS攻击)
  • 文件上传接口
  • 搜索接口
  • 数据导出接口
  • 所有资源消耗较高的AI/API操作
  • 报告生成功能
  • 批量操作
通常无需使用场景:
  • 静态资源请求(由CDN处理)
  • 仅读取公开数据的简单GET接口
  • 健康检查接口
  • 已经受鉴权限流保护的接口

withCsrf() - Apply to:

withCsrf() - 适用于:

Always apply to:
  • All POST/PUT/DELETE operations
  • Any state-changing operation
  • Form submissions
  • Account modifications
  • Payment operations
  • Data deletion operations
Skip for:
  • GET requests (read-only operations)
  • Public read-only endpoints
  • Webhooks (use signature verification instead)
始终适用场景:
  • 所有POST/PUT/DELETE操作
  • 所有会变更状态的操作
  • 表单提交
  • 账户信息修改
  • 支付操作
  • 数据删除操作
跳过使用场景:
  • GET请求(只读操作)
  • 公开只读接口
  • Webhooks(改用签名校验)

Combining Both Middlewares

组合使用两个中间件

For maximum protection:
typescript
// Order matters: rate limit first, then CSRF
export const POST = withRateLimit(withCsrf(handler));
Why order matters:
  1. Rate limiting runs first to block excessive requests early
  2. CSRF verification runs on requests that pass rate limiting
  3. More efficient: don't waste CSRF verification on rate-limited requests
Decision Matrix:
Route TypeRate LimitCSRFAuthentication
Public form submission✅ Yes✅ Yes❌ No
Protected data modification✅ Yes✅ Yes✅ Yes
Public read-only API❌ No❌ No❌ No
Protected read-only API✅ Maybe❌ No✅ Yes
Webhook endpoint✅ Yes❌ No✅ Signature
File upload✅ Yes✅ Yes✅ Yes

实现最高防护等级:
typescript
// 顺序很重要:先限流,再做CSRF校验
export const POST = withRateLimit(withCsrf(handler));
为什么顺序很重要:
  1. 先执行限流逻辑,尽早拦截过量请求
  2. 对通过限流的请求再执行CSRF校验
  3. 效率更高:不需要在已经被限流的请求上浪费CSRF校验资源
决策矩阵:
路由类型限流CSRF身份校验
公开表单提交✅ 是✅ 是❌ 否
受保护的数据修改✅ 是✅ 是✅ 是
公开只读API❌ 否❌ 否❌ 否
受保护的只读API✅ 可选❌ 否✅ 是
Webhook接口✅ 是❌ 否✅ 签名校验
文件上传✅ 是✅ 是✅ 是

Environment Variables & Secrets

环境变量与密钥

Required Environment Variables for This Project

本项目所需环境变量

Development (.env.local - NEVER commit):
bash
undefined
开发环境 (.env.local - 绝对不要提交到代码仓库)
bash
undefined

CSRF Protection

CSRF防护

Generate with: node -p "require('crypto').randomBytes(32).toString('base64url')"

生成命令:node -p "require('crypto').randomBytes(32).toString('base64url')"

CSRF_SECRET=<32-byte-base64url-string> SESSION_SECRET=<32-byte-base64url-string>
CSRF_SECRET=<32-byte-base64url-string> SESSION_SECRET=<32-byte-base64url-string>

Clerk Authentication (from Clerk dashboard)

Clerk身份校验(从Clerk控制台获取)

NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_... CLERK_SECRET_KEY=sk_test_... NEXT_PUBLIC_CLERK_FRONTEND_API_URL=https://your-app.clerk.accounts.dev
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_... CLERK_SECRET_KEY=sk_test_... NEXT_PUBLIC_CLERK_FRONTEND_API_URL=https://your-app.clerk.accounts.dev

Convex Database (from Convex dashboard)

Convex数据库(从Convex控制台获取)

CONVEX_DEPLOYMENT=dev:... NEXT_PUBLIC_CONVEX_URL=https://...convex.cloud
CONVEX_DEPLOYMENT=dev:... NEXT_PUBLIC_CONVEX_URL=https://...convex.cloud

Optional: Stripe (if using direct Stripe, not Clerk Billing)

可选:Stripe(如果你直接使用Stripe而非Clerk Billing)

STRIPE_SECRET_KEY=sk_test_... NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_... NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...

Optional: Clerk Webhook Secret

可选:Clerk Webhook密钥

CLERK_WEBHOOK_SECRET=whsec_...

**Production (Vercel/hosting platform):**

```bash
CLERK_WEBHOOK_SECRET=whsec_...

**生产环境 (Vercel/其他托管平台)**

```bash

CSRF Protection (different from dev!)

CSRF防护(和开发环境密钥不同!)

CSRF_SECRET=<different-32-byte-string> SESSION_SECRET=<different-32-byte-string>
CSRF_SECRET=<different-32-byte-string> SESSION_SECRET=<different-32-byte-string>

Clerk Production Keys

Clerk生产环境密钥

NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_live_... CLERK_SECRET_KEY=sk_live_... NEXT_PUBLIC_CLERK_FRONTEND_API_URL=https://your-app.clerk.accounts.com
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_live_... CLERK_SECRET_KEY=sk_live_... NEXT_PUBLIC_CLERK_FRONTEND_API_URL=https://your-app.clerk.accounts.com

Convex Production

Convex生产环境

CONVEX_DEPLOYMENT=prod:... NEXT_PUBLIC_CONVEX_URL=https://...convex.cloud
CONVEX_DEPLOYMENT=prod:... NEXT_PUBLIC_CONVEX_URL=https://...convex.cloud

Optional: Stripe Production

可选:Stripe生产环境

STRIPE_SECRET_KEY=sk_live_... NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_...
STRIPE_SECRET_KEY=sk_live_... NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_live_...

Optional: Clerk Webhook Secret (production)

可选:Clerk Webhook密钥(生产环境)

CLERK_WEBHOOK_SECRET=whsec_...
undefined
CLERK_WEBHOOK_SECRET=whsec_...
undefined

Generating Secrets

生成密钥

bash
undefined
bash
undefined

Generate CSRF_SECRET (32 bytes)

生成CSRF_SECRET(32字节)

node -p "require('crypto').randomBytes(32).toString('base64url')"
node -p "require('crypto').randomBytes(32).toString('base64url')"

Generate SESSION_SECRET (32 bytes)

生成SESSION_SECRET(32字节)

node -p "require('crypto').randomBytes(32).toString('base64url')"
undefined
node -p "require('crypto').randomBytes(32).toString('base64url')"
undefined

Environment Variable Best Practices

环境变量最佳实践

✅ DO:
  • Use different secrets for dev/staging/production
  • Generate strong random secrets (32+ bytes)
  • Add
    .env.local
    to
    .gitignore
  • Store production secrets in hosting platform's secret manager
  • Rotate secrets quarterly
  • Validate required environment variables on startup
❌ NEVER:
  • Hardcode API keys, tokens, or secrets in code
  • Commit
    .env.local
    to version control
  • Log environment variables
  • Expose secrets in client-side code
  • Use
    .env.local
    values in
    NEXT_PUBLIC_*
    variables (they're exposed to browser!)
  • Share secrets via email, Slack, or insecure channels
✅ 推荐做法:
  • 开发/预发/生产环境使用不同的密钥
  • 生成高强度随机密钥(32字节以上)
  • .env.local
    加入
    .gitignore
  • 将生产环境密钥存储在托管平台的密钥管理器中
  • 每季度轮换一次密钥
  • 项目启动时校验必填环境变量
❌ 绝对禁止:
  • 在代码中硬编码API密钥、令牌或密钥
  • .env.local
    提交到版本控制
  • 打印输出环境变量
  • 在客户端代码中暴露密钥
  • .env.local
    中的值用于
    NEXT_PUBLIC_*
    变量(这类变量会暴露给浏览器!)
  • 通过邮件、Slack或其他不安全渠道共享密钥

Validating Configuration on Startup

启动时校验配置

typescript
// lib/config.ts
const requiredEnvVars = [
  'CSRF_SECRET',
  'SESSION_SECRET',
  'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY',
  'CLERK_SECRET_KEY',
  'NEXT_PUBLIC_CONVEX_URL'
];

export function validateConfig() {
  const missing = requiredEnvVars.filter(v => !process.env[v]);

  if (missing.length > 0) {
    throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
  }

  // Validate secret lengths
  if (process.env.CSRF_SECRET && process.env.CSRF_SECRET.length < 32) {
    throw new Error('CSRF_SECRET must be at least 32 characters');
  }

  if (process.env.SESSION_SECRET && process.env.SESSION_SECRET.length < 32) {
    throw new Error('SESSION_SECRET must be at least 32 characters');
  }
}

// In your app startup (e.g., middleware.ts or layout.tsx)
validateConfig();

typescript
// lib/config.ts
const requiredEnvVars = [
  'CSRF_SECRET',
  'SESSION_SECRET',
  'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY',
  'CLERK_SECRET_KEY',
  'NEXT_PUBLIC_CONVEX_URL'
];

export function validateConfig() {
  const missing = requiredEnvVars.filter(v => !process.env[v]);

  if (missing.length > 0) {
    throw new Error(`缺失必填环境变量:${missing.join(', ')}`);
  }

  // 校验密钥长度
  if (process.env.CSRF_SECRET && process.env.CSRF_SECRET.length < 32) {
    throw new Error('CSRF_SECRET长度至少需要32个字符');
  }

  if (process.env.SESSION_SECRET && process.env.SESSION_SECRET.length < 32) {
    throw new Error('SESSION_SECRET长度至少需要32个字符');
  }
}

// 在应用启动时调用(例如middleware.ts或layout.tsx)
validateConfig();

Pre-Deployment Security Checklist

部署前安全检查清单

Run through this checklist before every production deployment:
每次生产环境部署前都要完整核对以下检查项:

Environment & Configuration

环境与配置

  • All environment variables set in production environment
  • CSRF_SECRET
    generated and configured (32+ bytes)
  • SESSION_SECRET
    generated and configured (32+ bytes)
  • Clerk production keys configured (
    pk_live_...
    ,
    sk_live_...
    )
  • Convex production deployment configured
  • Stripe live mode keys configured (if using direct Stripe)
  • .env.local
    NOT committed to git (check with
    git status
    )
  • Different secrets used for dev vs production
  • 生产环境所有环境变量已配置
  • 已生成并配置
    CSRF_SECRET
    (32字节以上)
  • 已生成并配置
    SESSION_SECRET
    (32字节以上)
  • 已配置Clerk生产环境密钥(
    pk_live_...
    sk_live_...
  • 已配置Convex生产环境部署
  • 已配置Stripe live模式密钥(如果直接使用Stripe)
  • .env.local
    未提交到git(用
    git status
    检查)
  • 开发和生产环境使用不同的密钥

Dependencies

依赖

  • Run
    npm audit --production
    - 0 vulnerabilities
  • Run
    npm outdated
    - Check for critical security updates
  • package-lock.json
    committed to git
  • Next.js on latest stable version (currently 15.5.4+)
  • All critical packages updated
  • 执行
    npm audit --production
    - 0个漏洞
  • 执行
    npm outdated
    - 检查关键安全更新
  • package-lock.json
    已提交到git
  • Next.js使用最新稳定版本(当前为15.5.4+)
  • 所有关键依赖包已更新

Security Features

安全功能

  • CSRF protection tested (see
    security-testing
    skill)
  • Rate limiting tested (
    node scripts/test-rate-limit.js
    )
  • Input validation tested with malicious input
  • Security headers verified (
    curl -I https://yourapp.com
    )
  • HSTS enabled in production (automatic in middleware)
  • Error messages are generic in production (no stack traces)
  • CSRF防护已测试(参考
    security-testing
    技能)
  • 限流功能已测试(
    node scripts/test-rate-limit.js
  • 已使用恶意输入测试输入校验逻辑
  • 已校验安全头(
    curl -I https://yourapp.com
  • 生产环境已启用HSTS(middleware中自动配置)
  • 生产环境错误信息为通用提示(无堆栈追踪信息)

Authentication & Authorization

身份与权限校验

  • Protected routes require authentication
  • Resource ownership checked before access
  • Subscription status verified for premium features
  • Webhook signatures verified (Clerk, Stripe)
  • Session expiration handled gracefully
  • No hardcoded credentials in code
  • 受保护路由需要身份校验
  • 访问资源前已校验资源所有权
  • 访问高级功能前已校验订阅状态
  • Webhook签名已校验(Clerk、Stripe)
  • 会话过期处理逻辑正常
  • 代码中无硬编码凭证

API Security

API安全

  • All POST/PUT/DELETE routes have CSRF protection
  • All public endpoints have rate limiting
  • All user input validated with Zod schemas
  • All errors handled with error handler utilities
  • No sensitive data in logs (passwords, tokens, cards, PII)
  • No hardcoded secrets in code (grep check below)
  • 所有POST/PUT/DELETE路由已添加CSRF防护
  • 所有公开接口已添加限流
  • 所有用户输入已通过Zod schema校验
  • 所有错误已通过错误处理工具统一处理
  • 日志中无敏感数据(密码、令牌、银行卡信息、个人可识别信息)
  • 代码中无硬编码密钥(可通过下方grep命令检查)

Payment Security (if applicable)

支付安全(如适用)

  • Using Clerk Billing + Stripe (not handling cards directly)
  • Webhooks verified with Svix signatures
  • Subscription status checked on server
  • Test mode disabled in production
  • No card data logged anywhere
  • 使用Clerk Billing + Stripe(不直接处理银行卡信息)
  • Webhook已通过Svix签名校验
  • 订阅状态在服务端校验
  • 生产环境已关闭测试模式
  • 任何地方都没有记录银行卡数据

Testing

测试

  • Rate limit test passes:
    node scripts/test-rate-limit.js
  • CSRF protection tested manually
  • Input validation tested with XSS payloads
  • Security headers checked:
    curl -I https://yourapp.com
  • Authentication flows tested
  • Error handling tested in production mode
  • 限流测试通过:
    node scripts/test-rate-limit.js
  • 已手动测试CSRF防护
  • 已使用XSS payload测试输入校验
  • 已检查安全头:
    curl -I https://yourapp.com
  • 已测试身份校验流程
  • 已在生产模式下测试错误处理逻辑

Final Checks

最终检查

bash
undefined
bash
undefined

Check for hardcoded secrets

检查硬编码的密钥

grep -r "sk_live" . --exclude-dir=node_modules grep -r "AKIA" . --exclude-dir=node_modules grep -r "api_key.*=" . --exclude-dir=node_modules
grep -r "sk_live" . --exclude-dir=node_modules grep -r "AKIA" . --exclude-dir=node_modules grep -r "api_key.*=" . --exclude-dir=node_modules

Verify .env.local not in git

确认.env.local未提交到git

git status | grep .env.local # Should return nothing
git status | grep .env.local # 应该无任何输出

Run full security audit

执行完整安全审计

npm audit --production bash scripts/security-check.sh
npm audit --production bash scripts/security-check.sh

Test production build

测试生产构建

npm run build NODE_ENV=production npm start

---
npm run build NODE_ENV=production npm start

---

Security Monitoring Post-Deployment

部署后安全监控

What to Monitor

需要监控的内容

Server Logs (Daily)

服务端日志(每日检查)

Monitor for these patterns that indicate potential attacks:
Rate Limit Violations (HTTP 429):
- Repeated 429 errors from same IP → potential abuse/brute force
- High volume of 429s → possible distributed attack
- 429s on login endpoints → credential stuffing attempt
CSRF Failures (HTTP 403):
- Repeated 403 with "CSRF token invalid" → potential CSRF attack
- Sudden spike in CSRF failures → possible automated attack
- 403s without prior token fetch → attack bypass attempt
Authentication Failures (HTTP 401/403):
- 401 spikes → potential brute force on protected endpoints
- 403 spikes → unauthorized access attempts
- Pattern of 401 followed by 403 → enumeration attack
Unusual Error Patterns:
- Sudden increase in 500 errors → potential attack or system issue
- 400 errors with validation failures → input attack attempts
- Errors from unusual geographic locations
监控以下可能代表攻击的模式:
限流触发(HTTP 429):
- 同一IP重复返回429错误 → 可能存在滥用/暴力破解行为
- 大量429错误 → 可能存在分布式攻击
- 登录接口返回429 → 可能存在凭证撞库攻击
CSRF校验失败(HTTP 403):
- 重复返回“CSRF token invalid”的403错误 → 可能存在CSRF攻击
- CSRF失败数量突增 → 可能存在自动化攻击
- 未先获取token就返回403 → 可能存在绕过攻击尝试
身份校验失败(HTTP 401/403):
- 401错误突增 → 可能存在对受保护接口的暴力破解
- 403错误突增 → 未授权访问尝试
- 先返回401再返回403的规律模式 → 枚举攻击
异常错误模式:
- 500错误突增 → 可能存在攻击或系统故障
- 校验失败返回400错误 → 输入攻击尝试
- 来自异常地理位置的错误

Metrics to Track (Weekly)

需要追踪的指标(每周检查)

Authentication Metrics:
  • Failed authentication attempts per hour
  • Account lockouts (if implemented)
  • Geographic distribution of login attempts
  • Unusual login times (3am mass logins = bot)
Rate Limiting Metrics:
  • Rate limit violations per IP
  • Top IPs hitting rate limits
  • Endpoints most frequently rate-limited
  • Rate limit violation trends over time
CSRF Protection Metrics:
  • CSRF validation failures
  • CSRF token generation rate
  • Token reuse attempts
  • Missing token attempts
Input Validation Metrics:
  • Validation failures by field
  • XSS attempt patterns (script tags in input)
  • SQL injection attempt patterns
  • Excessive input length attempts
Error Rate Metrics:
  • Error rates by endpoint
  • Error rates by HTTP status code
  • Error rate trends over time
  • Geographic distribution of errors
身份校验相关指标:
  • 每小时身份验证失败次数
  • 账户锁定次数(如有实现)
  • 登录尝试的地理位置分布
  • 异常登录时间(例如凌晨3点大量登录=机器人攻击)
限流相关指标:
  • 每个IP的限流触发次数
  • 触发限流最多的IP排名
  • 触发限流最频繁的接口
  • 限流触发量的时间趋势
CSRF防护相关指标:
  • CSRF校验失败次数
  • CSRF token生成速率
  • token复用尝试次数
  • 缺失token的请求次数
输入校验相关指标:
  • 各字段的校验失败次数
  • XSS尝试模式(输入中包含script标签)
  • SQL注入尝试模式
  • 输入长度超限尝试
错误率指标:
  • 各接口的错误率
  • 各HTTP状态码的错误率
  • 错误率的时间趋势
  • 错误的地理位置分布

Setting Up Monitoring

搭建监控

Vercel Logs (Built-in)

Vercel日志(内置)

bash
undefined
bash
undefined

View logs in Vercel dashboard

在Vercel控制台查看日志

Filter by status code

按状态码过滤

Status: 429 # Rate limited Status: 403 # CSRF/Forbidden Status: 401 # Unauthorized
undefined
Status: 429 # 限流触发 Status: 403 # CSRF/禁止访问 Status: 401 # 未授权
undefined

Clerk Dashboard (Authentication)

Clerk控制台(身份校验相关)

Monitor in Clerk dashboard:
  • Failed sign-in attempts
  • Account creation rate
  • Session activity
  • Suspicious IP addresses
在Clerk控制台监控以下内容:
  • 登录失败尝试
  • 账户创建速率
  • 会话活动
  • 可疑IP地址

Custom Logging

自定义日志

typescript
// lib/security-logger.ts
export function logSecurityEvent(event: {
  type: 'RATE_LIMIT' | 'CSRF_FAILURE' | 'AUTH_FAILURE' | 'VALIDATION_FAILURE';
  ip?: string;
  userId?: string;
  endpoint?: string;
  details?: Record<string, any>;
}) {
  const log = {
    timestamp: new Date().toISOString(),
    environment: process.env.NODE_ENV,
    ...event
  };

  // In production, send to logging service
  if (process.env.NODE_ENV === 'production') {
    console.log(JSON.stringify(log));
    // Optional: Send to external service (Datadog, LogRocket, etc.)
  } else {
    console.log('Security Event:', log);
  }
}

// Usage in middleware/routes
if (rateLimitExceeded) {
  logSecurityEvent({
    type: 'RATE_LIMIT',
    ip: clientIp,
    endpoint: request.nextUrl.pathname
  });
}
typescript
// lib/security-logger.ts
export function logSecurityEvent(event: {
  type: 'RATE_LIMIT' | 'CSRF_FAILURE' | 'AUTH_FAILURE' | 'VALIDATION_FAILURE';
  ip?: string;
  userId?: string;
  endpoint?: string;
  details?: Record<string, any>;
}) {
  const log = {
    timestamp: new Date().toISOString(),
    environment: process.env.NODE_ENV,
    ...event
  };

  // 生产环境下发送到日志服务
  if (process.env.NODE_ENV === 'production') {
    console.log(JSON.stringify(log));
    // 可选:发送到外部服务(Datadog、LogRocket等)
  } else {
    console.log('安全事件:', log);
  }
}

// 在middleware/路由中使用
if (rateLimitExceeded) {
  logSecurityEvent({
    type: 'RATE_LIMIT',
    ip: clientIp,
    endpoint: request.nextUrl.pathname
  });
}

Response Procedures

响应流程

High-Priority Alerts (Immediate Response):
  • Massive spike in failed authentication (>100/min)
  • CSRF failures from many IPs (coordinated attack)
  • Sudden 500 error rate increase (>10x normal)
  • Known vulnerability being exploited
Medium-Priority (24-hour Response):
  • Gradual increase in rate limit violations
  • Single IP with persistent failed auth attempts
  • New error patterns in logs
  • Unusual traffic from new geographic regions
Low-Priority (Weekly Review):
  • Normal background failed auth attempts
  • Occasional rate limit hits
  • Standard input validation failures
  • Routine error patterns
高优先级告警(立即响应):
  • 身份验证失败量突增(>100次/分钟)
  • 大量IP出现CSRF失败(协同攻击)
  • 500错误率突增(超过正常水平10倍)
  • 已知漏洞正在被利用
中优先级告警(24小时内响应):
  • 限流触发量逐步上升
  • 单个IP持续出现身份验证失败
  • 日志中出现新的错误模式
  • 来自新的异常地理位置的异常流量
低优先级告警(每周 review):
  • 正常的背景身份验证失败尝试
  • 偶发的限流触发
  • 常规的输入校验失败
  • 常规错误模式

Automated Alerting

自动告警

Set up alerts in your hosting platform:
Vercel:
Alerts → New Alert Rule
- Error rate > 10% for 5 minutes → Email/Slack
- 429 responses > 100/min → Email/Slack
- 500 responses > 50/min → Email/Slack
Custom Alerts:
typescript
// Monitor and alert on patterns
if (rateLimitViolations > THRESHOLD) {
  await sendAlert({
    severity: 'HIGH',
    message: `Rate limit violations: ${rateLimitViolations}/min`,
    ip: attackerIp
  });
}

在你的托管平台配置告警:
Vercel:
告警 → 新建告警规则
- 5分钟内错误率>10% → 邮件/Slack通知
- 429响应>100次/分钟 → 邮件/Slack通知
- 500响应>50次/分钟 → 邮件/Slack通知
自定义告警:
typescript
// 监控模式并触发告警
if (rateLimitViolations > THRESHOLD) {
  await sendAlert({
    severity: 'HIGH',
    message: `限流触发量:${rateLimitViolations}/分钟`,
    ip: attackerIp
  });
}

Resources & Documentation

资源与文档

Project Security Documentation

项目安全文档

Implementation Guides:
  • .claude/skills/security/security-overview/SKILL.md
    - Overall architecture
  • .claude/skills/security/*/SKILL.md
    - Individual security features
  • docs/security/SECURITY_IMPLEMENTATION.md
    - Complete implementation guide
  • README.md
    - Security Configuration section
Awareness & Learning:
  • .claude/skills/security/security-awareness/
    - AI code vulnerability analysis
  • .claude/skills/security/security-awareness/awareness-overview/
    - Complete security overview
实现指南:
  • .claude/skills/security/security-overview/SKILL.md
    - 整体架构
  • .claude/skills/security/*/SKILL.md
    - 各安全功能实现说明
  • docs/security/SECURITY_IMPLEMENTATION.md
    - 完整实现指南
  • README.md
    - 安全配置章节
安全意识与学习:
  • .claude/skills/security/security-awareness/
    - AI代码漏洞分析
  • .claude/skills/security/security-awareness/awareness-overview/
    - 完整安全概览

Testing & Verification Scripts

测试与校验脚本

Security Testing:
  • scripts/test-rate-limit.js
    - Rate limiting verification
  • scripts/security-check.sh
    - Dependency audit
  • scripts/security-test.sh
    - Comprehensive security test suite (if created)
Example Implementations:
  • app/api/example-protected/route.ts
    - Complete security stack example
  • app/api/test-rate-limit/route.ts
    - Rate limiting test endpoint
  • app/api/csrf/route.ts
    - CSRF token generation
安全测试:
  • scripts/test-rate-limit.js
    - 限流功能校验
  • scripts/security-check.sh
    - 依赖审计
  • scripts/security-test.sh
    - 完整安全测试套件(如有创建)
实现示例:
  • app/api/example-protected/route.ts
    - 完整安全栈实现示例
  • app/api/test-rate-limit/route.ts
    - 限流测试接口
  • app/api/csrf/route.ts
    - CSRF token生成接口

External Security Resources

外部安全资源

OWASP (Security Standards):
Framework & Service Docs:
Testing Tools:

OWASP(安全标准):
框架与服务文档:
测试工具:

Maintenance Schedule

维护计划

Daily

每日

  • Check error logs in Vercel dashboard
  • Monitor Clerk dashboard for failed auth attempts
  • Review any security alerts
  • 查看Vercel控制台的错误日志
  • 监控Clerk控制台的登录失败尝试
  • 处理所有安全告警

Weekly

每周

  • Run
    npm audit --production
  • Check GitHub Dependabot alerts
  • Review error logs for patterns
  • Check rate limit violation trends
  • 执行
    npm audit --production
  • 查看GitHub Dependabot告警
  • 分析错误日志的规律模式
  • 查看限流触发量趋势

Monthly

每月

  • Full security audit:
    bash scripts/security-check.sh
  • Update dependencies:
    npm update
    + test
  • Review and rotate any compromised secrets
  • Re-run security testing suite
  • Check security headers: https://securityheaders.com/
  • 完整安全审计:
    bash scripts/security-check.sh
  • 更新依赖:
    npm update
    + 测试
  • 轮换所有泄露的密钥
  • 重新运行安全测试套件
  • 检查安全头:https://securityheaders.com/

Quarterly

每季度

  • Rotate CSRF_SECRET and SESSION_SECRET
  • Major framework updates (Next.js, React)
  • Full penetration test (manual XSS, CSRF, auth bypass attempts)
  • Review and update security policies
  • Security awareness training (review skills)

  • 轮换CSRF_SECRET和SESSION_SECRET
  • 框架大版本更新(Next.js、React)
  • 完整渗透测试(手动测试XSS、CSRF、鉴权绕过等)
  • review并更新安全策略
  • 安全意识培训(review相关技能)

Quick Reference Commands

快速参考命令

bash
undefined
bash
undefined

Generate secrets

生成密钥

node -p "require('crypto').randomBytes(32).toString('base64url')"
node -p "require('crypto').randomBytes(32).toString('base64url')"

Check for vulnerabilities

检查漏洞

npm audit --production
npm audit --production

Check for outdated packages

检查过期依赖包

npm outdated
npm outdated

Run security test suite

运行安全测试套件

node scripts/test-rate-limit.js bash scripts/security-check.sh
node scripts/test-rate-limit.js bash scripts/security-check.sh

Check for hardcoded secrets

检查硬编码密钥

grep -r "sk_live" . --exclude-dir=node_modules grep -r "AKIA" . --exclude-dir=node_modules
grep -r "sk_live" . --exclude-dir=node_modules grep -r "AKIA" . --exclude-dir=node_modules

Test security headers

测试安全头

Verify .env.local not committed

确认.env.local未提交

git status | grep .env.local
git status | grep .env.local

Production build test

生产构建测试

npm run build NODE_ENV=production npm start

---
npm run build NODE_ENV=production npm start

---

Summary: Security Operations Principles

总结:安全运营原则

🔒 Before Deployment:
  • Checklist must be 100% complete
  • 0 npm audit vulnerabilities
  • All tests passing
  • All environment variables configured
🔒 After Deployment:
  • Monitor logs daily
  • Respond to alerts immediately
  • Review metrics weekly
  • Update dependencies monthly
🔒 Continuous:
  • Security is never "done"
  • Stay updated on new vulnerabilities
  • Keep dependencies current
  • Test security features regularly
For implementation details, refer to individual security skills. For vulnerability awareness, refer to security-awareness skills.
🔒 部署前:
  • 检查清单必须100%完成
  • npm audit无任何漏洞
  • 所有测试通过
  • 所有环境变量已配置
🔒 部署后:
  • 每日监控日志
  • 立即响应告警
  • 每周review指标
  • 每月更新依赖
🔒 持续:
  • 安全永远没有“完成”的状态
  • 及时跟进新的漏洞信息
  • 保持依赖为最新版本
  • 定期测试安全功能
实现细节请参考各安全技能文档。 漏洞意识相关内容请参考安全意识技能文档。