mcpField
S
security-architecture-overview

security-architecture-overview

github.com/harperaa安全19199 次安装45 周前更新
代码仓库

关于 security-architecture-overview

security-architecture-overview 是面向 Secure Vibe Coding OS SaaS 起步模板的安全指南,该模板基于 Next.js。它介绍分层防护,并为开发者实现和审查应用安全提供模式与清单。

主要功能

  1. 01讲解五层安全架构
  2. 02涵盖 CSRF、速率限制和验证
  3. 03提供受保护 API 路由模式
  4. 04说明开发与生产环境控制
  5. 05附带安全实施清单

适用场景

  1. 01规划新 API 路由的防护
  2. 02审查身份验证与授权模式
  3. 03部署前核对安全控制

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/harperaa/secure-claude-skills --skill security-architecture-overview

安装后在 Claude Code 中输入/security-architecture-overview确认已加载。

详细介绍

安全架构概览

项目安全概况

项目: Secure Vibe Coding OS 版本: 1.0 Next.js 版本: 15.5.4 安全审计状态: 0 个漏洞 OWASP 评分: 90/100(Next.js 应用中排名前 10%)

项目简介

Secure Vibe Coding OS 是一个可用于生产环境的 SaaS 起始模板,将安全性作为首要考量,而非事后补充。与仅提供基础身份验证、让你自行摸索其余安全措施的典型 Next.js 起始模板不同,本模板从第一天起就内置了企业级安全控制。

采用此架构的原因

根据 Veracode 的《2024 年软件安全现状报告》,AI 生成的代码有 45% 的概率会采用不安全模式。标准 SaaS 起始模板提供的安全指导又非常有限,使这一问题雪上加霜。开发者随后会提示 AI 在不安全的基础上构建功能,而每个新功能都可能成为漏洞。

此架构通过提供以下内容打破这一循环:

  • 纵深防御(多层防护)
  • 默认安全模式(可选择放宽安全限制)
  • 适合 AI 使用的安全工具(易于正确使用)
  • 90/100 的 OWASP 基线评分(应用中排名前 10%)

核心安全原则

1. 纵深防御

每个请求都会经过多层安全防护。如果其中一层失效,其他层会拦截攻击。

2. 故障时确保安全

发生错误时,系统默认拒绝访问。显示错误也好过授予未经授权的访问权限。

3. 最小权限

用户和系统仅获得所需的最低访问权限。身份验证确认身份;授权则限制其可执行的操作。

4. 安全是实际落实的,而非想当然

我们不会假设用户会“安全地使用它”。安全性已融入每个工具、中间件和模式中。

5 层安全防护栈

每个请求在到达业务逻辑之前,都会经过以下各层:

User Browser
     │
     ▼
┌─────────────────────────────────────────────┐
│ Layer 0: Middleware (Security Headers)     │
│ • X-Frame-Options: DENY                     │
│ • Content-Security-Policy                   │
│ • HSTS (production only)                    │
│ • X-Content-Type-Options: nosniff           │
└──────────────┬──────────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────────┐
│ Layer 1: Rate Limiting                      │
│ • 5 requests per minute per IP              │
│ • Returns HTTP 429 when exceeded            │
│ • Prevents brute force & resource abuse     │
└──────────────┬──────────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────────┐
│ Layer 2: CSRF Protection                    │
│ • HMAC-SHA256 cryptographic signing         │
│ • Single-use tokens                         │
│ • Returns HTTP 403 if invalid               │
└──────────────┬──────────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────────┐
│ Layer 3: Input Validation                   │
│ • Zod schema validation                     │
│ • Automatic XSS sanitization                │
│ • Type-safe data transformation             │
│ • Returns HTTP 400 if invalid               │
└──────────────┬──────────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────────┐
│ Layer 4: Business Logic                     │
│ • Your handler code runs here               │
│ • Receives validated, sanitized data        │
│ • Clerk authentication checked in middleware│
└──────────────┬──────────────────────────────┘
               │
               ▼
┌─────────────────────────────────────────────┐
│ Layer 5: Secure Error Handling              │
│ • Generic messages in production            │
│ • Detailed errors in development            │
│ • No information leakage                    │
└─────────────────────────────────────────────┘

实现的效果: 攻击者必须同时绕过全部 5 层才能攻破系统——以当前的攻击技术而言,这实际上不可能。

各安全技能的适用场景

API 路由保护:
  • csrf-protection skill:创建会更改状态的 POST/PUT/DELETE 端点时
  • rate-limiting skill:保护端点免受滥用时(表单、开销较大的操作)
  • input-validation skill:接受任何用户输入时(务必使用!)
应用安全:
  • security-headers skill:配置中间件或需要了解 CSP/HSTS 时
  • error-handling skill:在 API 路由中实现错误响应时
  • auth-security skill:使用 Clerk 实现身份验证/授权时
集成:
  • payment-security skill:通过 Clerk Billing 实现 Stripe 支付时
  • dependency-security skill:添加程序包或运行安全审计时
验证:
  • security-testing skill:测试安全功能或执行部署前检查清单时

架构决策依据

为什么采用分层安全?

单点故障问题: 传统 Web 应用通常依赖单一安全措施。如果该控制措施失效或被绕过,整个系统就会遭到攻破。

现实案例: 2020 年的 SolarWinds 攻击利用了一个遭到攻破的构建服务器。攻击者一旦绕过这项控制措施,就能访问数千家组织。采用纵深防御的方法,本可以在其他多个层级发现入侵。

我们的方法: 如同拥有护城河、城墙、塔楼和内城堡的中世纪城堡,攻击者必须攻破每一层防御。每一层都能拦截不同类型的攻击:

  • **中间件:**在请求到达应用代码之前将其拦截
  • **速率限制:**拦截自动化攻击
  • **CSRF:**拦截跨源攻击
  • **验证:**拦截注入攻击
  • **身份验证/授权:**阻止未经授权的访问

完整安全栈模式

以下是完全安全的 API 路由示例:

// app/api/contact/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { withRateLimit } from '@/lib/withRateLimit';
import { withCsrf } from '@/lib/withCsrf';
import { validateRequest } from '@/lib/validateRequest';
import { contactFormSchema } from '@/lib/validation';
import { handleApiError } from '@/lib/errorHandler';

async function contactHandler(request: NextRequest) {
  try {
    const body = await request.json();

    // Layer 3: Input validation
    const validation = validateRequest(contactFormSchema, body);
    if (!validation.success) {
      return validation.response;
    }

    const { name, email, subject, message } = validation.data;

    // Safe to process - all security layers passed
    await sendEmail({ to: '[email protected]', from: email, subject, message });

    return NextResponse.json({ success: true });

  } catch (error) {
    // Layer 5: Secure error handling
    return handleApiError(error, 'contact-form');
  }
}

// Layers 1-2: Apply security middlewares
export const POST = withRateLimit(withCsrf(contactHandler));

export const config = {
  runtime: 'nodejs', // Required for crypto operations
};

特定环境的安全性

开发环境(宽松)
  • ✅ 详细的错误消息(完整堆栈跟踪)
  • ✅ 详细日志记录
  • ✅ 允许使用 HTTP(localhost)
  • ✅ 开发密钥
生产环境(最高级别的保护)
  • ✅ 仅显示通用错误消息
  • ✅ 最少日志记录(不记录 PII)
  • ✅ 强制使用 HTTPS(HSTS)
  • ✅ 生产密钥

自动检测: 代码会检测 process.env.NODE_ENV === 'production',并自动调整安全防护级别。

技术栈安全组件

身份验证:Clerk
  • 通过 SOC 2 认证
  • 负责密码哈希、会话、MFA 和 OAuth
  • 与自定义实现相比,身份验证漏洞减少 73%
  • 技能: auth-security
付款:Clerk Billing + Stripe
  • 绝不接触银行卡数据
  • 符合 PCI-DSS(通过 Stripe)
  • Webhook 签名验证
  • 技能: payment-security
数据库:Convex
  • 类型安全的查询
  • 通过 ctx.auth.userId 限定用户数据范围
  • 在 mutations 中进行额外验证
框架:Next.js 15.5.4
  • 最新的安全补丁
  • 使用中间件实施全局安全控制
  • App Router 可提供更完善的安全边界

快速参考:安全检查清单

创建新的 API 路由时,请确保:

  • 如果路由可能被滥用,则应用 withRateLimit()
  • 对 POST/PUT/DELETE 请求应用 withCsrf()
  • 使用 lib/validation.ts 中的 Zod 架构验证输入
  • 在 catch 块中使用 handleApiError()
  • 使用 Clerk 的 await auth() 检查身份验证
  • 访问特定用户资源时检查授权
  • 使用适当的 HTTP 状态码(200、400、401、403、404、429、500)
  • 不记录敏感数据(密码、令牌、PII)
  • 在配置中设置 runtime: 'nodejs',用于加密操作
  • 提交前测试端点

常见模式 - 复制粘贴模板

模板 1:简单的受保护端点(无 CSRF)
import { NextRequest, NextResponse } from 'next/server';
import { withRateLimit } from '@/lib/withRateLimit';
import { handleApiError, handleUnauthorizedError } from '@/lib/errorHandler';
import { auth } from '@clerk/nextjs/server';

async function handler(request: NextRequest) {
  try {
    const { userId } = await auth();
    if (!userId) return handleUnauthorizedError();

    // Your logic here

    return NextResponse.json({ success: true });
  } catch (error) {
    return handleApiError(error, 'route-name');
  }
}

export const GET = withRateLimit(handler);
export const config = { runtime: 'nodejs' };
模板 2:启用完整保护的表单提交
import { NextRequest, NextResponse } from 'next/server';
import { withRateLimit } from '@/lib/withRateLimit';
import { withCsrf } from '@/lib/withCsrf';
import { validateRequest } from '@/lib/validateRequest';
import { handleApiError, handleUnauthorizedError } from '@/lib/errorHandler';
import { contactFormSchema } from '@/lib/validation';
import { auth } from '@clerk/nextjs/server';

async function handler(request: NextRequest) {
  try {
    const { userId } = await auth();
    if (!userId) return handleUnauthorizedError();

    const body = await request.json();
    const validation = validateRequest(contactFormSchema, body);

    if (!validation.success) {
      return validation.response;
    }

    const { name, email, subject, message } = validation.data;

    // Process form (send email, save to DB, etc.)

    return NextResponse.json({ success: true });
  } catch (error) {
    return handleApiError(error, 'contact-form');
  }
}

export const POST = withRateLimit(withCsrf(handler));
export const config = { runtime: 'nodejs' };
模板 3:公共端点(无需身份验证,但需速率限制)
import { NextRequest, NextResponse } from 'next/server';
import { withRateLimit } from '@/lib/withRateLimit';
import { validateRequest } from '@/lib/validateRequest';
import { handleApiError } from '@/lib/errorHandler';
import { emailSchema } from '@/lib/validation';

async function handler(request: NextRequest) {
  try {
    const body = await request.json();
    const validation = validateRequest(emailSchema, body);

    if (!validation.success) {
      return validation.response;
    }

    const email = validation.data;

    // Process (e.g., newsletter signup)

    return NextResponse.json({ success: true });
  } catch (error) {
    return handleApiError(error, 'newsletter');
  }
}

export const POST = withRateLimit(handler);
export const config = { runtime: 'nodejs' };

不要这样做 - 常见反模式

❌ 反模式 1:不使用安全中间件
// BAD - No protection
export async function POST(request: NextRequest) {
  const body = await request.json();
  // directly use body.field
  return NextResponse.json({ success: true });
}

**这样做的问题:**没有速率限制、CSRF 保护或输入验证,容易遭受暴力破解、CSRF 攻击和注入攻击。

❌ 反模式 2:跳过输入验证
// BAD - No validation
async function handler(request: NextRequest) {
  const body = await request.json();
  const { title } = body; // Could contain <script> tags!
  await saveToDatabase(title);
}

**这样做的问题:**会造成 XSS 漏洞。未经清理的用户输入会被直接存储或显示。

❌ 反模式 3:在生产环境中暴露错误详情
// BAD - Information leakage
catch (error) {
  return NextResponse.json({
    error: error.message,      // Could reveal internal paths
    stack: error.stack,        // Exposes code structure
    query: failedQuery         // Reveals database schema
  }, { status: 500 });
}

**这样做的问题:**这会帮助攻击者了解系统内部、数据库结构和文件路径。

❌ 反模式 4:硬编码密钥
// BAD - Hardcoded secret
const apiKey = 'sk_live_123456789';

// GOOD - Environment variable
const apiKey = process.env.API_KEY;

**这样做的问题:**密钥会进入版本控制;如果代码仓库遭到入侵,密钥就很容易泄露。

❌ 反模式 5:不对公共表单实施速率限制
// BAD - Can be spammed infinitely
export async function POST(request: NextRequest) {
  await sendEmail(data);
  return NextResponse.json({ success: true });
}

// GOOD - Rate limited
export const POST = withRateLimit(async (request: NextRequest) => {
  await sendEmail(data);
  return NextResponse.json({ success: true });
});

**这样做的问题:**攻击者可以向端点发送垃圾请求、抬高成本或实施暴力破解攻击。

安全意识:了解 AI 代码漏洞

在实施安全控制之前,请先了解AI 为什么会生成不安全的代码,以及需要留意哪些漏洞:

AI 代码为何常常不安全

研究统计数据:

  • 45% 的 AI 生成代码存在不安全模式(Veracode 2024)
  • 36–72% 的代码包含漏洞,具体比例因语言而异(Georgetown CSET 2024)
  • 68% 的数据库查询存在 SQL 注入问题(Aikido Security 2025)
  • 81% 的代码以不安全的方式存储密码(Databricks 2025)
安全意识技能

了解 AI 生成代码中特定类别的漏洞:

了解注入攻击: → security-awareness/injection-vulnerabilities - SQL 注入、命令注入、XSS

  • 真实案例:Equifax(1.47 亿条记录)、British Airways(罚款 2,000 万英镑)
  • 为什么 AI 会生成字符串拼接,而不是参数化查询
  • 攻击途径和利用模式

了解身份验证缺陷: → security-awareness/auth-vulnerabilities - 不安全的密码、失效的会话、访问控制

  • 真实案例:Ashley Madison(3,200 万个账户)、Dropbox(6,800 万个账户)
  • 为什么 AI 会推荐 MD5/明文密码
  • 为什么 AI 会忘记进行授权检查

了解信息泄露: → security-awareness/information-leakage - 硬编码的密钥、过于详细的日志

  • 真实案例:AWS 密钥泄露(12 小时内造成 4 万美元损失)、日志中包含支付数据
  • 为什么 AI 会硬编码凭据(训练数据)
  • 哪些内容绝不能记录到日志中

了解供应链风险: → security-awareness/supply-chain-risks - 易受攻击的依赖项、仿冒拼写攻击

  • 真实案例:event-stream 遭劫持(每周 200 万次下载)、24.5 万个恶意包(2023 年)
  • 为什么 AI 会推荐过时的包(其中 67% 存在漏洞)
  • 依赖项混淆攻击

了解业务逻辑缺陷: → security-awareness/business-logic-flaws - 竞态条件、整数溢出

  • 真实案例:闪购超卖、25 万美元退款漏洞利用
  • 为什么逻辑缺陷能通过功能测试
  • 并发访问漏洞

了解资源耗尽: → security-awareness/resource-exhaustion - 无限制操作、成本暴增

  • 真实案例:AI API 费用达到 20 万美元(4 小时内未被察觉)
  • 为什么 AI 不会添加资源限制
  • DoS 攻击模式

全面了解安全风险: → security-awareness/awareness-overview - AI 安全风险完整概述

  • 统计数据、研究、真实世界中的安全事件
  • 安全氛围编程的前进方向
  • 安全优先的提示词技巧

后续步骤

根据你的任务,调用相应的技能:

实现技能(如何安全地构建)
  • 需要保护 API 路由?→ csrf-protection 技能
  • 需要防止垃圾信息/滥用?→ rate-limiting 技能
  • 需要验证用户输入?→ input-validation 技能
  • 需要配置标头?→ security-headers 技能
  • 需要处理错误?→ error-handling 技能
  • 需要身份验证?→ auth-security 技能
  • 需要处理支付?→ payment-security 技能
  • 需要更新包?→ dependency-security 技能
  • 需要测试安全性?→ security-testing 技能
运维技能(部署与监控)
  • 何时使用哪种中间件?→ security-operations 技能
  • 需要设置环境变量?→ security-operations 技能
  • 需要部署前检查清单?→ security-operations 技能
  • 需要设置安全监控?→ security-operations 技能
  • 需要维护计划?→ security-operations 技能
安全意识技能(了解风险)
  • 想了解 AI 安全风险?→ security-awareness/awareness-overview 技能
  • 学习注入攻击?→ security-awareness/injection-vulnerabilities 技能
  • 了解身份验证漏洞?→ security-awareness/auth-vulnerabilities 技能
  • 学习密钥泄露?→ security-awareness/information-leakage 技能
  • 了解供应链?→ security-awareness/supply-chain-risks 技能
  • 学习逻辑缺陷?→ security-awareness/business-logic-flaws 技能
  • 了解 DoS 风险?→ security-awareness/resource-exhaustion 技能

参考资料

评论

支持 Markdown