Node.js Security Audit
Structured security audit for Node.js HTTP servers and web applications.
Audit Checklist
Critical (Must Fix Before Deploy)
Hardcoded Secrets
- Search for: API keys, passwords, tokens in source code
- Pattern:
grep -rn "password\|secret\|token\|apikey\|api_key" --include="*.js" --include="*.ts" | grep -v node_modules | grep -v "process.env\|\.env"
- Fix: Move to env vars, fail if missing:
if (!process.env.SECRET) process.exit(1);
XSS in Dynamic Content
- Search for:
innerHTML, template literals injected into DOM, unsanitized user input in responses
- Fix: Use
textContent, or escape: str.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":"'"}[c]))
SQL/NoSQL Injection
- Search for: String concatenation in queries,
eval(), Function() with user input
- Fix: Parameterized queries, input validation
High (Should Fix)
CORS Misconfiguration
- Search for:
Access-Control-Allow-Origin: *
- Fix: Allowlist specific origins:
const origin = ALLOWED.has(req.headers.origin) ? req.headers.origin : ALLOWED.values().next().value
Auth Bypass
- Check: Every route that should require auth actually checks it
- Common miss: Static file routes, agent/webhook endpoints, health checks that expose data
Path Traversal
- Check:
path.normalize() + startsWith(allowedDir) on all file-serving routes
- Extra: Resolve symlinks with
fs.realpathSync() and re-check
Medium (Recommended)
Security Headers
const HEADERS = {
'X-Frame-Options': 'SAMEORIGIN',
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
};
// Apply to all responses
Rate Limiting
const attempts = new Map(); // ip -> { count, resetAt }
const LIMIT = 5, WINDOW = 60000;
function isLimited(ip) {
const now = Date.now(), e = attempts.get(ip);
if (!e || now > e.resetAt) { attempts.set(ip, {count:1, resetAt:now+WINDOW}); return false; }
return ++e.count > LIMIT;
}
Input Validation
- Body size limits:
if (bodySize > 1048576) { req.destroy(); return; }
- JSON parse in try/catch
- Type checking on expected fields
Low (Consider)
Dependency Audit: npm audit
Error Leakage: Don't send stack traces to clients in production
Cookie Security: HttpOnly; Secure; SameSite=Strict
Report Format
## Security Audit: [filename]
### Critical
1. **[Category]** Description — File:Line — Fix: ...
### High
...
### Medium
...
### Low
...
### Summary
X critical, X high, X medium, X low
1---2name: nodejs-security-audit3description: Audit Node.js HTTP servers and web apps for security vulnerabilities. Checks OWASP Top 10, CORS, auth bypass, XSS, path traversal, hardcoded secrets, missing headers, rate limiting, and input validation. Use when reviewing server code before deployment or after changes.4---5
6# Node.js Security Audit
7
8Structured security audit for Node.js HTTP servers and web applications.
9
10## Audit Checklist
11
12### Critical (Must Fix Before Deploy)
13
14**Hardcoded Secrets**
15- Search for: API keys, passwords, tokens in source code
16- Pattern: `grep -rn "password\|secret\|token\|apikey\|api_key" --include="*.js" --include="*.ts" | grep -v node_modules | grep -v "process.env\|\.env"`
17- Fix: Move to env vars, fail if missing: `if (!process.env.SECRET) process.exit(1);`
18
19**XSS in Dynamic Content**
20- Search for: `innerHTML`, template literals injected into DOM, unsanitized user input in responses
21- Fix: Use `textContent`, or escape: `str.replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":"'"}[c]))`
22
23**SQL/NoSQL Injection**
24- Search for: String concatenation in queries, `eval()`, `Function()` with user input
25- Fix: Parameterized queries, input validation
26
27### High (Should Fix)
28
29**CORS Misconfiguration**
30- Search for: `Access-Control-Allow-Origin: *`
31- Fix: Allowlist specific origins: `const origin = ALLOWED.has(req.headers.origin) ? req.headers.origin : ALLOWED.values().next().value`
32
33**Auth Bypass**
34- Check: Every route that should require auth actually checks it
35- Common miss: Static file routes, agent/webhook endpoints, health checks that expose data
36
37**Path Traversal**
38- Check: `path.normalize()` + `startsWith(allowedDir)` on all file-serving routes
39- Extra: Resolve symlinks with `fs.realpathSync()` and re-check
40
41### Medium (Recommended)
42
43**Security Headers**
44```javascript
45const HEADERS = {
46 'X-Frame-Options': 'SAMEORIGIN',
47 'X-Content-Type-Options': 'nosniff',
48 'Referrer-Policy': 'strict-origin-when-cross-origin',
49 'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
50};
51// Apply to all responses
52```
53
54**Rate Limiting**
55```javascript
56const attempts = new Map(); // ip -> { count, resetAt }
57const LIMIT = 5, WINDOW = 60000;
58function isLimited(ip) {
59 const now = Date.now(), e = attempts.get(ip);
60 if (!e || now > e.resetAt) { attempts.set(ip, {count:1, resetAt:now+WINDOW}); return false; }
61 return ++e.count > LIMIT;
62}
63```
64
65**Input Validation**
66- Body size limits: `if (bodySize > 1048576) { req.destroy(); return; }`
67- JSON parse in try/catch
68- Type checking on expected fields
69
70### Low (Consider)
71
72**Dependency Audit:** `npm audit`
73**Error Leakage:** Don't send stack traces to clients in production
74**Cookie Security:** `HttpOnly; Secure; SameSite=Strict`
75
76## Report Format
77
78```
79## Security Audit: [filename]
80
81### Critical
821. **[Category]** Description — File:Line — Fix: ...
83
84### High
85...
86
87### Medium
88...
89
90### Low
91...
92
93### Summary
94X critical, X high, X medium, X low
95```