086
LVL 04 — SENIOR-IN-TRAININGSESSION 086DAY 86

SECURITY AUDIT

🎫 PIXELCRAFT-072
🐛Security | 🔴 Expert | Priority: 🔴 Critical

A penetration test found 5 vulnerabilities in PixelCraft. XSS in image titles, unrestricted file upload, exposed secrets, missing CSRF protection, wide-open CORS. Fix all five. Harden the entire application.
CONCEPTS.UNLOCKED
💉
XSS (Cross-Site Scripting)
Injecting scripts into pages other users see. If image titles aren't escaped, an attacker can inject <script> tags. Every user who views that image runs the attacker's code.
🔄
CSRF & CORS
CSRF: tricking users into making requests they didn't intend. CORS: controlling which domains can call your API. Misconfigure CORS (origin: *) and you've opened the door to CSRF attacks.
📁
Insecure File Upload
Don't trust file extensions. An attacker renames malware.exe to photo.jpg. Validate magic bytes (file signature), not just the extension. Restrict file size and content type at the binary level.
🔑
Exposed Secrets
API keys, JWT secrets, database URLs in code. If they're in your source code, they're in your git history forever. Move everything to environment variables. Rotate compromised secrets immediately.
🪖
Helmet.js & CSP
Security headers in one line. Helmet sets X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security, and Content-Security-Policy. CSP blocks inline scripts — the most effective XSS defense.
📋
OWASP Top 10
The 10 most critical web security risks. Injection, broken auth, sensitive data exposure, XSS, insecure deserialization. The industry-standard checklist every developer should know.
HANDS-ON.TASKS
01
Vulnerability 1: Fix XSS
// ❌ BEFORE: raw HTML injection <h2>{image.title}</h2> // If title is: <script>steal()</script> // → XSS! Script runs in every user's browser // ✅ React auto-escapes by default // But watch for dangerouslySetInnerHTML: // NEVER use it with user input // Server-side: sanitize on input const sanitizeHtml = require('sanitize-html'); const cleanTitle = sanitizeHtml( req.body.title, { allowedTags: [], // No HTML allowedAttributes: {} // Nothing });
02
Vulnerability 2: Validate File Magic Bytes
const fileType = require('file-type-cjs'); async function validateImageFile( filePath ) { const type = await fileType.fromFile(filePath); const ALLOWED_TYPES = [ 'image/jpeg', 'image/png', 'image/webp', 'image/gif', ]; if (!type || !ALLOWED_TYPES.includes(type.mime)) { // Delete the uploaded file fs.unlinkSync(filePath); throw new Error( 'Invalid file type. ' + 'Only images allowed.'); } return type; } // Use in upload route app.post('/api/images/upload', authenticate, upload.single('image'), async (req, res) => { await validateImageFile( req.file.path); // ... proceed with valid image });
Magic bytes are the first few bytes of a file that identify its format. JPEG starts with FF D8 FF. PNG starts with 89 50 4E 47. Extensions lie. Magic bytes don't.
03
Vulnerability 3: Helmet + CSP
npm install helmet const helmet = require('helmet'); app.use(helmet()); // Custom Content Security Policy app.use(helmet.contentSecurityPolicy({ directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'"], styleSrc: [ "'self'", "https://fonts.googleapis.com" ], imgSrc: [ "'self'", "data:", "blob:" ], connectSrc: [ "'self'", "wss://pixelcraft.app" // WebSocket ], fontSrc: [ "'self'", "https://fonts.gstatic.com" ], objectSrc: ["'none'"], upgradeInsecureRequests: [], } }));
04
Vulnerability 4: Fix CORS & Secrets
// ❌ BEFORE: wide open app.use(cors({ origin: '*' })); // ✅ AFTER: whitelist specific origins app.use(cors({ origin: [ process.env.FRONTEND_URL, 'https://pixelcraft.app', ], credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], })); // Move ALL secrets to .env // .env (NEVER commit this file) DATABASE_URL=mongodb://... JWT_SECRET=generated-random-64-chars RESEND_API_KEY=re_... REDIS_URL=redis://... // .gitignore .env .env.local .env.production
05
Vulnerability 5: Rate Limit Auth Endpoints
// Stricter rate limiting for auth async function authRateLimit( req, res, next ) { const key = `auth-limit:${req.ip}`; const current = await redis.incr(key); if (current === 1) { await redis.expire(key, 900); // 15-minute window } if (current > 10) { // 10 attempts per 15 minutes return res.status(429).json({ error: 'Too many login attempts. ' + 'Try again in 15 minutes.', }); } next(); } app.use('/api/auth/login', authRateLimit); app.use('/api/auth/forgot-password', authRateLimit);
06
Close the Ticket
git switch -c fix/PIXELCRAFT-072-security-audit git add server/ .gitignore git commit -m "Fix 5 security vulnerabilities (PIXELCRAFT-072)" git push origin fix/PIXELCRAFT-072-security-audit # PR → Security review → Merge → Close ticket ✅
CS.DEEP-DIVE

Security is not a feature — it's a constraint on every feature.

The OWASP Top 10 has barely changed in 20 years. The same classes of vulnerabilities keep appearing because developers keep making the same mistakes.

// OWASP Top 10 (2021):

A01 Broken Access Control
A02 Cryptographic Failures
A03 Injection (SQL, XSS, etc.)
A04 Insecure Design
A05 Security Misconfiguration
A06 Vulnerable Components
A07 Auth & Identity Failures
A08 Data Integrity Failures
A09 Logging & Monitoring Failures
A10 SSRF (Server-Side Request Forgery)

// You fixed: A03 (XSS), A05 (CORS,
// headers), A02 (secrets), A07 (rate
// limit), A04 (file upload).
// Security is a mindset, not a task.
"Security Lab"
[A]Run npm audit and fix all reported vulnerabilities. Set up Dependabot or Snyk to auto-detect vulnerable dependencies in CI. Security is ongoing, not one-time.
[B]Add account lockout: after 5 failed login attempts, lock the account for 30 minutes. Send an email notification to the user. Track failed attempts in Redis with TTL.
[C]Research: what is SSRF (Server-Side Request Forgery)? How did the Capital One breach happen? Could PixelCraft's image URL fetching feature be exploited? Write a threat model document.
REF.MATERIAL
ARTICLE
OWASP Foundation
The definitive list of web application security risks. Every web developer should know this list by heart.
OWASPOFFICIALESSENTIAL
VIDEO
Fireship
Quick overview of common web vulnerabilities: XSS, CSRF, injection, and how to prevent them. Practical and visual.
SECURITYQUICK
ARTICLE
Helmet.js Team
Security headers for Express: CSP, HSTS, X-Frame-Options, and more. One middleware, 11 security headers.
HELMETOFFICIAL
ARTICLE
OWASP Foundation
Practical security guides: XSS prevention, CSRF prevention, password storage, session management. Quick-reference security patterns.
OWASPCHEATSHEETESSENTIAL
VIDEO
Computerphile
How XSS works, why it's dangerous, and how to prevent it. Clear explanation with real-world examples from a security researcher.
XSSVISUAL
// LEAVE EXCITED BECAUSE
Five vulnerabilities found, five vulnerabilities fixed. Helmet sets security headers. CSP blocks XSS. Magic bytes catch fake uploads. Secrets are in .env. Auth endpoints are rate-limited. Your app is hardened.