| name | security-audit |
| description | Comprehensive security audit for OWASP Top 10, secrets detection, and vulnerability analysis. Use when auditing security, checking for vulnerabilities, or preparing for security reviews. |
Security Audit Report
Scope: $0 (options: all, owasp, secrets, dependencies, auth, input-validation - default: all)
Module: $1 (if empty, audit entire project)
1. OWASP Top 10 (2021) Analysis
1.1 A01:2021 - Broken Access Control
Check for:
- โ Missing authorization checks in controllers/use cases
- โ Insecure direct object references (IDOR)
- โ Missing role-based access control (RBAC)
- โ Elevation of privilege vulnerabilities
Analyze:
@Get(':id')
async getOrder(@Param('id') id: string) {
return this.orderService.findById(id);
}
@Get(':id')
@UseGuards(JwtAuthGuard, OrderOwnershipGuard)
async getOrder(@Param('id') id: string, @CurrentUser() user: User) {
return this.orderService.findById(id, user.id);
}
Search patterns:
- Controllers with @Get, @Post, @Put, @Delete without @UseGuards
- Use cases accepting userId but not validating ownership
- Admin-only operations without role checks
1.2 A02:2021 - Cryptographic Failures
Check for:
- โ Passwords stored in plain text
- โ Weak hashing algorithms (MD5, SHA1)
- โ Sensitive data in logs
- โ Unencrypted data transmission
- โ Hardcoded secrets/keys
Analyze:
const user = { password: dto.password };
const hashedPassword = await bcrypt.hash(dto.password, 10);
const user = { password: hashedPassword };
Search for:
console.log with sensitive data (passwords, tokens, credit cards)
- Database schemas storing sensitive fields without encryption
- HTTP URLs instead of HTTPS
- JWT secrets in code instead of environment variables
1.3 A03:2021 - Injection
Check for:
- โ SQL Injection (if using raw queries)
- โ NoSQL Injection (MongoDB query injection)
- โ Command Injection (shell commands with user input)
- โ Code Injection (eval, Function constructor)
Analyze:
SQL/NoSQL Injection:
async findByUsername(username: string) {
return this.model.find({ username: username });
}
async findByUsername(username: string) {
if (typeof username !== 'string') {
throw new BadRequestException('Invalid username');
}
return this.model.findOne({ username });
}
Command Injection:
exec(`convert ${userFileName} output.pdf`);
const sanitized = sanitizeFileName(userFileName);
execFile('convert', [sanitized, 'output.pdf']);
Search for:
exec(), execSync(), spawn() with user input
- Raw MongoDB queries:
db.collection.find({ $where: ... })
- String concatenation in database queries
eval(), Function() constructor usage
1.4 A04:2021 - Insecure Design
Check for:
- โ Missing rate limiting
- โ No request throttling
- โ Unlimited file upload sizes
- โ Missing input validation
- โ Lack of defense in depth
Analyze:
@Post('login')
async login(@Body() dto: LoginDto) {
return this.authService.login(dto);
}
@Post('login')
@UseGuards(ThrottlerGuard)
@Throttle(5, 60)
async login(@Body() dto: LoginDto) {
return this.authService.login(dto);
}
Search for:
- Authentication endpoints without rate limiting
- File upload endpoints without size limits
- Missing CORS configuration
- No request size limits
1.5 A05:2021 - Security Misconfiguration
Check for:
- โ Debug mode enabled in production
- โ Default credentials
- โ Unnecessary features enabled
- โ Missing security headers
- โ Verbose error messages exposing internals
Analyze:
Error Handling:
@Catch()
export class GlobalExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
return {
message: exception.message,
stack: exception.stack,
};
}
}
@Catch()
export class GlobalExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
this.logger.error(exception);
return {
message: 'An error occurred',
code: exception.code,
};
}
}
Security Headers:
- Helmet.js configured?
- CORS properly restricted?
- CSP (Content Security Policy) set?
Search for:
NODE_ENV=development in production
- Default admin passwords
- Enabled Swagger in production
- Missing helmet() middleware
1.6 A06:2021 - Vulnerable and Outdated Components
Check for:
- โ Outdated dependencies with known vulnerabilities
- โ Unused dependencies
- โ Dependencies from untrusted sources
Run:
npm audit
npm outdated
Analyze results:
- Critical vulnerabilities (fix immediately)
- High vulnerabilities (fix soon)
- Dependency tree depth (supply chain risk)
1.7 A07:2021 - Identification and Authentication Failures
Check for:
- โ Weak password requirements
- โ No account lockout after failed attempts
- โ Session IDs in URLs
- โ Missing multi-factor authentication
- โ Predictable session tokens
Analyze:
@IsString()
password: string;
@IsString()
@MinLength(12)
@Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/, {
message: 'Password must contain uppercase, lowercase, number, and special character',
})
password: string;
JWT Security:
jwt.sign(payload, 'secret', { expiresIn: '30d' });
jwt.sign(payload, process.env.JWT_SECRET, {
expiresIn: '15m',
algorithm: 'HS256',
});
Search for:
- Password fields without validation
- JWT tokens without expiration
- Sessions without timeout
- No CSRF protection
1.8 A08:2021 - Software and Data Integrity Failures
Check for:
- โ Unsigned/unverified packages
- โ Auto-deploy without CI/CD verification
- โ Insecure deserialization
- โ Missing integrity checks on updates
Analyze:
const obj = JSON.parse(userInput);
const schema = z.object({ });
const obj = schema.parse(JSON.parse(userInput));
Search for:
JSON.parse() on untrusted input without validation
eval() or Function() with external data
- Package-lock.json committed and verified?
1.9 A09:2021 - Security Logging and Monitoring Failures
Check for:
- โ No logging of security events
- โ Logs with insufficient detail
- โ No alerting on suspicious activity
- โ Logs stored insecurely
Analyze:
async login(dto: LoginDto) {
return this.authService.login(dto);
}
async login(dto: LoginDto) {
try {
const result = await this.authService.login(dto);
this.logger.log(`Successful login: ${dto.username}`);
return result;
} catch (error) {
this.logger.warn(`Failed login attempt: ${dto.username}`);
throw error;
}
}
Log checklist:
- โ
Failed login attempts
- โ
Authorization failures
- โ
Input validation failures
- โ
Suspicious patterns (SQL injection attempts)
- โ Don't log passwords, tokens, or sensitive data
1.10 A10:2021 - Server-Side Request Forgery (SSRF)
Check for:
- โ User-controlled URLs in HTTP requests
- โ No URL validation/whitelist
- โ Internal network access from user input
Analyze:
async fetchUrl(@Body('url') url: string) {
return axios.get(url);
}
async fetchUrl(@Body('url') url: string) {
const allowed = ['https://api.example.com'];
const urlObj = new URL(url);
if (!allowed.includes(urlObj.origin)) {
throw new BadRequestException('URL not allowed');
}
return axios.get(url);
}
Search for:
axios.get(userInput)
fetch(userInput)
- HTTP requests with user-controlled URLs
2. Secrets Detection
Scan for hardcoded secrets:
2.1 Common Secret Patterns
Search codebase for:
- โ API keys:
api_key, apiKey, API_KEY
- โ Passwords:
password =, pwd =
- โ JWT secrets:
jwt.sign(*, 'secret')
- โ Database URLs:
mongodb://user:pass@
- โ AWS credentials:
AKIA[0-9A-Z]{16}
- โ Private keys:
BEGIN PRIVATE KEY
- โ OAuth tokens:
access_token, refresh_token
2.2 Environment Variables
Check .env files:
git ls-files | grep '\.env$'
.env
.env.local
.env.*.local
Verify all secrets use environment variables:
const secret = 'my-secret-key-12345';
const secret = process.env.JWT_SECRET;
if (!process.env.JWT_SECRET) {
throw new Error('JWT_SECRET is required');
}
2.3 Git History
Check for secrets in git history:
git log -p | grep -i 'password\|secret\|api_key'
3. Input Validation
Check all entry points:
3.1 HTTP Controllers
Verify DTOs have validation:
export class CreateOrderDto {
customerId: string;
items: any[];
}
export class CreateOrderDto {
@IsString()
@IsNotEmpty()
@IsUUID()
customerId: string;
@IsArray()
@ArrayMinSize(1)
@ValidateNested({ each: true })
@Type(() => OrderItemDto)
items: OrderItemDto[];
@IsNumber()
@Min(0)
@Max(1000000)
total: number;
}
3.2 Validation Gaps
Search for:
- Controllers without
ValidationPipe
- DTOs without
class-validator decorators
- Any type usage:
any, object
- Missing sanitization on string inputs
4. Authentication & Authorization
4.1 Authentication Review
Check:
- โ
Passport strategy configured correctly?
- โ
JWT tokens properly validated?
- โ
Password hashing uses bcrypt/argon2?
- โ Passwords stored in plain text?
- โ Session fixation vulnerabilities?
4.2 Authorization Review
Check:
- โ
Guards applied to protected routes?
- โ
Role-based access control implemented?
- โ
Resource ownership verified?
- โ Missing authorization checks?
- โ Privilege escalation possible?
Pattern to check:
@Delete(':id')
async delete(@Param('id') id: string) {
return this.service.delete(id);
}
@Delete(':id')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin', 'owner')
async delete(@Param('id') id: string, @User() user) {
return this.service.delete(id, user.id);
}
5. Dependency Security
5.1 NPM Audit
Run security audit:
npm audit --json
Analyze:
- Critical: Fix immediately
- High: Fix within 1 week
- Medium: Fix within 1 month
- Low: Monitor and fix when convenient
5.2 Known Vulnerabilities
Check:
npm ls for dependency tree
- Vulnerable packages identified
- Unused dependencies removed
6. Infrastructure Security
6.1 CORS Configuration
app.enableCors({ origin: '*' });
app.enableCors({
origin: process.env.ALLOWED_ORIGINS?.split(','),
credentials: true,
});
6.2 Rate Limiting
imports: [
ThrottlerModule.forRoot({
ttl: 60,
limit: 10,
}),
];
Output Format
๐ Security Score
Overall: 0-100%
- OWASP Compliance: X%
- Secrets Detection: Pass/Fail
- Input Validation: X%
- Authentication: X%
- Dependencies: X vulnerabilities
๐จ Critical Issues (Fix Immediately)
For each critical issue:
Severity: CRITICAL
Category: [OWASP Category]
Location: src/path/to/file.ts:line
Issue: [Description]
Impact: [Security impact]
Exploit: [How this can be exploited]
Fix: [Specific fix with code example]
โ ๏ธ High Priority Issues
๐ Medium Priority Issues
๐ก Recommendations
๐ Compliance Checklist
Provide actionable security report with:
- Specific file locations and line numbers
- Code examples showing vulnerabilities
- Fixed code examples
- Commands to run for remediation
- Priority ranking for fixes