Claude
Skills
Sign in
Back

security-architecture-overview

Included with Lifetime
$97 forever

Understand the defense-in-depth security architecture of Secure Vibe Coding OS. Use this skill when you need to understand the overall security approach, the 5-layer security stack, OWASP scoring, or when to use other security skills. Triggers include "security architecture", "defense in depth", "security layers", "how does security work", "OWASP score", "security overview", "security principles".

Security

What this skill does


# 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)

## 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.

## 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)

## Key Security Principles

### 1. Defense-in-Depth
Every request passes through multiple security layers. If one fails, others catch the attack.

### 2. Fail-Secure
When errors occur, the system denies access by default. Better to show an error than grant unauthorized access.

### 3. Least Privilege
Users and systems get minimum access needed. Authentication confirms identity; authorization limits what they can do.

### 4. Security is Implemented, Not Assumed
We don't assume users will "use it securely." Security is baked into every utility, middleware, and pattern.

## The 5-Layer Security Stack

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.

## When to Use Each Security Skill

### For API Route Protection:
- **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!)

### 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

### For Integrations:
- **payment-security skill**: When implementing Stripe payments via Clerk Billing
- **dependency-security skill**: When adding packages or running security audits

### For Verification:
- **security-testing skill**: When testing security features or pre-deployment checklist

## 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

## 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: '[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
};
```

## Environment-Specific Security

### Development (Relaxed)
- ✅ Detailed error messages (full stack traces)
- ✅ Verbose logging
- ✅ HTTP allowed (localhost)
- ✅ Development keys

### 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.

## Tech Stack Security Components

### Authentication: Clerk
- SOC 2 certified
- Handles password hashing, sessions, MFA, OAuth
- 73% fewer auth vulnerabilities vs custom implementations
- **Skill:** `auth-security`

### Payments: Clerk Billing + Stripe
- Never touch card data
- PCI-DSS compliant (via Stripe)
- Webhook signature verifi
Files: 1
Size: 19.6 KB
Complexity: 26/100
Category: Security

Related in Security