
Security Prompts
- 177 installs
- 15 repo stars
- Updated December 14, 2025
- harperaa/secure-claude-skills
Apply security-focused prompts and guardrails when building or reviewing AI-assisted code and agent behavior.
About
Supplies security-oriented prompt patterns and guardrails for Claude Code agents to avoid leaking secrets, generating vulnerable code, or bypassing policies during implementation, review, and pre-launch hardening workflows.
- secure prompt templates
- agent guardrails
- secret-leak prevention
- threat-aware instructions
- pre-ship review prompts
Security Prompts by the numbers
- 177 all-time installs (skills.sh)
- +1 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #821 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 2, 2026 (Skillselion catalog sync)
npx skills add https://github.com/harperaa/secure-claude-skills --skill security-promptsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 177 |
|---|---|
| repo stars | ★ 15 |
| Last updated | December 14, 2025 |
| Repository | harperaa/secure-claude-skills ↗ |
What it does
Apply security-focused prompts and guardrails when building or reviewing AI-assisted code and agent behavior.
Files
Auth & Authorization Security Templates
Purpose
This skill provides authentication and authorization prompt templates for implementing secure access control systems. Use these templates to set up role-based access control (RBAC), granular permissions, ownership verification, and comprehensive authorization testing.
Available Templates
01: RBAC Implementation
File: 01_rbac_implementation.md When to use: First time adding roles (user, premium, admin) Time: 60 minutes
Implementation Coverage:
- Server-side role storage
- Clerk publicMetadata integration
- Webhook-based role assignment
- Role-based route protection
- Middleware enforcement
- Role checking utilities
Roles Implemented:
- user (default) - Basic authenticated access
- premium (paid) - Enhanced features via Clerk Billing
- admin (staff) - Full system access
Trigger keywords: "RBAC", "role-based access", "user roles", "implement roles", "setup roles", "add roles", "role system"
Use case: Initial authorization setup, multi-tier application, SaaS with subscription tiers
Output: Complete RBAC system with Clerk integration
---
02: Permissions System
File: 02_permissions.md When to use: Granular permission system beyond basic roles Time: 90 minutes
Implementation Coverage:
- Fine-grained permissions
- Permission groups
- Resource-level access
- Permission inheritance
- Dynamic permission checks
- Permission management UI
Permission Examples:
users.read,users.write,users.deleteposts.create,posts.edit,posts.publishadmin.dashboard,admin.settings
Trigger keywords: "permissions", "permission system", "granular access", "fine-grained permissions", "permission management", "resource permissions"
Use case: Enterprise applications, complex access requirements, team collaboration tools
Output: Comprehensive permission system with management interface
---
03: Ownership Verification
File: 03_ownership.md When to use: Resource ownership checks (users can only modify their own data) Time: 30 minutes
Implementation Coverage:
- Ownership validation
- User-resource relationship checks
- Authorization errors
- Multi-owner scenarios
- Delegation patterns
Security Focus:
- Prevent horizontal privilege escalation
- Verify user owns the resource
- Handle shared resources
- Team/organization ownership
Trigger keywords: "ownership", "ownership check", "resource ownership", "user owns", "own data only", "verify ownership", "prevent user accessing others data"
Use case: Profile editing, document management, any user-specific resources
Output: Ownership verification utilities and endpoint protection
---
04: Authorization Testing
File: 04_auth_testing.md When to use: Comprehensive authorization testing Time: 60 minutes
Test Coverage:
- Role-based access tests
- Permission verification tests
- Ownership check tests
- Negative authorization tests
- Cross-user access prevention
- Privilege escalation tests
Test Scenarios:
- User cannot access admin routes
- User cannot modify other users' data
- Premium features blocked for free users
- Unauthenticated requests rejected
- Invalid role assignments rejected
Trigger keywords: "auth testing", "authorization tests", "test permissions", "test RBAC", "test access control", "authorization test suite"
Use case: Continuous testing, CI/CD integration, security validation
Output: Complete authorization test suite
---
Usage Pattern
1. Identify Authorization Need
First-time setup (no auth beyond Clerk): → 01_rbac_implementation.md
Need granular control: → 02_permissions.md
User-specific resources: → 03_ownership.md
Verify authorization: → 04_auth_testing.md
2. Sequential Implementation
Recommended order:
Step 1: RBAC (Foundation)
→ Use: 01_rbac_implementation.md
Step 2: Ownership (User Resources)
→ Use: 03_ownership.md
Step 3: Permissions (If Needed)
→ Use: 02_permissions.md
Step 4: Testing (Always)
→ Use: 04_auth_testing.md3. Load Template
Read: .claude/skills/security/security-prompts/auth-authorization/[number]_[name].md4. Customize for Application
Replace in template:
[role names]with your roles[permission names]with your permissions[resource types]with your data models[access matrix]with your requirements
5. Present Implementation Plan
I'll implement [AUTHORIZATION_TYPE] using the auth template.
**What we'll set up**:
- [List from template]
**How it integrates with Clerk**:
- [Clerk-specific details]
**Testing strategy**:
- [Testing approach]
**Estimated time**: [From template]
Let me customize the template for your application...Common Authorization Patterns
Pattern 1: Basic RBAC
Application: Blog with user/admin roles
Implementation:
→ 01_rbac_implementation.md
Role Matrix:
- user: Read posts, comment, manage own comments
- admin: All user access + create/edit/delete posts, moderate comments
Testing:
→ 04_auth_testing.mdPattern 2: SaaS with Tiers
Application: SaaS tool with free/premium/enterprise
Implementation:
→ 01_rbac_implementation.md
Role Matrix:
- free: Basic features, 10 projects limit
- premium: Advanced features, unlimited projects
- enterprise: All features + team management
Integration:
→ Clerk Billing webhooks set role based on subscription
Testing:
→ 04_auth_testing.mdPattern 3: User Resources
Application: Profile management
Implementation:
Step 1: RBAC for basic roles
→ 01_rbac_implementation.md
Step 2: Ownership for profile editing
→ 03_ownership.md
Verification:
- User A cannot edit User B's profile
- Admins can edit any profile
- Users can edit their own profile
Testing:
→ 04_auth_testing.mdPattern 4: Enterprise Permissions
Application: Team collaboration tool
Implementation:
Step 1: RBAC for base roles
→ 01_rbac_implementation.md
Step 2: Granular permissions
→ 02_permissions.md
Step 3: Ownership for resources
→ 03_ownership.md
Permission Matrix:
- Owner: All permissions
- Admin: Most permissions, cannot delete workspace
- Member: View and edit, cannot manage team
- Guest: View only
Testing:
→ 04_auth_testing.mdIntegration with Feature Templates
Authenticated Endpoints
Step 1: Setup RBAC
→ auth-authorization/01_rbac_implementation.md
Step 2: Implement feature with auth
→ prompt-engineering/02_authenticated_endpoint.md
Step 3: Add ownership checks
→ auth-authorization/03_ownership.md
Step 4: Test authorization
→ auth-authorization/04_auth_testing.mdAdmin Features
Step 1: Setup RBAC (if not exists)
→ auth-authorization/01_rbac_implementation.md
Step 2: Implement admin endpoints
→ prompt-engineering/04_admin_action.md
Step 3: Test admin access
→ auth-authorization/04_auth_testing.md
Step 4: Review security
→ threat-modeling/04_code_review.mdClerk Integration
All templates integrate with Clerk:
Role Storage: publicMetadata.role
// Read from session
const { sessionClaims } = auth();
const role = sessionClaims?.publicMetadata?.role;Webhook Assignment:
// In convex/http.ts or app/api/webhooks/clerk/route.ts
await clerkClient.users.updateUserMetadata(userId, {
publicMetadata: { role: "user" }
});Middleware Protection:
// In middleware.ts
const role = auth().sessionClaims?.publicMetadata?.role;
if (role !== "admin" && pathname.startsWith("/admin")) {
return Response.redirect("/unauthorized");
}Permission Storage (if using 02_permissions.md):
publicMetadata: {
role: "user",
permissions: ["posts.read", "posts.create", "comments.create"]
}Best Practices
1. Server-Side Only
Always verify on server:
// ✅ Good - server-side check
export async function DELETE(req: Request) {
const { userId } = auth();
const role = auth().sessionClaims?.publicMetadata?.role;
if (role !== "admin") {
return new Response("Forbidden", { status: 403 });
}
// Delete logic
}
// ❌ Bad - client could bypass
if (userRole === "admin") {
deleteButton.disabled = false;
}2. Default Deny
Require explicit permission:
// ✅ Good - default deny
if (role === "admin" || role === "moderator") {
// Allow
} else {
return new Response("Forbidden", { status: 403 });
}
// ❌ Bad - default allow
if (role === "guest") {
return new Response("Forbidden", { status: 403 });
}
// Continues without check3. Test Negative Cases
Always test rejection:
// Test user cannot access admin
test("non-admin cannot delete posts", async () => {
const response = await DELETE("/api/posts/123", {
headers: { Authorization: `Bearer ${userToken}` }
});
expect(response.status).toBe(403);
});4. Log Authorization Failures
Audit access attempts:
if (role !== "admin") {
await logSecurityEvent({
event: "unauthorized_admin_access_attempt",
userId,
resource: pathname,
timestamp: new Date()
});
return new Response("Forbidden", { status: 403 });
}Agent Usage
When Implementing Features
Agent: "User needs to edit their profile"
Response: "First check if RBAC exists. If not, use:
.claude/skills/security/security-prompts/auth-authorization/01_rbac_implementation.md
Then for the profile endpoint, use:
.claude/skills/security/security-prompts/prompt-engineering/02_authenticated_endpoint.md
Add ownership verification with:
.claude/skills/security/security-prompts/auth-authorization/03_ownership.md"When Reviewing Security
Agent: "Review authorization implementation"
Response: "Check against template:
.claude/skills/security/security-prompts/auth-authorization/04_auth_testing.md
Verify:
- All routes have role checks
- Server-side enforcement
- Default deny pattern
- Negative test cases exist"Common Pitfalls
❌ Client-Side Only Checks
Problem: Hiding UI elements without server enforcement
// ❌ Bad
{role === "admin" && <DeleteButton />}Solution: Always enforce server-side
// ✅ Good
{role === "admin" && <DeleteButton />}
// On server
export async function DELETE(req: Request) {
const role = auth().sessionClaims?.publicMetadata?.role;
if (role !== "admin") return Response.json({error: "Forbidden"}, {status: 403});
}❌ Trusting Client Claims
Problem: Reading role from request body
// ❌ Bad
const { role } = await req.json();
if (role === "admin") { /* allow */ }Solution: Read from server session
// ✅ Good
const role = auth().sessionClaims?.publicMetadata?.role;
if (role === "admin") { /* allow */ }❌ Missing Ownership Checks
Problem: Only checking authentication
// ❌ Bad
export async function PATCH(req: Request, { params }: { params: { id: string } }) {
const { userId } = auth();
if (!userId) return Response.json({error: "Unauthorized"}, {status: 401});
// Updates ANY post, even if user doesn't own it
await db.posts.update(params.id, data);
}Solution: Verify ownership
// ✅ Good
export async function PATCH(req: Request, { params }: { params: { id: string } }) {
const { userId } = auth();
if (!userId) return Response.json({error: "Unauthorized"}, {status: 401});
const post = await db.posts.get(params.id);
if (post.authorId !== userId) {
return Response.json({error: "Forbidden"}, {status: 403});
}
await db.posts.update(params.id, data);
}Testing Strategy
Unit Tests
Role checks:
describe("Role-based access", () => {
test("admin can access admin routes", async () => {
// Test with admin token
});
test("user cannot access admin routes", async () => {
// Test with user token, expect 403
});
});Integration Tests
Full flow:
describe("Profile editing", () => {
test("user can edit own profile", async () => {
// Create user, edit profile, verify success
});
test("user cannot edit other user profile", async () => {
// User A tries to edit User B, expect 403
});
});E2E Tests
Real scenarios:
- Sign up → assigned user role → verify limited access
- Subscribe → role changes to premium → verify enhanced access
- Admin promotes user → verify role change → verify new access
Related Skills
Parent Skill:
- security-prompts - Main directory with all template categories (engineering, threat-modeling, controls, auth)
Implementation Skills (referenced by templates):
- auth-security - Clerk authentication implementation
- clerk - Clerk integration patterns
Note: For other template categories (implementation, threat modeling, simple controls), see the parent security-prompts skill
Version History
v1.0 (2025-10-23): Initial skill creation
- Converted 4 auth/authorization templates
- Added Clerk integration guidance
- Added common pitfalls and best practices
- Integration patterns with other templates
---
Note: Authentication (who you are) is handled by Clerk. These templates focus on authorization (what you can do). Always implement both.
RBAC Implementation
Category: Auth & Authorization When to Use: First time adding roles (user, premium, admin) Module: 3.4 Time to Implement: 60 minutes
Security Controls Applied
- ✅ Server-side role storage
- ✅ Clerk publicMetadata
- ✅ Webhook integration
- ✅ Role-based routing
- ✅ Middleware protection
The Prompt
CONTEXT:
I'm working with Secure Vibe Coding OS which has Clerk authentication already configured.
I need to add Role-Based Access Control (RBAC) with three roles: "user" (default),
"premium" (paid subscribers via Clerk Billing), and "admin" (staff). All role checks
must happen server-side using Clerk's publicMetadata.
FUNCTIONAL REQUIREMENTS:
- New users automatically get "user" role on signup
- Premium role assigned via Clerk Billing webhook (when user subscribes)
- Admin role manually assigned only by existing admins
- Users cannot change their own roles
- Each role has different route and feature access
Role Access Matrix:
- User role: /dashboard, /profile, /settings
- Premium role: user access + /premium-features, /advanced-analytics
- Admin role: all access + /admin, /admin/users
SECURITY REQUIREMENTS:
Authorization:
- Roles stored in Clerk publicMetadata (server-controlled)
- ALL role checks happen server-side (never trust client claims)
- Middleware checks roles before route access
- API endpoints verify roles in every handler
- Default role "user" assigned on webhook user creation
- Only admins can modify roles (never user-controlled)
- 403 Forbidden for insufficient permissions
- 401 Unauthorized for unauthenticated requests
Role Storage:
- Store as: publicMetadata.role = "user" | "premium" | "admin"
- Read from: auth().sessionClaims.publicMetadata.role
- Never expose role change endpoints publicly
- Log all role changes for audit trail
Webhook Integration:
- On user.created event → set role: "user" in publicMetadata
- On subscription.created event → set role: "premium"
- On subscription.canceled event → revert role to "user"
- Verify webhook signatures (already configured in project)
TECHNICAL SPECIFICATIONS:
- Framework: Next.js 14 (existing Secure Vibe Coding OS setup)
- Auth: Clerk (already configured)
- Middleware: middleware.ts (extend existing protection)
- Database: Convex (webhook handler in convex/http.ts)
- TypeScript types for roles: lib/types.ts
Files to modify:
1. convex/http.ts - Add role assignment in webhook handler
2. middleware.ts - Add role-based route protection
3. lib/types.ts - Add role type definitions
4. lib/auth-utils.ts - Create role checking utilities
5. app/admin - Create admin-only pages
Files to create:
- lib/rbac.ts - Role checking functions
- app/api/admin/change-role/route.ts - Admin endpoint to change roles
VALIDATION CRITERIA:
After implementation, I should be able to:
1. Sign up new account and verify role="user" in Clerk Dashboard
2. Try to access /admin as user and receive 403 error
3. Manually set role="admin" in Clerk Dashboard and access /admin successfully
4. Subscribe via Clerk Billing and verify role changes to "premium"
5. Call admin API endpoint as non-admin and get rejected
6. Verify all role checks happen server-side (can't bypass with browser tools)
7. See role changes logged in Convex database
Please implement RBAC following Secure Vibe Coding OS architecture.
Reference:
@middleware.ts
@convex/http.ts
@lib/clerk.tsCustomization Tips
Add more roles: Add: "moderator", "editor", etc.
Change role names: Rename to match your app
Add role hierarchy: Define which roles inherit from others
Testing Checklist
- [ ] New signups get "user" role
- [ ] Cannot access admin routes as user
- [ ] Admin role grants access
- [ ] Roles synced from Clerk
- [ ] Server-side checks enforced
- [ ] Role changes logged
Related Prompts
- Permissions:
auth-authorization/02_permissions.md - Ownership:
auth-authorization/03_ownership.md
Version History
v1.0 (2025-10-21): Initial version
Granular Permission System
Category: Auth & Authorization When to Use: Need specific action permissions beyond roles Module: 3.4 Time to Implement: 45 minutes
Security Controls Applied
- ✅ Permission storage in Clerk metadata
- ✅ Server-side permission checks
- ✅ Admin auto-permissions
- ✅ Granular action control
The Prompt
CONTEXT:
I have role-based access control working (user, premium, admin roles) in Secure Vibe
Coding OS. Now I need granular permissions for specific actions like editing content,
deleting users, accessing analytics, etc. Some actions need combination permissions.
FUNCTIONAL REQUIREMENTS:
- Define specific permissions: can_edit_content, can_delete_content,
can_view_analytics, can_manage_users
- Admins get all permissions automatically
- Other users can be granted specific permissions
- Check permissions for each protected action
SECURITY REQUIREMENTS:
Permission Storage:
- Permissions stored in Clerk publicMetadata alongside roles
- Server-controlled only (users cannot grant themselves permissions)
- Permissions loaded with authentication, not queried separately
Permission Checking:
- Check permission before allowing action
- Some actions require multiple permissions (AND logic)
- Some actions allow alternative permissions (OR logic)
- Fail closed (no permission = deny access)
- Log permission denials for audit trail
Permission Structure:
- Each permission is a string identifier
- Permissions grouped by domain (content, user, analytics)
- Clear naming convention: can_<action>_<resource>
- Type-safe permission checks
Error Handling:
- 403 status for insufficient permissions
- Generic error message to user
- Specific permission logged server-side
TECHNICAL SPECIFICATIONS:
- Store permissions array in Clerk publicMetadata
- Create hasPermission() helper function
- Create requirePermission() middleware
- Type definitions for all permissions
- Permission checking in both pages and API routes
Files to modify:
- lib/types.ts - Permission type definitions
- lib/rbac.ts - Add permission checking functions
- convex/http.ts - Set default permissions in webhook
- app/api/admin/grant-permission/route.ts - Admin endpoint
VALIDATION CRITERIA:
After implementation, I should be able to:
1. Create user with specific permissions and verify they work
2. Attempt action without required permission and receive 403
3. Verify admins bypass permission checks (have all permissions)
4. Test combining permissions (user needs can_edit AND can_publish)
5. Check permission in component to conditionally show UI elements
6. Verify permissions can be granted/revoked by admin
7. See permission denial logged with user ID and attempted action
Please implement a granular permission system following Secure Vibe Coding OS standards.
Reference:
@lib/rbac.ts - Existing role checking
@middleware.ts - Current authorization middleware
@docs/security/SECURITY_ARCHITECTURE.md - Security architectureCustomization Tips
Define your permissions: List all permissions your app needs
Permission naming: Follow: can_<action>_<resource> pattern
Permission groups: Group related permissions for easier management
Testing Checklist
- [ ] Permissions stored in metadata
- [ ] Permission checks work
- [ ] Admin has all permissions
- [ ] Users can't grant themselves permissions
- [ ] Permission denials logged
- [ ] UI respects permissions
Related Prompts
- RBAC:
auth-authorization/01_rbac_implementation.md - Ownership:
auth-authorization/03_ownership.md
Version History
v1.0 (2025-10-21): Initial version
Ownership-Based Authorization
Category: Auth & Authorization When to Use: Users should manage their own content Module: 3.4 Time to Implement: 30 minutes
Security Controls Applied
- ✅ Resource ownership verification
- ✅ Combined with role checks
- ✅ Combined with permission checks
- ✅ Three-layer authorization
The Prompt
CONTEXT:
I have roles and permissions working. Now I need ownership-based authorization
so users can edit their own blog posts even without special permissions.
SECURITY REQUIREMENTS:
Ownership Verification:
- Check if resource.authorId === userId
- Always verify server-side (never trust client)
- Combined with existing role/permission checks
- Authorization logic: admin OR permission OR ownership
Resource Pattern:
- Every resource has authorId/userId/ownerId field
- Stored in database with resource
- Verified before any modification
- Return 403 if ownership check fails
Authorization Flow (in order):
1. Check if user is admin → Allow (admins can do anything)
2. Check if user has specific permission → Allow
3. Check if user owns resource → Allow
4. Deny (403 Forbidden)
IMPLEMENTATION REQUIREMENTS:
- Create canModifyResource() helper function
- Accept: userId, resourceId, action type
- Check all three authorization layers
- Return true/false
- Log authorization decisions
Error Handling:
- 401 for unauthenticated
- 403 for failed authorization
- Include which check failed in logs (not to user)
TECHNICAL SPECIFICATIONS:
- Add to: lib/auth-utils.ts or lib/authorization.ts
- Use with: API routes that modify resources
- Integrate with: Existing RBAC and permission system
VALIDATION CRITERIA:
After implementation, I should be able to:
1. Regular user can edit own blog post
2. Regular user cannot edit others' posts (403)
3. Admin can edit any post
4. User with can_edit_content permission can edit any post
5. Verify authorization logic: admin OR permission OR ownership
Generate the ownership authorization system.
Reference:
@lib/rbac.ts
@lib/types.tsCustomization Tips
Change ownership field: Use: authorId, userId, ownerId, creatorId
Add co-ownership: Support multiple owners per resource
Add delegation: Allow owners to grant access to others
Testing Checklist
- [ ] User can edit own content
- [ ] User cannot edit others' content
- [ ] Admin can edit any content
- [ ] Permission holders can edit any
- [ ] Authorization order correct
- [ ] All checks logged
Related Prompts
- RBAC:
auth-authorization/01_rbac_implementation.md - Permissions:
auth-authorization/02_permissions.md
Version History
v1.0 (2025-10-21): Initial version
Authorization Testing
Category: Auth & Authorization When to Use: Verify all authorization layers work correctly Module: 3.4 Time to Implement: 30 minutes
Test Coverage
- ✅ Role-based access control
- ✅ Permission checks
- ✅ Ownership verification
- ✅ Security boundary tests
- ✅ Authorization combinations
The Prompt
Before launching, I need to test that all authorization controls work correctly.
**Context**:
I have implemented:
- RBAC with roles: [list roles]
- Permissions: [list permissions]
- Ownership checks for: [list resources]
**Security Requirements**:
Test Coverage:
- Role-based access control working
- Permission checks enforcing access
- Ownership checks allowing user content management
- All checks happen server-side
- Bypasses are impossible
Please create a comprehensive authorization test plan:
**1. ROLE TESTS**:
- Access [protected route] as each role (user, premium, admin)
- Verify role assignment on signup
- Test role changes via Clerk Dashboard
- Verify role changes via subscription webhook (if applicable)
**2. PERMISSION TESTS**:
- Call protected endpoints with/without permissions
- Test permission grant/revoke as admin
- Verify client cannot modify own permissions
- Test AND logic (multiple permissions required)
- Test OR logic (alternative permissions)
**3. OWNERSHIP TESTS**:
- Edit own content as regular user
- Try to edit others' content (should fail)
- Verify admin can edit any content
- Test combined ownership + permission checks
**4. SECURITY BOUNDARY TESTS**:
- Attempt role escalation via API
- Try to bypass middleware with direct API calls
- Modify metadata via client (should fail)
- Use expired/invalid tokens
- Test IDOR (Insecure Direct Object Reference) vulnerabilities
**5. COMBINED AUTHORIZATION TESTS**:
- Test: Admin OR Permission OR Ownership logic
- Verify authorization order (admin checked first)
- Test edge cases (no role, empty permissions)
For each test provide:
- Exact steps to perform
- Expected result (success/failure + status code)
- How to verify in Clerk Dashboard
- What logs should show
- How to test via curl or Postman
Create a checklist I can work through before deployment.
Reference:
@lib/rbac.ts
@lib/auth-utils.ts
@middleware.tsTest Script Template
# Test 1: User cannot access admin route
curl http://localhost:3000/admin \
-H "Authorization: Bearer [USER_TOKEN]"
# Expected: 403 Forbidden
# Test 2: Admin can access admin route
curl http://localhost:3000/admin \
-H "Authorization: Bearer [ADMIN_TOKEN]"
# Expected: 200 OK
# Add more tests...Deliverables
- [ ] Role test suite
- [ ] Permission test suite
- [ ] Ownership test suite
- [ ] Security boundary tests
- [ ] Combined authorization tests
- [ ] Test results documented
- [ ] All tests passing
Testing Checklist
Role Tests:
- [ ] New signups get default role
- [ ] Admin routes blocked for non-admins
- [ ] Premium routes blocked for free users
- [ ] Role changes sync from Clerk
Permission Tests:
- [ ] Users without permissions blocked
- [ ] Users with permissions allowed
- [ ] Admins bypass permission checks
- [ ] Permissions cannot be self-granted
Ownership Tests:
- [ ] Users can modify own resources
- [ ] Users blocked from others' resources
- [ ] Admins can modify any resource
- [ ] Ownership combined with permissions
Security Boundaries:
- [ ] Cannot escalate role via API
- [ ] Cannot bypass middleware
- [ ] Cannot modify own metadata
- [ ] Expired tokens rejected
Related Prompts
- RBAC setup:
auth-authorization/01_rbac_implementation.md - Permissions:
auth-authorization/02_permissions.md - Ownership:
auth-authorization/03_ownership.md
Version History
v1.0 (2025-10-21): Initial version
Contact Form with Security Stack
Category: Built-In Controls When to Use: Creating public forms that accept user input Module: 3.2 Time to Implement: 20 minutes
Security Controls Applied
- ✅ CSRF protection (withCsrf)
- ✅ Rate limiting (withRateLimit - 5 per 15 min)
- ✅ Input validation (Zod schemas)
- ✅ XSS sanitization (safeTextSchema)
- ✅ Secure error handling (handleApiError)
The Prompt
CONTEXT:
I'm working with Secure Vibe Coding OS and need an endpoint where users can submit a contact form.
SECURITY FOUNDATION REFERENCE:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md (Layer 2, 3, 4)
- Existing utilities: withCsrf, withRateLimit, validateRequest from Secure Vibe Coding OS
SECURITY REQUIREMENTS:
- CSRF protection using existing withCsrf() middleware
- Rate limiting: 5 submissions per 15 minutes per IP (using withRateLimit())
- Input validation with Zod schema (using safeTextSchema for name, emailSchema for email)
- XSS sanitization on all text inputs (automatically handled by safeTextSchema)
- Secure error handling (using handleApiError())
FUNCTIONAL REQUIREMENTS:
- Accept: name (string, max 100 chars), email (valid email), message (string, max 1000 chars)
- Send email notification to admin@myapp.com
- Return success message to user
- Log all submissions for monitoring
IMPLEMENTATION:
1. Create API route at `app/api/contact/route.ts`
2. Apply security middleware: withRateLimit(withCsrf(handler))
3. Define Zod schema for validation:
- name: safeTextSchema (max 100 chars)
- email: emailSchema
- message: safeTextSchema (max 1000 chars)
4. Validate input using validateRequest()
5. Return errors using handleApiError() for secure error responses
6. Frontend: Include CSRF token from /api/csrf endpoint
VERIFICATION:
After implementation, I should be able to:
1. Submit valid form → succeeds with 200 status
2. Submit without CSRF token → fails with 403
3. Submit 6 times rapidly → 5 succeed, 6th gets 429 (rate limited)
4. Submit with XSS attempt in message → sanitized automatically
5. Submit with invalid email → fails with 400 and helpful error
6. See submissions logged for monitoring
Please create the secure contact form API route using Secure Vibe Coding OS security utilities.
Reference:
@lib/withCsrf.ts
@lib/withRateLimit.ts
@lib/validateRequest.ts
@lib/validation.ts
@lib/errorHandler.ts
@app/api/example-protected/route.tsCustomization Tips
Change rate limit: Replace: 5 submissions per 15 minutes With: Your desired limit
Change validation: Modify Zod schema requirements:
- name length
- message length
- Additional fields
Change functionality: Replace: "Send email notification" With: Your desired action (save to database, send to Slack, etc.)
Testing Checklist
After implementation:
- [ ] Form submission works with valid data
- [ ] CSRF token required (try without - should fail 403)
- [ ] Rate limiting blocks 6th submission
- [ ] XSS payloads sanitized
- [ ] Error messages don't leak system info
Related Prompts
- More comprehensive: See
prompt-engineering/01_secure_form.md - Authenticated forms: See
built-in-controls/02_authenticated_update.md
Version History
v1.0 (2025-10-21): Initial version
Authenticated Data Update Endpoint
Category: Built-In Controls When to Use: Endpoints where users modify their own data Module: 3.2 Time to Implement: 20 minutes
Security Controls Applied
- ✅ Authentication (Clerk)
- ✅ Authorization (ownership verification)
- ✅ CSRF protection (withCsrf)
- ✅ Rate limiting (withRateLimit)
- ✅ Input validation (Zod schemas)
- ✅ XSS sanitization
- ✅ Secure error handling
The Prompt
CONTEXT:
I'm working with Secure Vibe Coding OS and need an endpoint where authenticated users can update their profile information.
SECURITY FOUNDATION REFERENCE:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Existing utilities: Clerk auth(), withCsrf, withRateLimit, validateRequest
SECURITY REQUIREMENTS:
- Clerk authentication required (verify userId from session)
- Authorization: User can ONLY update their own profile (verify userId matches profile)
- CSRF protection using withCsrf()
- Rate limiting: 10 updates per hour per user
- Input validation with Zod schemas
- XSS sanitization on all text fields
- Return 401 for unauthenticated users
- Return 403 for unauthorized access (trying to edit someone else's profile)
FUNCTIONAL REQUIREMENTS:
- Fields to update: name, bio, avatar URL
- Validate: name (max 100 chars), bio (max 500 chars), avatar URL (HTTPS only, image)
- Save to database (Convex or your database)
- Return success message with updated profile
IMPLEMENTATION:
1. Create API route at `app/api/profile/update/route.ts`
2. Check authentication: const { userId } = await auth()
3. Verify ownership: profile.userId === userId
4. Apply security middleware: withRateLimit(withCsrf(handler))
5. Validate input with Zod schemas
6. Update database only after all checks pass
7. Use handleApiError() for secure error responses
VERIFICATION:
After implementation, I should be able to:
1. Update own profile successfully when logged in
2. Get 401 when not logged in
3. Get 403 when trying to update another user's profile
4. Get 429 after 10 updates in an hour (rate limited)
5. XSS attempts in bio are sanitized
6. Invalid avatar URLs are rejected
7. All security checks logged
Please create the secure profile update endpoint using Secure Vibe Coding OS utilities.
Reference:
@lib/withCsrf.ts
@lib/withRateLimit.ts
@lib/validateRequest.ts
@lib/validation.ts
@lib/errorHandler.tsCustomization Tips
Change what can be updated: Add/remove fields in Zod schema
Change rate limits: Adjust: 10 updates per hour
Change authorization logic: Modify ownership check for different resources
Testing Checklist
- [ ] Authenticated user can update own profile
- [ ] Unauthenticated request returns 401
- [ ] User A cannot update User B's profile (403)
- [ ] Rate limiting works after 10 requests
- [ ] Input validation catches bad data
- [ ] XSS attempts sanitized
Related Prompts
- Ownership pattern: See
auth-authorization/03_ownership.md - Admin overrides: See
prompt-engineering/04_admin_action.md
Version History
v1.0 (2025-10-21): Initial version
Public Read API Endpoint
Category: Built-In Controls When to Use: GET endpoints returning public data Module: 3.2 Time to Implement: 20 minutes
Security Controls Applied
- ✅ Rate limiting (withRateLimit)
- ✅ Query parameter validation
- ✅ Secure error handling
- ❌ No CSRF (GET requests don't modify state)
- ❌ No authentication (public data)
The Prompt
CONTEXT:
I'm working with Secure Vibe Coding OS and need a public API endpoint that returns paginated blog posts.
SECURITY FOUNDATION REFERENCE:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Existing utilities: withRateLimit, validateRequest
SECURITY REQUIREMENTS:
- Rate limiting: 60 requests per minute per IP
- Query parameter validation (page, limit)
- Prevent parameter injection attacks
- No CSRF protection needed (GET is safe)
- No authentication needed (public data)
- Secure error handling (no information leakage)
FUNCTIONAL REQUIREMENTS:
- Endpoint: GET /api/posts
- Query params: page (default 1, min 1), limit (default 10, max 100)
- Return: Paginated list of posts
- Include: total count, current page, total pages
IMPLEMENTATION:
1. Create API route at `app/api/posts/route.ts`
2. Apply rate limiting: withRateLimit(handler)
3. Validate query parameters with Zod:
- page: positive integer, default 1
- limit: positive integer, max 100, default 10
4. Fetch data from database
5. Return paginated response
6. Use handleApiError() for errors
VERIFICATION:
After implementation, I should be able to:
1. Request /api/posts → succeeds with paginated data
2. Request /api/posts?page=1&limit=20 → succeeds
3. Request /api/posts?page=-1 → validation fails (400)
4. Request /api/posts?limit=1000 → caps at 100
5. Make 61 rapid requests → rate limited on 61st (429)
6. Invalid parameters → clear error message
Please create the secure public API endpoint using appropriate Secure Vibe Coding OS utilities.
Reference:
@lib/withRateLimit.ts
@lib/validateRequest.ts
@lib/errorHandler.tsCustomization Tips
Change rate limits: Adjust: 60 requests per minute
Change pagination: Modify: limit max value, default page size
Add filtering: Add query params: category, author, search
Change data source: Replace blog posts with your data
Testing Checklist
- [ ] Endpoint returns data successfully
- [ ] Pagination works correctly
- [ ] Query param validation catches bad input
- [ ] Rate limiting blocks excessive requests
- [ ] Error messages are user-friendly
- [ ] No sensitive data in responses
Related Prompts
- Authenticated APIs: See
built-in-controls/02_authenticated_update.md - Complex APIs: See
prompt-engineering/03_public_endpoint.md
Version History
v1.0 (2025-10-21): Initial version
Comprehensive Secure Form
Category: Prompt Engineering When to Use: Full security stack for public forms Module: 3.3 Time to Implement: 30 minutes
Security Controls Applied
- ✅ CSRF protection
- ✅ Rate limiting
- ✅ Input validation
- ✅ XSS sanitization
- ✅ Security headers
- ✅ Secure error handling
The Prompt
I'm adding a public contact form to the application.
**Security Foundation Reference**:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md (Layer 2, 3, 4)
- Existing utilities: withCsrf, withRateLimit, validateRequest from Secure Vibe Coding OS
**Security Requirements**:
- CSRF protection using existing withCsrf() middleware
- Rate limiting: 5 submissions per 15 minutes per IP (using withRateLimit())
- Input validation with Zod schema (using safeTextSchema for name, emailSchema for email)
- XSS sanitization on all text inputs (automatically handled by safeTextSchema)
- Secure error handling (using handleApiError())
**Implementation**:
1. Create API route at `app/api/contact/route.ts`
2. Apply security middleware: withRateLimit(withCsrf(handler))
3. Define Zod schema for validation:
- name: safeTextSchema (max 100 chars)
- email: emailSchema
- message: safeTextSchema (max 1000 chars)
4. Validate input using validateRequest()
5. Return errors using handleApiError() for secure error responses
6. Frontend: Include CSRF token from /api/csrf endpoint
**Verification**:
- Confirm form submission requires valid CSRF token
- Verify rate limiting blocks 6th submission within 15 minutes
- Test XSS payloads are sanitized: `<script>alert('xss')</script>`
- Check error messages don't leak system information
Generate the secure contact form API route following this security pattern.Customization Tips
Replace these placeholders:
[feature]→ your feature name[fields]→ your form fields[rate limit]→ your rate limit
Testing Checklist
- [ ] CSRF token required
- [ ] Rate limiting works
- [ ] XSS attempts sanitized
- [ ] Validation catches bad input
- [ ] Errors are secure
Related Prompts
- Simpler version:
built-in-controls/01_contact_form.md - With auth:
prompt-engineering/02_authenticated_endpoint.md
Version History
v1.0 (2025-10-21): Initial version
Authenticated Endpoint with Authorization
Category: Prompt Engineering When to Use: User profile updates, settings changes, data modification Module: 3.3 Time to Implement: 30 minutes
Security Controls Applied
- ✅ Authentication (Clerk)
- ✅ Authorization (ownership + permissions)
- ✅ CSRF protection
- ✅ Rate limiting
- ✅ Input validation
- ✅ Secure error handling
The Prompt
I'm working with Secure Vibe Coding OS and need an endpoint where authenticated users can [describe action, e.g., "update their profile information", "modify their settings"].
**Security Foundation Reference**:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Existing utilities: Clerk auth(), withCsrf, withRateLimit, validateRequest
**Security Requirements**:
- Clerk authentication required (verify userId from session)
- Authorization: User can ONLY [action] their own [resource]
- CSRF protection using withCsrf()
- Rate limiting: [specify limit, e.g., "10 updates per hour"]
- Input validation with Zod schemas
- XSS sanitization on all text fields
- Return 401 for unauthenticated users
- Return 403 for unauthorized access
**Functional Requirements**:
- Fields to [modify]: [list fields]
- Validation rules: [specify for each field]
- Save to database (Convex or your database)
- Return success message with updated data
**Implementation**:
1. Create API route at `app/api/[feature]/route.ts`
2. Check authentication: const { userId } = await auth()
3. Verify authorization: [resource].userId === userId
4. Apply security middleware: withRateLimit(withCsrf(handler))
5. Validate input with Zod schemas
6. Update database only after all checks pass
7. Use handleApiError() for secure error responses
**Verification**:
- Authenticated user can [action] successfully
- Get 401 when not logged in
- Get 403 when trying to [action] another user's [resource]
- Rate limiting works after [limit] requests
- XSS attempts sanitized
- Invalid input rejected with clear errors
Please create the secure authenticated endpoint using Secure Vibe Coding OS utilities.
Reference:
@lib/withCsrf.ts
@lib/withRateLimit.ts
@lib/validateRequest.ts
@lib/validation.tsCustomization Tips
Change action: Specify what users are doing (updating, deleting, creating)
Change authorization: Adjust ownership check for your resource type
Change rate limits: Tune based on expected usage patterns
Testing Checklist
- [ ] Authentication required
- [ ] Authorization enforced
- [ ] CSRF protection works
- [ ] Rate limiting functions
- [ ] Input validation catches bad data
- [ ] Errors handled securely
Related Prompts
- Ownership:
auth-authorization/03_ownership.md - Simpler version:
built-in-controls/02_authenticated_update.md
Version History
v1.0 (2025-10-21): Initial version
Public Endpoint with Pagination
Category: Prompt Engineering When to Use: Public data endpoints with query parameters and pagination Module: 3.3 Time to Implement: 30 minutes
Security Controls Applied
- ✅ Rate limiting
- ✅ Query parameter validation
- ✅ Pagination limits
- ✅ Secure error handling
- ❌ No CSRF (GET is safe)
- ❌ No authentication (public)
The Prompt
I'm working with Secure Vibe Coding OS and need a public API endpoint that returns paginated [data type, e.g., "blog posts", "products", "listings"].
**Security Foundation Reference**:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Existing utilities: withRateLimit, validateRequest
**Security Requirements**:
- Rate limiting: [specify limit, e.g., "60 requests per minute per IP"]
- Query parameter validation (page, limit, [other params])
- Prevent parameter injection attacks
- Pagination limits enforced (max items per page)
- No CSRF protection needed (GET is safe)
- No authentication needed (public data)
- Secure error handling (no information leakage)
**Functional Requirements**:
- Endpoint: GET /api/[resource]
- Query params:
- page (default 1, min 1)
- limit (default 10, max 100)
- [add other filters like category, search, sort]
- Return: Paginated list with metadata
- Include: total count, current page, total pages, has_next, has_previous
**Implementation**:
1. Create API route at `app/api/[resource]/route.ts`
2. Apply rate limiting: withRateLimit(handler)
3. Validate query parameters with Zod:
- page: positive integer, default 1
- limit: positive integer, max 100, default 10
- [add validation for other params]
4. Fetch data from database with pagination
5. Calculate pagination metadata
6. Return paginated response with metadata
7. Use handleApiError() for errors
**Verification**:
- Request /api/[resource] → succeeds with paginated data
- Request with pagination params → works correctly
- Request with page=-1 → validation fails (400)
- Request with limit=1000 → caps at 100
- Make [limit+1] rapid requests → rate limited
- Invalid parameters → clear error messages
Please create the secure public API endpoint using Secure Vibe Coding OS utilities.
Reference:
@lib/withRateLimit.ts
@lib/validateRequest.ts
@lib/errorHandler.tsCustomization Tips
Add filtering: Include query params like: category, author, search, date_from, date_to
Add sorting: Allow: sort_by=date, order=asc/desc
Change limits: Adjust max page size and rate limits
Testing Checklist
- [ ] Pagination works correctly
- [ ] Query param validation functions
- [ ] Rate limiting enforced
- [ ] Edge cases handled (page=0, limit=0)
- [ ] Metadata accurate (total_pages, etc.)
- [ ] No sensitive data exposed
Related Prompts
- Simpler version:
built-in-controls/03_public_api.md - With auth:
prompt-engineering/02_authenticated_endpoint.md
Version History
v1.0 (2025-10-21): Initial version
Admin-Only Action
Category: Prompt Engineering When to Use: Admin dashboard, user management, system configuration Module: 3.3 Time to Implement: 30 minutes
Security Controls Applied
- ✅ Authentication (Clerk)
- ✅ Role verification (admin only)
- ✅ CSRF protection
- ✅ Aggressive rate limiting
- ✅ Input validation
- ✅ Audit logging
The Prompt
CONTEXT:
I'm working with Secure Vibe Coding OS and need an admin-only endpoint for [describe admin action, e.g., "deleting users", "changing user roles", "viewing system logs"].
**Security Foundation Reference**:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Existing utilities: Clerk auth(), withCsrf, withRateLimit, validateRequest
- RBAC: @lib/rbac.ts
**Security Requirements**:
- Clerk authentication required
- Role verification: Only users with role="admin" can access
- CSRF protection using withCsrf()
- Aggressive rate limiting: 10 requests per hour per admin
- Input validation for all parameters
- Audit logging: Log every admin action with userId, action type, timestamp
- Return 401 for unauthenticated users
- Return 403 for non-admin users
**Functional Requirements**:
- [Describe what the admin action does]
- [List input parameters]
- [Describe success response]
**Implementation**:
1. Create API route at `app/api/admin/[action]/route.ts`
2. Check authentication: const { userId } = await auth()
3. Verify admin role: const { sessionClaims } = await auth()
4. Check: sessionClaims.publicMetadata.role === 'admin'
5. Apply security middleware: withRateLimit(withCsrf(handler))
6. Validate all input parameters
7. Perform admin action
8. Log action to audit trail (Convex or your database)
9. Return success/error response
**Verification**:
- Admin can perform action successfully
- Non-admin gets 403 Forbidden
- Unauthenticated request gets 401
- Rate limiting blocks excessive admin requests
- All actions logged with timestamp and userId
- Input validation catches bad data
Generate the secure admin-only endpoint following this security pattern.
Reference:
@lib/rbac.ts
@lib/withCsrf.ts
@lib/withRateLimit.ts
@lib/validateRequest.tsCustomization Tips
Change admin action: Replace action description with your specific need
Change rate limits: Adjust for sensitivity: 10/hour for dangerous actions, 60/hour for safe ones
Add permissions: Beyond role, check specific permissions
Testing Checklist
- [ ] Admin can perform action
- [ ] Regular user gets 403
- [ ] Unauthenticated gets 401
- [ ] Rate limiting works
- [ ] Actions logged in audit trail
- [ ] Input validation works
Related Prompts
- RBAC setup:
auth-authorization/01_rbac_implementation.md - Permissions:
auth-authorization/02_permissions.md
Version History
v1.0 (2025-10-21): Initial version
Secure File Upload
Category: Prompt Engineering When to Use: Profile pictures, document uploads, any file handling Module: 3.3 Time to Implement: 45 minutes
Security Controls Applied
- ✅ Authentication
- ✅ CSRF protection
- ✅ Rate limiting
- ✅ File type validation
- ✅ File size limits
- ✅ External upload service
- ✅ Virus scanning
The Prompt
CONTEXT:
I'm working with Secure Vibe Coding OS and need a secure file upload endpoint for [profile pictures / documents / etc.].
**Security Foundation Reference**:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Existing utilities: Clerk auth(), withCsrf, withRateLimit
**Security Requirements**:
- Clerk authentication required
- Authorization: User can only upload to their own profile
- CSRF protection using withCsrf()
- Rate limiting: 5 uploads per hour per user
- File type validation:
- Check Content-Type header
- Verify file signature (magic bytes)
- Only allow: images (jpg, png, webp) OR PDFs OR [specify types]
- File size limit: 5MB maximum
- Upload to external service (Uploadthing, Cloudinary, S3)
- Virus scanning via upload service
- Never store files on application server
- Store only CDN URLs in database
**Functional Requirements**:
- Accept file upload from authenticated user
- Validate file before uploading to external service
- Upload to external CDN with virus scanning
- Store returned CDN URL in database
- Delete previous file from CDN (cleanup)
- Return new file URL to client
**Implementation**:
1. Create API route: `app/api/profile/upload-picture/route.ts`
2. Verify authentication and authorization
3. Apply security middleware: withRateLimit(withCsrf(handler))
4. Validate file metadata:
- Check Content-Type header
- Verify file signature (magic bytes) matches claimed type
- Check file size <= 5MB
5. Upload to external service (e.g., Uploadthing with virus scanning)
6. Receive back CDN URL and thumbnail URL
7. Update user profile in Convex with new URLs
8. Delete previous image from CDN (cleanup)
9. Return new image URLs to frontend
**Verification**:
- Unauthenticated uploads return 401
- Wrong user cannot upload to another profile (403)
- Non-image files rejected
- Files over 5MB rejected
- 6th upload in 1 hour blocked
- Malicious files caught by external service scanning
- Old profile pictures removed from CDN
- Database stores CDN URLs only, not file content
Generate the secure file upload endpoint following this security pattern, emphasizing external upload service usage.
Reference:
@lib/withCsrf.ts
@lib/withRateLimit.tsCustomization Tips
Change file types: Adjust allowed types: images, PDFs, documents
Change size limits: Modify: 5MB → your limit
Change upload service: Replace Uploadthing with: Cloudinary, AWS S3, Vercel Blob
Testing Checklist
- [ ] Valid files upload successfully
- [ ] Invalid file types rejected
- [ ] Oversized files rejected
- [ ] Rate limiting works
- [ ] Old files cleaned up
- [ ] Only CDN URLs stored
Related Prompts
- Authentication:
auth-authorization/01_rbac_implementation.md - Admin uploads:
prompt-engineering/04_admin_action.md
Version History
v1.0 (2025-10-21): Initial version
Composable Security Middleware
Category: Prompt Engineering When to Use: Complex endpoints requiring multiple security layers Module: 3.3 Time to Implement: 20 minutes
Security Controls Applied
- ✅ Multiple middleware layers
- ✅ Correct ordering (critical!)
- ✅ Defense-in-depth composition
- ✅ Type-safe middleware
The Prompt
I'm building [feature description] that requires multiple security controls.
**Security Foundation Reference**:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Utilities: [list all utilities needed, e.g., withRateLimit, withCsrf, auth()]
**Security Stack for this Endpoint**:
Layer 1: Authentication [yes/no + details]
Layer 2: Input Validation [Zod schema details]
Layer 3: Middleware [which middlewares + order]
Layer 4: Error Handling [which error handlers]
Layer 5: Headers [auto-applied]
**Implementation Order** (critical for composable middleware):
1. Outermost: Rate limiting (withRateLimit)
2. Middle: CSRF protection (withCsrf)
3. Innermost: Route handler (with auth check inside)
4. Reason for order: Rate limit first to block brute force before processing CSRF
Correct pattern:export const POST = withRateLimit( withCsrf( async (req) => { // Auth check here const { userId } = await auth() if (!userId) return Response.json({ error: 'Unauthorized' }, { status: 401 })
// Authorization check here // Handler logic here } ) );
**Why This Order Matters**:
- Rate limiting outermost: Block attackers before they consume resources
- CSRF middle: Verify legitimate origin after rate check
- Handler innermost: Process request only after all security checks pass
**Validation Criteria**:
After implementation, I should be able to:
1. Verify rate limiting blocks excessive requests first
2. Verify CSRF protection works after rate limit
3. Verify authentication checked before handler logic
4. Verify authorization checked after authentication
5. Confirm middleware compose correctly without conflicts
6. Test that removing any layer causes security failure
Generate the endpoint with properly ordered security middleware.
Reference:
@lib/withRateLimit.ts
@lib/withCsrf.ts
@lib/validateRequest.tsCustomization Tips
Add more middleware: Insert additional layers in correct order
Change ordering: Only if you have specific reasons (document why!)
Conditional middleware: Apply different stacks for GET vs POST
Testing Checklist
- [ ] Middleware order correct
- [ ] Rate limiting first
- [ ] CSRF after rate limiting
- [ ] Auth inside handler
- [ ] All layers tested independently
- [ ] Combined layers work together
Common Mistakes
❌ Wrong Order:
// WRONG - CSRF before rate limit
export const POST = withCsrf(withRateLimit(handler))✅ Correct Order:
// CORRECT - Rate limit before CSRF
export const POST = withRateLimit(withCsrf(handler))Related Prompts
- Individual layers: See other prompt-engineering prompts
- Testing:
prompt-engineering/08_security_testing.md
Version History
v1.0 (2025-10-21): Initial version
Extending Security Architecture with New Control
Category: Prompt Engineering When to Use: Adding security controls not in Secure Vibe Coding OS Module: 3.3 Time to Implement: 60 minutes
What This Creates
- ✅ New security utility
- ✅ Composable with existing middleware
- ✅ Maintains architecture patterns
- ✅ TypeScript typed
- ✅ Tested and documented
The Prompt
I need to add [new security control name] to Secure Vibe Coding OS.
**Security Foundation Reference**:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Current security stack: CSRF, rate limiting, input validation, auth, headers
- New control fits at: [which layer? Layer 1-5]
**New Security Control Requirements**:
- Name: [descriptive name, e.g., geoBlocking, deviceFingerprinting]
- Purpose: [what attack does it prevent?]
- Implementation: [how should it work?]
- Integration: [how does it fit with existing controls?]
**Maintain Architecture Consistency**:
- Follow existing middleware pattern (higher-order function)
- Accept configuration options like other middlewares
- Return composable function
- Include proper TypeScript types
- Add error handling using handleApiError()
- Log security events for monitoring
**Implementation Steps**:
1. Create new utility file: `lib/[controlName].ts`
2. Implement as composable middleware following existing patterns
3. Add TypeScript types in `lib/types.ts`
4. Include configuration options
5. Add to security architecture docs
6. Create test cases in `__tests__/lib/[controlName].test.ts`
7. Update `.cursor/rules/security_rules.mdc` with usage examples
**Example Signature** (follow this pattern):export function with[ControlName]( handler: (req: Request) => Promise<Response>, options?: [ControlName]Options ): (req: Request) => Promise<Response>
**Verification**:
- New control composable with existing middleware
- Maintains OWASP score (doesn't introduce new vulnerabilities)
- Works in development and production environments
- Properly tested with 80%+ coverage
- Documentation updated
- Can be used like: withRateLimit(with[NewControl](handler))
Generate the new security control following Secure Vibe Coding OS patterns.
Reference:
@lib/withRateLimit.ts (as example pattern)
@lib/withCsrf.ts (as example pattern)
@lib/types.ts
@docs/security/SECURITY_ARCHITECTURE.mdExample New Controls
Geo-blocking: Block requests from certain countries
Device Fingerprinting: Track suspicious login patterns
Content Security Policy Nonce: Dynamic CSP nonce generation
API Key Authentication: Machine-to-machine API auth
Customization Tips
Study existing utilities: Look at withRateLimit and withCsrf for patterns
Keep it composable: Must work with other middleware
Type everything: TypeScript types prevent bugs
Testing Checklist
- [ ] Middleware composes correctly
- [ ] Configuration options work
- [ ] Error handling functions
- [ ] TypeScript types correct
- [ ] Tests pass (80%+ coverage)
- [ ] Documentation complete
Related Prompts
- Testing:
prompt-engineering/08_security_testing.md - Middleware order:
prompt-engineering/06_composable_middleware.md
Version History
v1.0 (2025-10-21): Initial version
Comprehensive Security Testing
Category: Prompt Engineering When to Use: After implementing features, before deployment Module: 3.3 Time to Implement: 30 minutes
Test Coverage
- ✅ Authentication tests
- ✅ Authorization tests
- ✅ CSRF tests
- ✅ Rate limiting tests
- ✅ Input validation tests
- ✅ Error handling tests
The Prompt
I've implemented [feature name] with security controls. Generate comprehensive security tests.
**Security Foundation Reference**:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Feature: [what you built]
- Security controls applied: [list them]
**Generate Tests For**:
1. **Authentication Tests**:
- Valid authentication allows access
- Missing auth token returns 401
- Expired auth token returns 401
- Tampered auth token returns 401
2. **Authorization Tests**:
- User can access their own resources
- User cannot access other users' resources (403)
- Admin can access admin resources
- Non-admin cannot access admin resources (403)
3. **CSRF Tests**:
- Request with valid CSRF token succeeds
- Request with missing CSRF token returns 403
- Request with invalid CSRF token returns 403
- GET requests don't require CSRF (read-only)
4. **Rate Limiting Tests**:
- Requests under limit succeed
- Requests over limit return 429
- Rate limit resets after window expires
- Different users have separate rate limit buckets
5. **Input Validation Tests**:
- Valid input accepted
- Invalid input returns 400 with clear message
- XSS payloads sanitized: `<script>alert('xss')</script>`
- SQL injection attempts blocked: `'; DROP TABLE users;--`
- Oversized input rejected (length limits enforced)
6. **Error Handling Tests**:
- Errors in production don't leak stack traces
- Errors in production don't leak file paths
- Errors in production don't leak environment variables
- Error responses use generic messages
**Test Implementation**:
- Use Jest or Vitest for test framework
- Use supertest for HTTP testing
- Mock authentication (Clerk) for testing
- Mock database (Convex) for isolation
- Test both success and failure cases
- Measure code coverage (aim for 80%+ on security utilities)
Generate test file at `__tests__/api/[feature].security.test.ts` with all test cases.Customization Tips
Add feature-specific tests: Include tests for your specific functionality
Change test framework: Adapt for your testing setup
Add performance tests: Test response times under load
Testing Checklist
- [ ] All authentication tests pass
- [ ] All authorization tests pass
- [ ] CSRF protection verified
- [ ] Rate limiting verified
- [ ] Input validation verified
- [ ] Error handling verified
- [ ] 80%+ code coverage
Related Prompts
- Code review:
threat-modeling/04_code_review.md - Threat model:
threat-modeling/01_stride_analysis.md
Version History
v1.0 (2025-10-21): Initial version
Security Prompts Skills
Converted from: .claude/security-prompts/ (original prompt library) Converted on: 2025-10-23 Total Templates: 23 security prompt templates Format: Claude Code Skills with automatic trigger activation
---
What Changed
Before (Prompt Library)
- Location:
.claude/security-prompts/ - Format: Markdown files organized by category
- Usage: Manual copy-paste from files
- Discovery: Browse README or files manually
- Agent Access: Agents had to know exact paths
After (Skills System)
- Location:
.claude/skills/security/security-prompts/ - Format: Skills with SKILL.md + template files
- Usage: Automatic activation via trigger keywords
- Discovery: Keywords automatically trigger appropriate skill
- Agent Access: Agents can reference skills by name or keyword
---
Structure
.claude/skills/security/security-prompts/
├── SKILL.md # Main skill (overview & directory)
│
├── prompt-engineering/ # 8 comprehensive templates
│ ├── SKILL.md # Category skill
│ ├── 01_secure_form.md
│ ├── 02_authenticated_endpoint.md
│ ├── 03_public_endpoint.md
│ ├── 04_admin_action.md
│ ├── 05_file_upload.md
│ ├── 06_composable_middleware.md
│ ├── 07_new_control.md
│ └── 08_security_testing.md
│
├── threat-modeling/ # 8 analysis templates
│ ├── SKILL.md # Category skill
│ ├── 01_stride_analysis.md
│ ├── 02_feature_threats.md
│ ├── 03_architecture_impact.md
│ ├── 04_code_review.md
│ ├── 05_security_tests.md
│ ├── 06_owasp_check.md
│ ├── 07_payment_security.md
│ └── 08_update_model.md
│
├── auth-authorization/ # 4 auth/authz templates
│ ├── SKILL.md # Category skill
│ ├── 01_rbac_implementation.md
│ ├── 02_permissions.md
│ ├── 03_ownership.md
│ └── 04_auth_testing.md
│
└── built-in-controls/ # 3 simple templates
├── SKILL.md # Category skill
├── 01_contact_form.md
├── 02_authenticated_update.md
└── 03_public_api.md---
How to Use
For Users (Automatic Activation)
Simply mention trigger keywords and the skill activates:
Example 1:
User: "I need to add a secure contact form"
→ Triggers: security-prompts skill
→ Claude suggests: built-in-controls/01_contact_form.mdExample 2:
User: "Help me implement RBAC with Clerk"
→ Triggers: security-prompts-auth skill
→ Claude suggests: auth-authorization/01_rbac_implementation.mdExample 3:
User: "I need to do a STRIDE threat model"
→ Triggers: security-prompts-threat-modeling skill
→ Claude suggests: threat-modeling/01_stride_analysis.mdFor Agents (Explicit Reference)
Agents can reference skills directly:
# In agent instructions
"Use security prompt templates from the security-prompts skill to guide implementation"
# Load specific template
"Apply the RBAC template from:
.claude/skills/security/security-prompts/auth-authorization/01_rbac_implementation.md"
# Reference by trigger
"Use the admin action security template to implement this feature"For Skills (Chaining)
Skills can reference each other:
# In a security implementation skill
"For authentication setup, reference the security-prompts-auth skill templates"
# Chain multiple skills
"First use security-prompts-auth for RBAC, then security-prompts-engineering for the feature"---
Trigger Keywords by Category
Main Skill (security-prompts)
Triggers when mentioning:
- "security prompt"
- "secure form"
- "RBAC"
- "threat model"
- "STRIDE"
- "admin endpoint"
- "file upload"
- "security testing"
- "code review"
- "OWASP"
Prompt Engineering (security-prompts-engineering)
Specific triggers:
- "secure form" / "contact form"
- "authenticated endpoint" / "user update"
- "public endpoint" / "public API"
- "admin action" / "admin feature"
- "file upload" / "image upload"
- "composable middleware" / "security layers"
- "new security control" / "custom middleware"
- "security testing" / "test security"
Threat Modeling (security-prompts-threat-modeling)
Specific triggers:
- "STRIDE" / "threat model"
- "feature threats" / "analyze feature"
- "architecture security" / "security impact"
- "security review" / "code review"
- "OWASP" / "OWASP compliance"
- "payment security" / "Stripe security"
- "update threat model"
Auth & Authorization (security-prompts-auth)
Specific triggers:
- "RBAC" / "role-based access"
- "permissions" / "permission system"
- "ownership" / "ownership check"
- "auth testing" / "authorization tests"
Built-In Controls (security-prompts-controls)
Specific triggers:
- "contact form" / "simple form"
- "authenticated update" / "update profile"
- "public API" / "read-only API"
---
Integration Examples
Example 1: Security-Aware Agent
# .claude/agents/secure-feature-builder.md
---
name: secure-feature-builder
description: Builds features with security-first approach using security-prompts skill
---
When implementing features:
1. **Identify feature type**
- Form, API, auth, admin, file upload
2. **Load security-prompts skill template**
- Use trigger keywords or direct file reference
- Customize template for user's needs
3. **Generate implementation**
- Follow template security controls
- Apply testing checklist
4. **Recommend related templates**
- Testing templates
- Threat model updatesExample 2: Course Lesson Using Security Prompts
# In course-lesson-builder skill
When teaching secure feature implementation:
**Show students the security prompt to use:**
"Prompt to Claude Code:"I need to implement a contact form with full security controls.
Use the security prompt template for secure forms.
Reference: @docs/security/SECURITY_ARCHITECTURE.md
This triggers the security-prompts skill automatically.Example 3: Security Orchestrator Agent
# In security-orchestrator agent
When conducting security assessment:
Step 1: Threat Model
→ Use template: security-prompts/threat-modeling/01_stride_analysis.md
Step 2: Code Review
→ Use template: security-prompts/threat-modeling/04_code_review.md
Step 3: OWASP Check
→ Use template: security-prompts/threat-modeling/06_owasp_check.md---
Migration Guide
For Existing Code References
If you have existing references to .claude/security-prompts/:
Option 1: Update to new path
# Old
.claude/security-prompts/prompt-engineering/01_secure_form.md
# New
.claude/skills/security/security-prompts/prompt-engineering/01_secure_form.mdOption 2: Use trigger keywords (recommended)
# Instead of referencing path
"Use the secure form security template"
# Automatically activates skillFor Agents
Update agent instructions:
Old approach:
"Read prompt from .claude/security-prompts/..."New approach:
"Use security-prompts skill template for [feature type]"For Course Content
Update module references:
Old:
See: `.claude/security-prompts/README.md`New:
Skills Triggered: Keywords like "secure form", "RBAC", "STRIDE" activate security-prompts skill automatically.---
Benefits of Skills Format
1. Automatic Activation
- No need to know exact paths
- Keywords trigger appropriate templates
- Contextual suggestions
2. Better Discovery
- Claude suggests relevant templates
- Trigger keywords guide users
- Related templates linked
3. Agent Integration
- Agents can reference by name
- Skills can chain together
- Easier orchestration
4. Maintainability
- Centralized in skills directory
- Clear skill boundaries
- Version tracking per skill
5. Composability
- Skills reference each other
- Build complex workflows
- Reusable patterns
---
Maintenance
Adding New Templates
1. Add template file to appropriate category directory 2. Update category SKILL.md with new template info 3. Update main SKILL.md quick reference 4. Add trigger keywords to skill description 5. Link related templates
Updating Existing Templates
1. Modify template file in place 2. Update version history in template 3. Update SKILL.md if triggers/usage changed 4. Test with real implementation
Deprecating Templates
1. Mark as deprecated in template and SKILL.md 2. Provide migration path to new template 3. Keep file for backwards compatibility 4. Remove trigger keywords to prevent activation
---
Testing the Skills
Test Automatic Activation
Ask Claude:
"I need to add a contact form"
→ Should suggest built-in-controls/01_contact_form.md
"Help me implement RBAC"
→ Should suggest auth-authorization/01_rbac_implementation.md
"I need to create a threat model"
→ Should suggest threat-modeling/01_stride_analysis.mdTest Agent References
In agent:
"Use security-prompts skill for implementation guidance"
→ Should load appropriate templatesTest Skill Chaining
Request complex feature:
"I need an admin dashboard with RBAC"
→ Should suggest:
1. auth-authorization/01_rbac_implementation.md
2. prompt-engineering/04_admin_action.md
3. prompt-engineering/08_security_testing.md---
Related Skills
Works With
- course-lesson-builder - Teaching security using prompts
- security/* - Implementation-focused security skills
- security-awareness/* - Understanding vulnerability patterns
- threat-modeler (agent) - Using threat modeling templates
- security-scanner (agent) - Using review templates
- security-reporter (agent) - Using reporting templates
Complements
- csrf-protection - Deep dive on CSRF
- rate-limiting - Deep dive on rate limiting
- input-validation - Deep dive on validation
- auth-security - Deep dive on Clerk auth
- security-testing - Deep dive on testing
---
Troubleshooting
Skill Not Activating
Problem: Trigger keywords not working
Solution: 1. Check keyword spelling matches SKILL.md 2. Try more specific keywords 3. Use direct file reference 4. Check skill is in .claude/skills/
Wrong Template Suggested
Problem: Claude suggests incorrect template
Solution: 1. Be more specific in request 2. Mention category explicitly 3. Reference template directly 4. Provide more context
Agent Can't Find Template
Problem: Agent can't access skill
Solution: 1. Use full path: .claude/skills/security/security-prompts/[category]/[file].md 2. Reference skill name: security-prompts-[category] 3. Check agent has Read tool access 4. Verify file exists
---
Version History
v1.0 (2025-10-23): Initial conversion from prompt library to skills
- Converted 23 prompt templates
- Created 5 skill files (main + 4 categories)
- Added trigger keywords for automatic activation
- Integrated with agent system
- Added usage examples and migration guide
---
Original Prompt Library
The original prompt library remains at .claude/security-prompts/ for reference and backwards compatibility. The new skills system in .claude/skills/security/security-prompts/ is the recommended approach going forward.
Original location: .claude/security-prompts/ Original documentation: .claude/security-prompts/README.md
---
Questions?
For issues or suggestions: 1. Check this README 2. Review category SKILL.md files 3. Reference original prompt documentation 4. Test with trigger keywords
---
Pro Tip: Let trigger keywords do the work! Instead of remembering paths, just describe what you need: "secure contact form", "implement RBAC", "threat model", etc. The skills system will guide you to the right template.
STRIDE Threat Model
Category: Threat Modeling When to Use: After architecture design, before building features Module: 3.5 Time to Implement: 60 minutes
Analysis Coverage
- ✅ Spoofing threats
- ✅ Tampering threats
- ✅ Repudiation threats
- ✅ Information Disclosure
- ✅ Denial of Service
- ✅ Elevation of Privilege
The Prompt
I need a comprehensive threat model for my application using the STRIDE methodology.
**Application Context**:
- App: [Your app description, e.g., "SaaS project management tool"]
- Users: [Who uses it, e.g., "Teams of 5-50 people, authenticated users"]
- Key Features: [List main features, e.g., "Task management, file uploads, team chat, admin dashboard"]
- Architecture: Secure Vibe Coding OS (90/100 OWASP score baseline)
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Stack: Next.js, Clerk (auth), Convex (database), Stripe (payments via Clerk Billing)
- Security controls: CSRF protection, rate limiting, input validation, secure error handling, security headers
**Assets to Protect** (what attackers want):
1. User authentication credentials
2. User personal data (names, emails, project data)
3. Payment information (handled by Stripe, not stored by us)
4. API keys and environment variables
5. Admin access privileges
6. File uploads (project documents)
**Threat Analysis Needed**:
For each STRIDE category, identify:
1. **Specific threats** to my application
2. **Attack scenarios** - how would the attack happen?
3. **Existing mitigations** - which Secure Vibe Coding OS controls already prevent this?
4. **Gaps** - what additional protections are needed?
5. **Priority** - Critical/High/Medium/Low based on likelihood and impact
**STRIDE Categories**:
**Spoofing (Identity)**:
- How could attackers fake authentication?
- Session hijacking possibilities?
- Token theft scenarios?
**Tampering (Data)**:
- How could attackers modify data they don't own?
- SQL injection possibilities (even with Convex)?
- XSS attack vectors?
- CSRF vulnerabilities in forms?
**Repudiation (Non-repudiation)**:
- Can users deny actions they took?
- Are admin actions logged?
- Is there an audit trail for sensitive operations?
**Information Disclosure (Confidentiality)**:
- How could attackers steal user data?
- Error messages leaking information?
- API endpoints exposing sensitive data?
- Database query vulnerabilities?
**Denial of Service (Availability)**:
- How could attackers make the app unavailable?
- Rate limiting gaps?
- Resource exhaustion attacks?
- Webhook flooding?
**Elevation of Privilege (Authorization)**:
- How could regular users become admins?
- Authorization bypass scenarios?
- Ownership checks missing?
- Role escalation vectors?
**Output Format**:
For each threat identified, provide:THREAT: [Name] STRIDE Category: [S/T/R/I/D/E] Description: [What is the threat?] Attack Scenario: [How would attacker exploit this?] Existing Mitigation: [Which Secure Vibe Coding OS control prevents this?] Additional Mitigation Needed: [What else should be added?] Priority: [Critical/High/Medium/Low]
Generate a complete threat model covering all STRIDE categories for my application.Customization Tips
Your app details: Replace all placeholders with your actual app info
Your assets: List what's valuable in your app
Your features: Focus threats on your specific features
Deliverables
- [ ] Complete STRIDE analysis document
- [ ] 15-30 threats identified
- [ ] Attack scenarios documented
- [ ] Mitigations mapped
- [ ] Priorities assigned
- [ ] Save to:
docs/security/THREAT_MODEL.md
Related Prompts
- Feature threats:
threat-modeling/02_feature_threats.md - Update model:
threat-modeling/08_update_model.md
Version History
v1.0 (2025-10-21): Initial version
Feature-Specific Threat Analysis
Category: Threat Modeling When to Use: Before implementing each new feature Module: 3.5 Time to Implement: 20 minutes
Analysis Focus
- ✅ Feature-specific threats
- ✅ Attack scenarios
- ✅ Mitigation strategies
- ✅ Risk assessment
- ✅ Security requirements
The Prompt
I'm about to implement [feature name]. Identify security threats specific to this feature before I start coding.
**Feature Description**:
- What: [What does this feature do?]
- Who: [Who can use it? Public, authenticated, admin?]
- Data: [What data does it handle?]
- Actions: [What actions can users perform?]
**Current Security Context**:
- Architecture: Secure Vibe Coding OS (90/100 OWASP baseline)
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Existing threat model: @docs/security/THREAT_MODEL.md
**Threat Analysis Needed**:
**1. Feature-Specific Threats**:
Using STRIDE methodology, identify threats specific to THIS feature:
- Spoofing: How could attackers impersonate users in this feature?
- Tampering: How could they modify data they shouldn't?
- Repudiation: Could users deny actions?
- Information Disclosure: What sensitive data could leak?
- Denial of Service: How could they make this feature unavailable?
- Elevation of Privilege: Could they gain unauthorized access?
**2. Attack Scenarios**:
For each threat, provide:
- Detailed attack scenario (step-by-step)
- Attacker motivation (what do they gain?)
- Likelihood (High/Medium/Low)
- Impact (Critical/High/Medium/Low)
**3. Existing Mitigations**:
Which Secure Vibe Coding OS controls already prevent these threats?
- CSRF protection?
- Rate limiting?
- Input validation?
- Authentication/Authorization?
- Error handling?
**4. Additional Security Needed**:
What additional controls should be implemented for this feature?
- New validation rules?
- Additional authorization checks?
- Feature-specific rate limits?
- Audit logging?
- Data encryption?
**5. Implementation Guidance**:
Provide security requirements I should include when prompting Claude to build this feature.
**Output Format**:THREAT: [Name] STRIDE: [Category] Attack Scenario: [How it would happen] Likelihood: [High/Medium/Low] Impact: [Critical/High/Medium/Low] Existing Mitigation: [What already prevents this] Additional Mitigation: [What to add] Implementation Note: [Security requirement for feature prompt]
Generate threat analysis for this specific feature.Customization Tips
Feature complexity: More complex features = more threats to consider
Data sensitivity: Sensitive data requires deeper analysis
User type: Public features have different threats than admin features
Deliverables
- [ ] Feature threat list (5-10 threats)
- [ ] Attack scenarios documented
- [ ] Risk ratings assigned
- [ ] Mitigations identified
- [ ] Implementation guidance provided
- [ ] Save to feature documentation
Integration
Use threat analysis when: 1. Before coding: Inform your implementation prompt 2. During coding: Verify controls implemented 3. After coding: Update main threat model
Related Prompts
- Main threat model:
threat-modeling/01_stride_analysis.md - Update model:
threat-modeling/08_update_model.md - Code review:
threat-modeling/04_code_review.md
Version History
v1.0 (2025-10-21): Initial version
Architecture Change Security Impact Analysis
Category: Threat Modeling When to Use: Before making architectural changes Module: 3.5 Time to Implement: 30 minutes
Analysis Coverage
- ✅ New attack vectors
- ✅ Threat model impact
- ✅ Security control changes
- ✅ Configuration security
- ✅ Net security impact
The Prompt
I'm considering an architecture change and need to assess the security impact before proceeding.
**Current Architecture**:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Current security posture: 90/100 OWASP score
- Existing threat model: @docs/security/THREAT_MODEL.md
**Proposed Change**:
[Describe the change, e.g., "Adding Redis for session storage and rate limiting", "Migrating from Convex to PostgreSQL", "Adding external API integration"]
**Change Details**:
- Why: [Reason for change]
- What: [Technical details]
- How: [Implementation plan]
- Timeline: [When this will happen]
**Security Impact Assessment Needed**:
**1. New Attack Vectors**:
What new threats does this introduce?
- New services exposed?
- New network boundaries?
- New dependencies?
- New credentials to manage?
- New failure modes?
**2. Threat Model Updates**:
Which existing threats are affected?
- Does this change any STRIDE threat mitigations?
- Are new STRIDE threats introduced?
- Does this amplify any existing threats?
**3. Security Control Changes**:
How do existing controls need updating?
- Authentication changes needed?
- Authorization changes needed?
- Encryption requirements?
- Access control for new components?
- Logging and monitoring updates?
**4. Configuration Security**:
What security settings are needed for new components?
- TLS/SSL configuration?
- Authentication setup?
- Network restrictions (firewall, IP whitelist)?
- Credential management?
- Key rotation policy?
- Backup and recovery security?
**5. Testing Requirements**:
How to verify security isn't degraded?
- What to test after migration?
- How to verify encryption works?
- How to test failover scenarios?
- Performance impact on security controls?
**6. Rollback Plan**:
If security is degraded:
- How to quickly rollback?
- What's the rollback window?
- How to verify security restored?
**Compare Security Posture**:
- Security before change: [Current state]
- Security after change: [Projected state]
- Net security impact: [Better/Same/Worse? Why?]
- Recommendation: [Proceed/Modify/Cancel?]
Generate comprehensive security impact analysis for this architecture change.
Reference:
@docs/security/SECURITY_ARCHITECTURE.md
@docs/security/THREAT_MODEL.mdExample Changes
Adding Redis:
- New: Network service, credentials, connection security
- Benefits: Distributed rate limiting, better session storage
- Risks: Redis vulnerabilities, credential theft, network exposure
Migrating Database:
- New: Different query patterns, different security model
- Benefits: Better performance, more features
- Risks: Migration errors, data exposure, query injection
Adding External API:
- New: Third-party dependency, API keys, webhook security
- Benefits: New functionality, reduced development
- Risks: API compromise, data leakage to third party
Deliverables
- [ ] New attack vectors identified
- [ ] Threat model update required
- [ ] Security control changes documented
- [ ] Configuration requirements listed
- [ ] Testing plan created
- [ ] Rollback plan documented
- [ ] Go/no-go recommendation
Decision Framework
Proceed if:
- Net security impact: Better or Same
- All new threats can be mitigated
- Team understands security requirements
Modify if:
- Some security concerns but change is valuable
- Can add additional controls to compensate
- Timeline allows for security improvements
Cancel if:
- Net security impact: Significantly worse
- Cannot mitigate new threats
- Security degradation unacceptable
Related Prompts
- Threat model:
threat-modeling/01_stride_analysis.md - Update model:
threat-modeling/08_update_model.md
Version History
v1.0 (2025-10-21): Initial version
Security Code Review
Category: Threat Modeling When to Use: After implementing features, before deployment Module: 3.5 Time to Implement: 30 minutes
Review Coverage
- ✅ Authentication & Authorization
- ✅ Input Validation
- ✅ Security Middleware
- ✅ Error Handling
- ✅ Data Protection
- ✅ OWASP Top 10
The Prompt
Review this code for security vulnerabilities and alignment with Secure Vibe Coding OS security architecture.
**Code to Review**:
[Paste your code or reference file path]
**Security Review Checklist**:
**1. Authentication & Authorization**:
- [ ] Authentication required where needed?
- [ ] Clerk session properly checked?
- [ ] Authorization checks present (user can only access own resources)?
- [ ] Admin role verification if admin-only endpoint?
- [ ] 401 returned for unauthenticated requests?
- [ ] 403 returned for unauthorized requests?
**2. Input Validation & Sanitization**:
- [ ] All user input validated with Zod schemas?
- [ ] XSS prevention (safeTextSchema used for text fields)?
- [ ] SQL injection prevention (parameterized queries)?
- [ ] File upload validation (type, size, signature)?
- [ ] Length limits enforced?
- [ ] Type coercion prevented?
**3. Security Middleware**:
- [ ] CSRF protection applied (withCsrf) for state-changing operations?
- [ ] Rate limiting applied (withRateLimit)?
- [ ] Middleware composed in correct order (rate limit → CSRF → handler)?
- [ ] GET requests don't use CSRF (read-only operations)?
**4. Error Handling**:
- [ ] Errors use handleApiError() for secure responses?
- [ ] Stack traces not leaked in production?
- [ ] Error messages generic to users?
- [ ] Detailed errors logged server-side?
- [ ] No sensitive data in error responses?
**5. Data Protection**:
- [ ] Sensitive data encrypted at rest?
- [ ] HTTPS enforced in production?
- [ ] API keys in environment variables, not code?
- [ ] Secrets never logged?
- [ ] Database queries follow least privilege?
**6. OWASP Top 10**:
- [ ] Injection prevention (A03:2021)?
- [ ] Broken authentication prevention (A07:2021)?
- [ ] Sensitive data exposure prevention (A02:2021)?
- [ ] XML external entities prevention (A04:2021)?
- [ ] Broken access control prevention (A01:2021)?
- [ ] Security misconfiguration prevention (A05:2021)?
- [ ] XSS prevention (A03:2021)?
- [ ] Insecure deserialization prevention (A08:2021)?
- [ ] Using components with known vulnerabilities prevention (A06:2021)?
- [ ] Insufficient logging & monitoring prevention (A09:2021)?
**For Each Vulnerability Found, Provide**:
- Severity: Critical / High / Medium / Low
- Category: Which OWASP Top 10 or security control
- Attack Scenario: How could this be exploited?
- Current Code: What's wrong
- Secure Fix: How to fix it
- Code Example: Show the secure implementation
**Additional Analysis**:
- Are there any logic flaws that could lead to security issues?
- Are there any race conditions?
- Are there any timing vulnerabilities?
- Is the code following Secure Vibe Coding OS patterns?
Generate comprehensive security review report.
Context: This code is built on Secure Vibe Coding OS with:
- 90/100 OWASP baseline score
- CSRF protection, rate limiting, input validation
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
Focus on:
- Proper use of existing security utilities
- Feature-specific vulnerabilities
- Gaps in the security controlsCustomization Tips
Focus areas: Add specific concerns for your code type
Code context: Provide info about what the code does
Review depth: Adjust checklist for complexity
Deliverables
- [ ] Security review report
- [ ] List of vulnerabilities
- [ ] Severity ratings
- [ ] Fix recommendations
- [ ] Code examples
- [ ] Save to:
docs/security/CODE_REVIEW_[date].md
Related Prompts
- Security tests:
prompt-engineering/08_security_testing.md - Threat model:
threat-modeling/01_stride_analysis.md
Version History
v1.0 (2025-10-21): Initial version
Automated Security Test Generation
Category: Threat Modeling When to Use: Generate comprehensive test suites Module: 3.5 Time to Implement: 30 minutes
Test Coverage
- ✅ 20+ security test cases
- ✅ Authentication tests
- ✅ CSRF protection tests
- ✅ Rate limiting tests
- ✅ Input validation tests
- ✅ Error handling tests
The Prompt
Generate comprehensive security test suite for [feature name].
**Feature Context**:
- Feature: [What you built]
- Endpoints: [List API routes]
- Security controls applied: [List them]
**Security Foundation Reference**:
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Testing framework: [Jest/Vitest/etc]
**Generate Tests For**:
**1. Authentication Tests** (if applicable):describe('Authentication', () => { test('allows access with valid token') test('returns 401 with missing token') test('returns 401 with expired token') test('returns 401 with invalid token') test('returns 401 with tampered token') })
**2. Authorization Tests** (if applicable):describe('Authorization', () => { test('user can access own resources') test('user cannot access other users resources (403)') test('admin can access all resources') test('non-admin cannot access admin resources (403)') test('ownership check prevents unauthorized access') })
**3. CSRF Protection Tests**:describe('CSRF Protection', () => { test('POST succeeds with valid CSRF token') test('POST fails with missing CSRF token (403)') test('POST fails with invalid CSRF token (403)') test('GET requests do not require CSRF token') test('CSRF token expires correctly') })
**4. Rate Limiting Tests**:describe('Rate Limiting', () => { test('requests under limit succeed') test('requests over limit return 429') test('rate limit resets after time window') test('different users have separate rate limits') test('rate limit headers included in response') })
**5. Input Validation Tests**:describe('Input Validation', () => { test('valid input is accepted') test('invalid input returns 400 with error message') test('XSS payloads are sanitized: <script>alert("xss")</script>') test('SQL injection blocked: "; DROP TABLE users;--') test('oversized input rejected (length limits)') test('wrong data types rejected') test('missing required fields rejected') })
**6. Error Handling Tests**:describe('Error Handling', () => { test('production errors do not leak stack traces') test('production errors do not leak file paths') test('production errors do not leak environment variables') test('error responses use generic messages') test('detailed errors logged server-side only') })
**7. Security Headers Tests**:describe('Security Headers', () => { test('Content-Security-Policy header present') test('X-Frame-Options header present') test('X-Content-Type-Options header present') test('Strict-Transport-Security header present in production') })
**Test Implementation Requirements**:
- Use [Jest/Vitest] for test framework
- Use supertest for HTTP testing
- Mock Clerk authentication
- Mock database (Convex)
- Test both success and failure cases
- Aim for 80%+ code coverage on security utilities
- Include setup and teardown
- Use descriptive test names
- Group related tests in describe blocks
**Output**:
Generate complete test file at `__tests__/api/[feature].security.test.ts` with:
- All test cases implemented
- Proper mocking
- Clear assertions
- Comments explaining security aspects being tested
Generate comprehensive security test suite now.Test File Structure
import { describe, test, expect, beforeEach, afterEach } from 'vitest'
import { mockAuth, mockDatabase } from './test-utils'
describe('[Feature] Security Tests', () => {
beforeEach(() => {
// Setup
})
afterEach(() => {
// Cleanup
})
describe('Authentication', () => {
// Auth tests
})
describe('CSRF Protection', () => {
// CSRF tests
})
// More test groups...
})Running Tests
# Run all tests
npm test
# Run security tests only
npm test -- security.test.ts
# Run with coverage
npm test -- --coverage
# Watch mode
npm test -- --watchDeliverables
- [ ] Complete test file generated
- [ ] All 20+ test cases implemented
- [ ] Tests passing
- [ ] 80%+ code coverage
- [ ] Mocks working correctly
- [ ] Edge cases covered
Testing Checklist
After generating tests:
- [ ] All tests pass
- [ ] Coverage meets target (80%+)
- [ ] Tests cover happy path
- [ ] Tests cover error cases
- [ ] Tests cover edge cases
- [ ] Tests are maintainable
- [ ] Tests run quickly (<5 seconds)
Related Prompts
- Code review:
threat-modeling/04_code_review.md - Manual testing:
prompt-engineering/08_security_testing.md
Version History
v1.0 (2025-10-21): Initial version
OWASP Top 10 Compliance Check
Category: Threat Modeling When to Use: Before production launch, quarterly reviews Module: 3.5 Time to Implement: 30 minutes
Compliance Coverage
- ✅ OWASP Top 10 2021
- ✅ Category-by-category scoring
- ✅ Gap analysis
- ✅ Recommendations
- ✅ Priority ranking
The Prompt
Assess my application's compliance with OWASP Top 10 2021 security standards.
**Application Context**:
- App: [Your application name and description]
- Architecture: Secure Vibe Coding OS (90/100 baseline)
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
- Threat Model: @docs/security/THREAT_MODEL.md
**OWASP Top 10 2021 Assessment**:
For each category, provide:
1. Compliance Score (0-10, 10 = fully compliant)
2. Controls in Place (what protects against this)
3. Gaps Identified (what's missing or weak)
4. Risk Level (Critical/High/Medium/Low)
5. Recommendations (specific improvements)
**A01:2021 – Broken Access Control**:
- Do users only access their own data?
- Is authorization checked on every request?
- Are there IDOR vulnerabilities?
- Can users escalate privileges?
**A02:2021 – Cryptographic Failures**:
- Is sensitive data encrypted at rest?
- Is HTTPS enforced everywhere?
- Are strong algorithms used?
- Are API keys and secrets protected?
**A03:2021 – Injection**:
- Is all input validated?
- Are parameterized queries used?
- Is XSS prevented?
- Are command injections blocked?
**A04:2021 – Insecure Design**:
- Is there a threat model?
- Are security requirements defined?
- Is defense-in-depth implemented?
- Are security patterns followed?
**A05:2021 – Security Misconfiguration**:
- Are defaults secure?
- Are error messages generic?
- Are unnecessary features disabled?
- Is the tech stack hardened?
**A06:2021 – Vulnerable and Outdated Components**:
- Are dependencies up to date?
- Are vulnerability scans automated?
- Is there a patching process?
- Are component versions tracked?
**A07:2021 – Identification and Authentication Failures**:
- Is authentication secure (using Clerk)?
- Are sessions managed properly?
- Is MFA available?
- Are passwords handled securely?
**A08:2021 – Software and Data Integrity Failures**:
- Are updates verified?
- Is code integrity checked?
- Are CI/CD pipelines secure?
- Are webhooks verified?
**A09:2021 – Security Logging and Monitoring Failures**:
- Are security events logged?
- Is there alerting on attacks?
- Are logs protected?
- Is audit trail complete?
**A10:2021 – Server-Side Request Forgery (SSRF)**:
- Is user input used in URLs?
- Are external requests validated?
- Is network access restricted?
- Are redirects validated?
**Summary Report**:Overall OWASP Score: [X/100] Baseline (Secure Vibe Coding OS): 90/100 Your Implementation: [X/100]
Critical Gaps: [List] High Priority: [List] Medium Priority: [List] Low Priority: [List]
Top 3 Recommendations: 1. [Most important improvement] 2. [Second most important] 3. [Third most important]
Generate complete OWASP Top 10 compliance assessment.Score Interpretation
90-100: Excellent - Production ready 80-89: Good - Minor improvements needed 70-79: Fair - Several gaps to address 60-69: Poor - Significant work required Below 60: Critical - Not production ready
Deliverables
- [ ] OWASP Top 10 assessment complete
- [ ] Score for each category
- [ ] Overall compliance score
- [ ] Gap analysis documented
- [ ] Prioritized recommendations
- [ ] Action plan created
- [ ] Save to:
docs/security/OWASP_ASSESSMENT.md
Action Plan Template
Based on assessment results:
Immediate (Critical):
- [ ] [Fix critical gaps]
- [ ] Timeline: [Within 1 week]
Short-term (High Priority):
- [ ] [Address high priority items]
- [ ] Timeline: [Within 1 month]
Medium-term (Medium Priority):
- [ ] [Improve medium priority areas]
- [ ] Timeline: [Within 3 months]
Long-term (Low Priority):
- [ ] [Optimize low priority items]
- [ ] Timeline: [Within 6 months]
Review Schedule
Quarterly Reviews:
- Re-run OWASP assessment
- Track score changes
- Update action plan
- Document improvements
Trigger Reviews:
- Major architecture changes
- New feature launches
- Security incidents
- Dependency updates
Related Prompts
- Threat model:
threat-modeling/01_stride_analysis.md - Code review:
threat-modeling/04_code_review.md - Payment security:
threat-modeling/07_payment_security.md
Version History
v1.0 (2025-10-21): Initial version
Payment Security Assessment (Clerk Billing + Stripe)
Category: Threat Modeling When to Use: If using Clerk Billing + Stripe for payments Module: 3.5 Time to Implement: 30 minutes
Security Coverage
- ✅ PCI-DSS concepts compliance
- ✅ No card data on server
- ✅ Webhook security
- ✅ Stripe integration security
- ✅ Common pitfalls avoided
The Prompt
Assess the security of my payment implementation using Clerk Billing and Stripe.
**Payment Implementation Context**:
- Payment Provider: Clerk Billing + Stripe
- Features: [e.g., subscriptions, one-time payments, usage-based billing]
- Architecture: Secure Vibe Coding OS
- Reference: @docs/security/SECURITY_ARCHITECTURE.md
**PCI-DSS Concepts Assessment**:
Important: You are NOT handling credit cards directly (Stripe does), so full PCI-DSS compliance is not required. However, verify these security concepts:
**1. Card Data Handling**:
Critical Questions:
- Does any cardholder data ever touch my server? [MUST BE NO]
- Are payment forms hosted by Stripe Checkout? [MUST BE YES]
- Is card data collected client-side and sent directly to Stripe? [MUST BE YES]
- Do server logs ever contain card numbers? [MUST BE NO]
- Is card data ever stored in my database? [MUST BE NO]
**2. Webhook Security**:
Stripe sends webhooks for payment events. Verify:
- Are webhook signatures validated using Stripe's library?
- Are webhook endpoints protected from replay attacks?
- Is webhook processing idempotent (handle duplicates)?
- Are webhook secrets stored securely (env variables)?
- Are failed webhooks logged and alerted?
**3. HTTPS Everywhere**:
- Is HTTPS enforced on all pages?
- Are cookies Secure and HttpOnly?
- Is HSTS header present?
- Are API calls to Stripe over HTTPS?
**4. Subscription Security**:
- Can users only cancel their own subscriptions?
- Are subscription changes authorized?
- Are subscription status checks server-side?
- Is subscription data in sync with Stripe?
**5. API Key Security**:
- Are Stripe API keys in environment variables?
- Are publishable and secret keys used correctly?
- Are test and live keys separated?
- Are keys never exposed client-side (except publishable key)?
- Is key rotation planned?
**6. Error Handling**:
- Do payment errors leak sensitive information?
- Are Stripe error messages sanitized for users?
- Are payment failures logged securely?
- Are declined cards handled gracefully?
**7. Access Control**:
- Can users only access their own payment history?
- Are admin payment operations logged?
- Is payment data properly authorized?
**Common Payment Implementation Pitfalls**:
Check for these mistakes:
- ❌ Collecting card data on your own forms
- ❌ Storing CVV codes (NEVER allowed)
- ❌ Not validating webhook signatures
- ❌ Exposing secret API keys client-side
- ❌ Using test keys in production
- ❌ Not handling webhook retries
- ❌ Trusting client-side payment status
- ❌ Missing HTTPS on payment pages
- ❌ Logging card numbers
- ❌ No idempotency for webhooks
**Security Checklist**:
Verify each item:
- [ ] NO card data touches our server
- [ ] All payment forms use Stripe Checkout or Elements
- [ ] Webhook signatures validated
- [ ] HTTPS enforced everywhere
- [ ] API keys in environment variables
- [ ] Publishable key used client-side only
- [ ] Secret key used server-side only
- [ ] Webhook processing is idempotent
- [ ] Failed payments logged
- [ ] Users can only access own payment data
- [ ] Payment errors don't leak info
- [ ] Subscription changes authorized
- [ ] Test keys not in production
- [ ] Key rotation process exists
**Assessment Output**:
Provide:
1. Security Score (0-100)
2. Critical Issues (must fix before launch)
3. High Priority Issues (fix soon)
4. Medium Priority Issues (improve over time)
5. Best Practices Followed
6. Recommendations
Generate complete payment security assessment.
Reference:
@docs/security/SECURITY_ARCHITECTURE.md
[Your Clerk Billing integration code]
[Your webhook handlers]Red Flags
Immediate Action Required:
- 🚨 Card data on your server
- 🚨 Unvalidated webhooks
- 🚨 Secret keys exposed
- 🚨 No HTTPS on payment pages
Deliverables
- [ ] Payment security assessment complete
- [ ] PCI-DSS concepts verified
- [ ] Webhook security confirmed
- [ ] Critical issues identified
- [ ] Recommendations provided
- [ ] Save to:
docs/security/PAYMENT_SECURITY_ASSESSMENT.md
Best Practices
Do:
- ✅ Use Stripe Checkout (easiest, most secure)
- ✅ Validate all webhook signatures
- ✅ Handle webhook retries with idempotency
- ✅ Store only Stripe IDs, not card data
- ✅ Use different keys for test and production
- ✅ Log payment events for debugging
Don't:
- ❌ Touch card data ever
- ❌ Store CVV codes (illegal)
- ❌ Trust client-side payment status
- ❌ Use test keys in production
- ❌ Expose secret keys client-side
- ❌ Log sensitive payment details
Testing Payment Security
# Test webhook signature validation
curl -X POST http://localhost:3000/api/webhooks/stripe \
-H "Content-Type: application/json" \
-H "stripe-signature: fake_signature" \
-d '{"type": "payment_intent.succeeded"}'
# Expected: 400 Bad Request (invalid signature)
# Test with valid signature (use Stripe CLI)
stripe listen --forward-to localhost:3000/api/webhooks/stripe
stripe trigger payment_intent.succeeded
# Expected: 200 OK, webhook processedRelated Prompts
- OWASP check:
threat-modeling/06_owasp_check.md - Code review:
threat-modeling/04_code_review.md
Version History
v1.0 (2025-10-21): Initial version
Update Threat Model for New Feature
Category: Threat Modeling When to Use: After each feature to keep threat model current Module: 3.5 Time to Implement: 20 minutes
Update Coverage
- ✅ New assets
- ✅ New threats
- ✅ New attack surface
- ✅ Security controls verification
- ✅ Residual risk assessment
The Prompt
Update my application's threat model to include the new feature I just built.
**Current Threat Model**: @docs/security/THREAT_MODEL.md
**New Feature**: [Description of what you added]
**Update Requirements**:
**1. New Assets**:
- What new data/resources does this feature introduce?
- What's the value of these assets to attackers?
**2. New Threats**:
- What new STRIDE threats does this feature introduce?
- Attack scenarios specific to this feature?
**3. New Attack Surface**:
- What new endpoints/interfaces are exposed?
- What new user input is accepted?
**4. Security Controls**:
- What security controls were applied to this feature?
- Do existing controls adequately mitigate new threats?
**5. Residual Risk**:
- Are there threats that aren't fully mitigated?
- What's the acceptable risk level?
- What monitoring is needed?
**Integration with Existing Threat Model**:
- How does this feature interact with existing threats?
- Does it amplify any existing risks?
- Does it provide new attack paths to existing assets?
**Updated Threat Model Output**:
Update @docs/security/THREAT_MODEL.md with:
- New threats section for this feature
- Updated asset inventory
- Updated attack surface map
- Updated STRIDE analysis
- New recommendations if any gaps identified
- Version number increment (e.g., v1.2 → v1.3)
- Changelog documenting what changed
Generate updated threat model content I can add to my document.Customization Tips
Feature details: Describe what you built specifically
Threat focus: Highlight concerns for this feature type
Integration: Note how feature connects to existing app
Deliverables
- [ ] Updated threat model content
- [ ] New threats documented
- [ ] Updated asset inventory
- [ ] Version incremented
- [ ] Changelog added
- [ ] Updated in:
docs/security/THREAT_MODEL.md
Related Prompts
- Initial model:
threat-modeling/01_stride_analysis.md - Feature threats:
threat-modeling/02_feature_threats.md
Version History
v1.0 (2025-10-21): Initial version