security-architecture-overview
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".
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 verifiRelated in Security
mac-ops
IncludedComprehensive macOS workstation operations — diagnose kernel panics, identify failing drives, audit launchd startup items, decode wake reasons, triage TCC permission denials, manage APFS snapshots, recover from no-boot. Use for: Mac is slow, slow bootup, won't boot, kernel panic, kernel_task hot, mds_stores CPU, photoanalysisd, cloudd, login loop, gray screen, sleep wake failure, drive failing, IO errors, APFS snapshots eating space, Time Machine local snapshots, Spotlight indexing, launchd, LaunchAgent, LaunchDaemon, login items, TCC permissions, Full Disk Access, Screen Recording denied, Gatekeeper, quarantine, com.apple.quarantine, app is damaged, helper tool, /Library/PrivilegedHelperTools, pmset, wake reasons, dark wake, sysdiagnose, panic.ips, DiagnosticReports, configuration profile, MDM profile, remote diagnostics over SSH.
a11y-audit
IncludedRun accessibility audits on web projects combining automated scanning (axe-core, Lighthouse) with WCAG 2.1 AA compliance mapping, manual check guidance, and structured reporting. Output is configurable: markdown report only, markdown plus machine-readable JSON, or markdown plus issue tracker integration. Use this skill whenever the user mentions "accessibility audit", "a11y audit", "WCAG audit", "accessibility check", "compliance scan", or asks to check a web project for accessibility issues. Also trigger when the user wants to verify WCAG conformance or map findings to a specific standard (CAN-ASC-6.2, EN 301 549, ADA/AODA).
erpclaw
IncludedAI-native ERP system with self-extending OS. Full accounting, invoicing, inventory, purchasing, tax, billing, HR, payroll, advanced accounting (ASC 606/842, intercompany, consolidation), and financial reporting. 413 actions across 14 domains, 43 expansion modules. Constitutional guardrails, adversarial audit, schema migration. Double-entry GL, immutable audit trail, US GAAP.
assess
IncludedAssesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.
spring-boot-security-jwt
IncludedProvides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x. Use when implementing authentication or authorization in Spring Boot applications.
code-hardcode-audit
IncludedDetect hardcoded values, magic numbers, and leaked secrets. TRIGGERS - hardcode audit, magic numbers, PLR2004, secret scanning.