security-architecture-overview

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Security Architecture Overview

安全架构概览

Project Security Profile

项目安全概况

Project: Secure Vibe Coding OS Version: 1.0 Next.js Version: 15.5.4 Security Audit Status: 0 vulnerabilities OWASP Score: 90/100 (Top 10% of Next.js applications)
项目: Secure Vibe Coding OS 版本: 1.0 Next.js版本: 15.5.4 安全审计状态: 0个漏洞 OWASP评分: 90/100(在Next.js应用中排名前10%)

What This Project Is

项目简介

Secure Vibe Coding OS is a production-ready SaaS starter template built with security as a first-class concern, not an afterthought. Unlike typical Next.js starters that provide basic authentication and hope you figure out the rest, this starter embeds enterprise-grade security controls from day one.
Secure Vibe Coding OS是一款生产就绪的SaaS启动模板,将安全作为核心设计要素,而非事后补充。与仅提供基础身份验证、让开发者自行完善其余安全措施的典型Next.js启动模板不同,本模板从一开始就嵌入了企业级安全控制。

Why This Architecture Exists

该架构的设计初衷

According to Veracode's 2024 State of Software Security Report, AI-generated code picks insecure patterns 45% of the time. Standard SaaS starters compound this problem by providing minimal security guidance. Developers then prompt AI to build features on an insecure foundation, and each new feature becomes a potential vulnerability.
This architecture breaks that cycle by providing:
  • Defense-in-depth security (multiple layers)
  • Secure-by-default patterns (opt-in to relaxed security)
  • AI-friendly security utilities (easy to use correctly)
  • 90/100 OWASP score baseline (top 10% of applications)
根据Veracode《2024年软件安全状态报告》,AI生成的代码中有45%存在不安全模式。标准SaaS启动模板几乎不提供安全指导,加剧了这一问题。开发者基于不安全的基础,通过AI生成功能代码,每新增一个功能都可能引入潜在漏洞。
本架构通过以下设计打破这一循环:
  • 纵深防御安全机制(多层防护)
  • 默认安全模式(需主动选择放宽安全限制)
  • AI友好型安全工具(易于正确使用)
  • 90/100的OWASP评分基准(排名前10%的应用)

Key Security Principles

核心安全原则

1. Defense-in-Depth

1. 纵深防御

Every request passes through multiple security layers. If one fails, others catch the attack.
每个请求都需经过多层安全校验,若某一层失效,其他层可拦截攻击。

2. Fail-Secure

2. 故障安全

When errors occur, the system denies access by default. Better to show an error than grant unauthorized access.
当发生错误时,系统默认拒绝访问。显示错误信息远比授予未授权访问权限更安全。

3. Least Privilege

3. 最小权限

Users and systems get minimum access needed. Authentication confirms identity; authorization limits what they can do.
用户和系统仅获得所需的最小访问权限。身份验证确认身份,授权限制其可执行的操作。

4. Security is Implemented, Not Assumed

4. 安全是实现出来的,而非假设的

We don't assume users will "use it securely." Security is baked into every utility, middleware, and pattern.
我们不假设用户会“安全地使用系统”,安全机制被嵌入到每个工具、中间件和模式中。

The 5-Layer Security Stack

5层安全栈

Every request passes through these layers before reaching business logic:
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                    │
└─────────────────────────────────────────────┘
What This Achieves: An attacker must bypass all 5 layers simultaneously to compromise the system—effectively impossible with current attack techniques.
每个请求在到达业务逻辑前需经过以下层级:
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层防护才能攻陷系统——以当前的攻击技术而言,这实际上是不可能的。

When to Use Each Security Skill

各安全技能的适用场景

For API Route Protection:

API路由防护:

  • csrf-protection skill: When creating POST/PUT/DELETE endpoints that change state
  • rate-limiting skill: When protecting endpoints from abuse (forms, expensive operations)
  • input-validation skill: When accepting any user input (always!)
  • csrf-protection技能:创建用于修改状态的POST/PUT/DELETE端点时
  • rate-limiting技能:防护易被滥用的端点(如表单、资源密集型操作)时
  • input-validation技能:接收任何用户输入时(务必使用!)

For Application Security:

应用安全:

  • security-headers skill: When configuring middleware or need to understand CSP/HSTS
  • error-handling skill: When implementing error responses in API routes
  • auth-security skill: When implementing authentication/authorization with Clerk
  • security-headers技能:配置中间件或需要理解CSP/HSTS时
  • error-handling技能:在API路由中实现错误响应时
  • auth-security技能:使用Clerk实现身份验证/授权时

For Integrations:

集成场景:

  • payment-security skill: When implementing Stripe payments via Clerk Billing
  • dependency-security skill: When adding packages or running security audits
  • payment-security技能:通过Clerk Billing集成Stripe支付时
  • dependency-security技能:添加依赖包或运行安全审计时

For Verification:

验证场景:

  • security-testing skill: When testing security features or pre-deployment checklist
  • security-testing技能:测试安全功能或执行部署前检查清单时

Architecture Decision Rationale

架构决策依据

Why Layered Security?

为什么采用分层安全?

The Single Point of Failure Problem: Traditional web applications often rely on a single security measure. If that one control fails or is bypassed, the entire system is compromised.
Real-world Example: The 2020 SolarWinds attack exploited a single compromised build server. Once attackers bypassed that one control, they had access to thousands of organizations. A defense-in-depth approach would have caught the intrusion at multiple other layers.
Our Approach: Like a medieval castle with moat, walls, towers, and inner keep—attackers must breach every layer. Each layer catches different attack types:
  • Middleware: Stops requests before they reach application code
  • Rate Limiting: Stops automated attacks
  • CSRF: Stops cross-origin attacks
  • Validation: Stops injection attacks
  • Authentication/Authorization: Stops unauthorized access
单点故障问题: 传统Web应用通常依赖单一安全措施。若该控制失效或被绕过,整个系统将面临风险。
实际案例: 2020年SolarWinds攻击利用了一个被攻陷的构建服务器。攻击者绕过这一层控制后,就获得了数千家企业的访问权限。而纵深防御方法会在其他多个层拦截此类入侵。
我们的方案: 就像拥有护城河、城墙、塔楼和内堡的中世纪城堡——攻击者必须突破每一层防护。每一层都能拦截不同类型的攻击:
  • **中间件:**在请求到达应用代码前拦截
  • **速率限制:**阻止自动化攻击
  • **CSRF防护:**阻止跨源攻击
  • **输入验证:**阻止注入攻击
  • **身份验证/授权:**阻止未授权访问

Complete Security Stack Pattern

完整安全栈示例

Here's what a fully secure API route looks like:
typescript
// 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: 'admin@example.com', 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
};
这是一个完全安全的API路由示例:
typescript
// 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: 'admin@example.com', 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
};

Environment-Specific Security

环境专属安全配置

Development (Relaxed)

开发环境(宽松)

  • ✅ Detailed error messages (full stack traces)
  • ✅ Verbose logging
  • ✅ HTTP allowed (localhost)
  • ✅ Development keys
  • ✅ 详细错误信息(完整堆栈跟踪)
  • ✅ 详细日志
  • ✅ 允许HTTP(仅本地主机)
  • ✅ 开发密钥

Production (Maximum Protection)

生产环境(最高防护)

  • ✅ Generic error messages ONLY
  • ✅ Minimal logging (no PII)
  • ✅ HTTPS enforced (HSTS)
  • ✅ Production keys
Automatic Detection: The code detects
process.env.NODE_ENV === 'production'
and adjusts security posture automatically.
  • ✅ 仅显示通用错误信息
  • ✅ 最小化日志(无个人可识别信息PII)
  • ✅ 强制HTTPS(HSTS)
  • ✅ 生产密钥
自动检测: 代码会检测
process.env.NODE_ENV === 'production'
,并自动调整安全策略。

Tech Stack Security Components

技术栈安全组件

Authentication: Clerk

身份验证:Clerk

  • SOC 2 certified
  • Handles password hashing, sessions, MFA, OAuth
  • 73% fewer auth vulnerabilities vs custom implementations
  • Skill:
    auth-security
  • SOC 2认证
  • 处理密码哈希、会话、多因素认证MFA、OAuth
  • 与自定义实现相比,身份验证漏洞减少73%
  • 对应技能:
    auth-security

Payments: Clerk Billing + Stripe

支付:Clerk Billing + Stripe

  • Never touch card data
  • PCI-DSS compliant (via Stripe)
  • Webhook signature verification
  • Skill:
    payment-security
  • 无需直接处理卡片数据
  • 符合PCI-DSS合规标准(通过Stripe)
  • Webhook签名验证
  • 对应技能:
    payment-security

Database: Convex

数据库:Convex

  • Type-safe queries
  • User-scoped data via ctx.auth.userId
  • Additional validation in mutations
  • 类型安全查询
  • 通过ctx.auth.userId实现用户范围数据隔离
  • 在变更操作中附加验证

Framework: Next.js 15.5.4

框架:Next.js 15.5.4

  • Latest security patches
  • Middleware for global security controls
  • App Router for better security boundaries
  • 最新安全补丁
  • 用于全局安全控制的中间件
  • 应用路由器提供更优的安全边界

Quick Reference: Security Checklist

快速参考:安全检查清单

When creating a new API route, ensure:
  • Applied
    withRateLimit()
    if route could be abused
  • Applied
    withCsrf()
    for POST/PUT/DELETE
  • Validated input with Zod schemas from
    lib/validation.ts
  • Used
    handleApiError()
    in catch block
  • Checked authentication with
    await auth()
    from Clerk
  • Checked authorization if accessing user-specific resources
  • Used proper HTTP status codes (200, 400, 401, 403, 404, 429, 500)
  • No sensitive data logged (passwords, tokens, PII)
  • Set
    runtime: 'nodejs'
    in config for crypto operations
  • Tested the endpoint before committing
创建新API路由时,需确保:
  • 若路由可能被滥用,已应用
    withRateLimit()
  • 对POST/PUT/DELETE请求已应用
    withCsrf()
  • 使用
    lib/validation.ts
    中的Zod schema验证输入
  • 在catch块中使用
    handleApiError()
  • 使用Clerk的
    await auth()
    检查身份验证
  • 若访问用户专属资源,已检查授权
  • 使用正确的HTTP状态码(200, 400, 401, 403, 404, 429, 500)
  • 未记录敏感数据(密码、令牌、PII)
  • 为加密操作在config中设置
    runtime: 'nodejs'
  • 提交前已测试端点

Common Patterns - Copy & Paste Templates

通用模式 - 可复制模板

Template 1: Simple Protected Endpoint (No CSRF)

模板1:简单受保护端点(无CSRF防护)

typescript
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' };
typescript
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' };

Template 2: Form Submission with Full Protection

模板2:表单提交(完整防护)

typescript
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' };
typescript
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' };

Template 3: Public Endpoint (No Auth, Yes Rate Limit)

模板3:公开端点(无身份验证,有速率限制)

typescript
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' };
typescript
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' };

What NOT to Do - Common Anti-Patterns

禁忌操作 - 常见反模式

❌ Anti-Pattern 1: No Security Middlewares

❌ 反模式1:未使用安全中间件

typescript
// BAD - No protection
export async function POST(request: NextRequest) {
  const body = await request.json();
  // directly use body.field
  return NextResponse.json({ success: true });
}
Why this is bad: No rate limiting, no CSRF protection, no input validation. Vulnerable to brute force, CSRF attacks, and injection attacks.
typescript
// 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攻击和注入攻击。

❌ Anti-Pattern 2: Skipping Input Validation

❌ 反模式2:跳过输入验证

typescript
// BAD - No validation
async function handler(request: NextRequest) {
  const body = await request.json();
  const { title } = body; // Could contain <script> tags!
  await saveToDatabase(title);
}
Why this is bad: XSS vulnerability. User input directly stored/displayed without sanitization.
typescript
// BAD - No validation
async function handler(request: NextRequest) {
  const body = await request.json();
  const { title } = body; // Could contain <script> tags!
  await saveToDatabase(title);
}
为什么不好: 存在XSS漏洞,用户输入未经清理直接存储/显示。

❌ Anti-Pattern 3: Exposing Error Details in Production

❌ 反模式3:在生产环境暴露错误详情

typescript
// 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 });
}
Why this is bad: Helps attackers understand your system internals, database structure, file paths.
typescript
// 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 });
}
为什么不好: 帮助攻击者了解系统内部结构、数据库架构、文件路径。

❌ Anti-Pattern 4: Hardcoding Secrets

❌ 反模式4:硬编码密钥

typescript
// BAD - Hardcoded secret
const apiKey = 'sk_live_123456789';

// GOOD - Environment variable
const apiKey = process.env.API_KEY;
Why this is bad: Secrets end up in version control, easily exposed if repository is compromised.
typescript
// BAD - Hardcoded secret
const apiKey = 'sk_live_123456789';

// GOOD - Environment variable
const apiKey = process.env.API_KEY;
为什么不好: 密钥会被提交到版本控制,若仓库泄露,密钥极易被获取。

❌ Anti-Pattern 5: No Rate Limiting on Public Forms

❌ 反模式5:公开表单未设置速率限制

typescript
// 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 });
});
Why this is bad: Attackers can spam your endpoints, rack up costs, or perform brute force attacks.
typescript
// 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 });
});
为什么不好: 攻击者可无限次发送请求,造成垃圾信息泛滥、成本激增或暴力破解。

Security Awareness: Understanding AI Code Vulnerabilities

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

Before implementing security controls, understand why AI generates insecure code and what vulnerabilities to watch for:
在实施安全控制前,需了解AI为何会生成不安全代码以及需要警惕哪些漏洞:

Why AI Code Is Often Insecure

AI生成代码通常不安全的原因

Statistics from Research:
  • 45% of AI-generated code has insecure patterns (Veracode 2024)
  • 36-72% contains vulnerabilities depending on language (Georgetown CSET 2024)
  • 68% of database queries have SQL injection (Aikido Security 2025)
  • 81% stores passwords insecurely (Databricks 2025)
研究统计数据:
  • 45%的AI生成代码存在不安全模式(Veracode 2024)
  • 36-72%的代码存在漏洞(取决于编程语言,Georgetown CSET 2024)
  • 68%的数据库查询存在SQL注入风险(Aikido Security 2025)
  • 81%的代码不安全存储密码(Databricks 2025)

Security Awareness Skills

安全意识技能

Learn about specific vulnerability categories in AI-generated code:
Understanding Injection Attacks:
security-awareness/injection-vulnerabilities
- SQL injection, command injection, XSS
  • Real examples: Equifax (147M records), British Airways (£20M fine)
  • Why AI generates string concatenation instead of parameterized queries
  • Attack vectors and exploitation patterns
Understanding Authentication Defects:
security-awareness/auth-vulnerabilities
- Insecure passwords, broken sessions, access control
  • Real examples: Ashley Madison (32M accounts), Dropbox (68M accounts)
  • Why AI suggests MD5/plaintext passwords
  • Why AI forgets authorization checks
Understanding Information Leakage:
security-awareness/information-leakage
- Hardcoded secrets, verbose logging
  • Real examples: AWS keys exposed ($40K in 12 hours), payment data in logs
  • Why AI hardcodes credentials (training data)
  • What should never be logged
Understanding Supply Chain Risks:
security-awareness/supply-chain-risks
- Vulnerable dependencies, typosquatting
  • Real examples: event-stream hijacked (2M downloads/week), 245K malicious packages (2023)
  • Why AI suggests outdated packages (67% have vulnerabilities)
  • Dependency confusion attacks
Understanding Business Logic Flaws:
security-awareness/business-logic-flaws
- Race conditions, integer overflow
  • Real examples: Flash sales overselling, $250K refund exploit
  • Why logic flaws pass functional tests
  • Concurrent access vulnerabilities
Understanding Resource Exhaustion:
security-awareness/resource-exhaustion
- Unbounded operations, cost explosion
  • Real examples: $200K in AI API charges (4 hours unnoticed)
  • Why AI doesn't add resource limits
  • DoS attack patterns
Overall Security Awareness:
security-awareness/awareness-overview
- Complete overview of AI security risks
  • Statistics, research, real-world breaches
  • Path forward for secure vibe coding
  • Security-first prompting techniques
了解AI生成代码中的特定漏洞类别:
理解注入攻击:
security-awareness/injection-vulnerabilities
- SQL注入、命令注入、XSS
  • 实际案例:Equifax(1.47亿条记录泄露)、英国航空(2000万英镑罚款)
  • AI为何生成字符串拼接而非参数化查询
  • 攻击向量与利用模式
理解身份验证缺陷:
security-awareness/auth-vulnerabilities
- 不安全密码、会话漏洞、访问控制失效
  • 实际案例:Ashley Madison(3200万账户泄露)、Dropbox(6800万账户泄露)
  • AI为何建议使用MD5/明文密码
  • AI为何忽略授权检查
理解信息泄露:
security-awareness/information-leakage
- 硬编码密钥、详细日志
  • 实际案例:AWS密钥泄露(12小时内产生4万美元费用)、日志中包含支付数据
  • AI为何硬编码凭证(训练数据影响)
  • 哪些信息绝对不能记录
理解供应链风险:
security-awareness/supply-chain-risks
- 易受攻击的依赖包、打字劫持
  • 实际案例:event-stream被劫持(每周200万次下载)、2023年有24.5万个恶意包
  • AI为何建议使用过时包(67%存在漏洞)
  • 依赖混淆攻击
理解业务逻辑缺陷:
security-awareness/business-logic-flaws
- 竞态条件、整数溢出
  • 实际案例:闪购超卖、25万美元退款漏洞
  • 逻辑缺陷为何能通过功能测试
  • 并发访问漏洞
理解资源耗尽:
security-awareness/resource-exhaustion
- 无界操作、成本激增
  • 实际案例:4小时内产生20万美元AI API费用(未被察觉)
  • AI为何不添加资源限制
  • DoS攻击模式
整体安全意识:
security-awareness/awareness-overview
- AI安全风险完整概览
  • 统计数据、研究成果、真实泄露事件
  • 安全氛围编码的前进方向
  • 安全优先的提示技巧

Next Steps

后续步骤

Based on your task, invoke the appropriate skill:
根据你的任务,调用对应的技能:

Implementation Skills (How to Build Securely)

实现类技能(如何安全构建)

  • Need to protect an API route? →
    csrf-protection
    skill
  • Need to prevent spam/abuse? →
    rate-limiting
    skill
  • Need to validate user input? →
    input-validation
    skill
  • Need to configure headers? →
    security-headers
    skill
  • Need error handling? →
    error-handling
    skill
  • Need authentication? →
    auth-security
    skill
  • Need payments? →
    payment-security
    skill
  • Need to update packages? →
    dependency-security
    skill
  • Need to test security? →
    security-testing
    skill
  • 需要保护API路由?→
    csrf-protection
    技能
  • 需要防止垃圾信息/滥用?→
    rate-limiting
    技能
  • 需要验证用户输入?→
    input-validation
    技能
  • 需要配置头部?→
    security-headers
    技能
  • 需要错误处理?→
    error-handling
    技能
  • 需要身份验证?→
    auth-security
    技能
  • 需要支付功能?→
    payment-security
    技能
  • 需要更新依赖包?→
    dependency-security
    技能
  • 需要测试安全功能?→
    security-testing
    技能

Operations Skills (Deployment & Monitoring)

运维类技能(部署与监控)

  • When to use which middleware? →
    security-operations
    skill
  • Need environment variable setup? →
    security-operations
    skill
  • Pre-deployment checklist? →
    security-operations
    skill
  • Security monitoring setup? →
    security-operations
    skill
  • Maintenance schedule? →
    security-operations
    skill
  • 何时使用各类中间件?→
    security-operations
    技能
  • 需要设置环境变量?→
    security-operations
    技能
  • 部署前检查清单?→
    security-operations
    技能
  • 安全监控设置?→
    security-operations
    技能
  • 维护计划?→
    security-operations
    技能

Awareness Skills (Understanding Risks)

意识类技能(理解风险)

  • Want to understand AI security risks? →
    security-awareness/awareness-overview
    skill
  • Learning about injection attacks? →
    security-awareness/injection-vulnerabilities
    skill
  • Understanding auth vulnerabilities? →
    security-awareness/auth-vulnerabilities
    skill
  • Learning about exposed secrets? →
    security-awareness/information-leakage
    skill
  • Understanding supply chain? →
    security-awareness/supply-chain-risks
    skill
  • Learning about logic flaws? →
    security-awareness/business-logic-flaws
    skill
  • Understanding DoS risks? →
    security-awareness/resource-exhaustion
    skill
  • 想要了解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
    技能

References

参考资料