Security and Hardening
Overview
Security-first development practices for web applications. Treat every external input as hostile, every secret as sacred, and every authorization check as mandatory. Security isn't a phase — it's a constraint on every line of code that touches user data, authentication, or external systems.
When to Use
- Building anything that accepts user input
- Implementing authentication or authorization
- Storing or transmitting sensitive data
- Integrating with external APIs or services
- Adding file uploads, webhooks, or callbacks
- Handling payment or PII data
Process: Threat Model First
Controls bolted on without a threat model are guesses. Before hardening, spend five minutes thinking like an attacker:
- Map the trust boundaries. Where does untrusted data cross into your system? HTTP requests, form fields, file uploads, webhooks, third-party APIs, message queues, and LLM output. Every boundary is attack surface.
- Name the assets. What's worth stealing or breaking? Credentials, PII, payment data, admin actions, money movement.
- Run STRIDE over each boundary — a quick lens, not a ceremony:
| Threat |
Ask |
Typical mitigation |
| Spoofing |
Can someone impersonate a user/service? |
Authentication, signature verification |
| Tampering |
Can data be altered in transit or at rest? |
Integrity checks, parameterized queries, HTTPS |
| Repudiation |
Can an action be denied later? |
Audit logging of security events |
| Information disclosure |
Can data leak? |
Encryption, field allowlists, generic errors |
| Denial of service |
Can it be overwhelmed? |
Rate limiting, input size caps, timeouts |
| Elevation of privilege |
Can a user gain rights they shouldn't? |
Authorization checks, least privilege |
- Write abuse cases next to use cases. For each feature, ask "how would I misuse this?" — then make that your first test.
If you can't name the trust boundaries for a feature, you're not ready to secure it. This is OWASP A04: Insecure Design — most breaches begin in design, not code.
The Three-Tier Boundary System
Always Do (No Exceptions)
- Validate all external input at the system boundary (API routes, form handlers)
- Parameterize all database queries — never concatenate user input into SQL
- Encode output to prevent XSS (use framework auto-escaping, don't bypass it)
- Use HTTPS for all external communication
- Hash passwords with bcrypt/scrypt/argon2 (never store plaintext)
- Set security headers (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)
- Use httpOnly, secure, sameSite cookies for sessions
- Run the detected package manager's native audit against the committed lockfile before every release
Ask First (Requires Human Approval)
- Adding new authentication flows or changing auth logic
- Storing new categories of sensitive data (PII, payment info)
- Adding new external service integrations
- Changing CORS configuration
- Adding file upload handlers
- Modifying rate limiting or throttling
- Granting elevated permissions or roles
Never Do
- Never commit secrets to version control (API keys, passwords, tokens)
- Never log sensitive data (passwords, tokens, full credit card numbers)
- Never trust client-side validation as a security boundary
- Never disable security headers for convenience
- Never use
eval() or innerHTML with user-provided data
- Never store sessions in client-accessible storage (localStorage for auth tokens)
- Never expose stack traces or internal error details to users
OWASP Top 10 Prevention Patterns
These are prevention patterns, not a ranking. For the 2021 ordering, see the quick-reference table in references/security-checklist.md.
Injection (SQL, NoSQL, OS Command)
// BAD: SQL injection via string concatenation
const query = `SELECT * FROM users WHERE id = '${userId}'`;
// GOOD: Parameterized query
const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
// GOOD: ORM with parameterized input
const user = await prisma.user.findUnique({ where: { id: userId } });
Broken Authentication
// Password hashing
import { hash, compare } from 'bcrypt';
const SALT_ROUNDS = 12;
const hashedPassword = await hash(plaintext, SALT_ROUNDS);
const isValid = await compare(plaintext, hashedPassword);
// Session management
app.use(session({
secret: process.env.SESSION_SECRET, // From environment, not code
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true, // Not accessible via JavaScript
secure: true, // HTTPS only
sameSite: 'lax', // CSRF protection
maxAge: 24 * 60 * 60 * 1000, // 24 hours
},
}));
Cross-Site Scripting (XSS)
// BAD: Rendering user input as HTML
element.innerHTML = userInput;
// GOOD: Use framework auto-escaping (React does this by default)
return <div>{userInput}</div>;
// If you MUST render HTML, sanitize first
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(userInput);
Broken Access Control
// Always check authorization, not just authentication
app.patch('/api/tasks/:id', authenticate, async (req, res) => {
const task = await taskService.findById(req.params.id);
// Check that the authenticated user owns this resource
if (task.ownerId !== req.user.id) {
return res.status(403).json({
error: { code: 'FORBIDDEN', message: 'Not authorized to modify this task' }
});
}
// Proceed with update
const updated = await taskService.update(req.params.id, req.body);
return res.json(updated);
});
Security Misconfiguration
// Security headers (use helmet for Express)
import helmet from 'helmet';
app.use(helmet());
// Content Security Policy
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"], // Tighten if possible
imgSrc: ["'self'", 'data:', 'https:'],
connectSrc: ["'self'"],
},
}));
// CORS — restrict to known origins
app.use(cors({
origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http://localhost:3000',
credentials: true,
}));
Sensitive Data Exposure
// Never return sensitive fields in API responses
function sanitizeUser(user: UserRecord): PublicUser {
const { passwordHash, resetToken, ...publicFields } = user;
return publicFields;
}
// Use environment variables for secrets
const API_KEY = process.env.STRIPE_API_KEY;
if (!API_KEY) throw new Error('STRIPE_API_KEY not configured');
Server-Side Request Forgery (SSRF)
Read the detailed procedure and examples when working on this part of the task.
Input Validation Patterns
Schema Validation at Boundaries
import { z } from 'zod';
const CreateTaskSchema = z.object({
title: z.string().min(1).max(200).trim(),
description: z.string().max(2000).optional(),
priority: z.enum(['low', 'medium', 'high']).default('medium'),
dueDate: z.string().datetime().optional(),
});
// Validate at the route handler
app.post('/api/tasks', async (req, res) => {
const result = CreateTaskSchema.safeParse(req.body);
if (!result.success) {
return res.status(422).json({
error: {
code: 'VALIDATION_ERROR',
message: 'Invalid input',
details: result.error.flatten(),
},
});
}
// result.data is now typed and validated
const task = await taskService.create(result.data);
return res.status(201).json(task);
});
File Upload Safety
// Restrict file types and sizes
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
function validateUpload(file: UploadedFile) {
if (!ALLOWED_TYPES.includes(file.mimetype)) {
throw new ValidationError('File type not allowed');
}
if (file.size > MAX_SIZE) {
throw new ValidationError('File too large (max 5MB)');
}
// Don't trust the file extension — check magic bytes if critical
}
Triaging Dependency Audit Results
Package-manager audits report known advisories; they do not prove a package is trustworthy or that vulnerable code is reachable. Use this decision tree:
The native package-manager audit reports a vulnerability
├── Severity: critical or high
│ ├── Is the vulnerable code reachable in runtime, build, test, or deployment paths?
│ │ ├── YES --> Fix immediately (update, patch, or replace the dependency)
│ │ └── NO (confirmed unused across those paths) --> Fix soon, but not a blocker
│ └── Is a fix available?
│ ├── YES --> Update to the patched version
│ └── NO --> Check for workarounds, consider replacing the dependency, or add to allowlist with a review date
├── Severity: moderate
│ ├── Reachable in production? --> Fix in the next release cycle
│ └── Dev-only? --> Fix when convenient, track in backlog
└── Severity: low
└── Track and fix during regular dependency updates
Key questions:
- Is the vulnerable function actually called in your code path?
- Is the dependency a runtime dependency or dev-only?
- Is the vulnerability exploitable given your deployment context (e.g., a server-side vulnerability in a client-only app)?
When you defer a fix, document the reason and set a review date.
Supply-Chain Hygiene
Do not assume npm or treat the nearest manifest as the install root. Apply this order:
- Find the installation boundary and manager. Use the workspace root that owns the lockfile, or an independent nested project only when it is outside that workspace. There, corroborate
packageManager (when present), the lockfile, and CI; stop on disagreement or competing lockfiles. Pin the manager version and use the matrix in references/security-checklist.md.
- Block dependency scripts before first execution. Bootstrap with scripts disabled or a documented fail-closed policy, inspect the pending script source, approve only the minimum required packages, commit the policy, then verify with a clean frozen/immutable install. Never blanket-approve scripts.
Audits only find known advisories; they do not catch a newly malicious or typosquatted package. Therefore:
- Never apply forced audit remediation automatically (
npm audit fix --force or equivalent). Preview the remediation, read changelogs, and test each resulting upgrade; forced fixes may cross declared dependency ranges.
- Verify registry signatures and provenance where supported (
npm audit signatures, pnpm audit signatures) and treat absence as a signal to investigate, not automatic proof of compromise.
- Review new dependencies, lockfile diffs, and script-policy changes together — ownership, maintenance, release age, provenance, transitive graph, and typosquats such as
cross-env vs crossenv (OWASP A06, LLM03).
Rate Limiting
import rateLimit from 'express-rate-limit';
// General API rate limit
app.use('/api/', rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
standardHeaders: true,
legacyHeaders: false,
}));
// Stricter limit for auth endpoints
app.use('/api/auth/', rateLimit({
windowMs: 15 * 60 * 1000,
max: 10, // 10 attempts per 15 minutes
}));
Secrets Management
.env files:
├── .env.example → Committed (template with placeholder values)
├── .env → NOT committed (contains real secrets)
└── .env.local → NOT committed (local overrides)
.gitignore must include:
.env
.env.local
.env.*.local
*.pem
*.key
Always check before committing:
# Check for accidentally staged secrets
git diff --cached | grep -i "password\|secret\|api_key\|token"
If a secret is ever committed, rotate it. Deleting the line or rewriting history is not enough — assume it's compromised the moment it reaches a remote. Revoke and reissue the key first, then purge it from history.
Data Privacy & Compliance
Securing data is "can an attacker read it?" Privacy is "should we even hold it, and for how long?" — a separate question that hardening doesn't answer. The cheapest data to protect, breach, and comply over is the data you never collected. Treat personal data as a liability to minimize, not an asset to hoard.
Know what you hold. You can't protect or honor a deletion request for data you can't find. Classify fields as you add them:
| Class |
Examples |
Handling |
| Non-personal |
Aggregates, anonymized counts |
Normal handling |
| Personal (PII) |
Name, email, IP, device/user IDs |
Minimize, access-control, include in export/delete |
| Sensitive |
Health, finance, location, biometrics, gov IDs, anything about minors |
Extra basis to collect, stricter access, often encryption + audit logging |
Operating rules:
- Minimize and set a purpose. Collect a field only against a stated use. "It might be useful later" is not a purpose — it's latent breach scope. Don't log PII into telemetry (the
observability-and-instrumentation skill makes the same point from the ops side).
- Set retention up front, then actually delete. Every personal-data store needs a TTL and a working deletion path — including backups, caches, search indexes, and analytics copies. Data with no expiry is a breach scheduled for later.
- Support the data-subject rights your jurisdiction requires (GDPR/CCPA and kin): export, correct, and delete on request. These are engineering features — design the schema so a user's data is findable and erasable, not smeared irreversibly across systems.
- Get consent before collection or third-party sharing, and make it auditable. Sending PII to an analytics/ad/LLM vendor is "sharing" — the user's choice gates it, and the vendor needs a data-processing agreement.
- Localize defaults, don't hardcode one region's law. Data-residency and rules differ by user location; make the policy a configurable boundary, not an assumption.
When data crosses a trust boundary, validate it as untrusted (see Input Validation above); when a privacy incident exposes personal data, the breach-notification clock is part of the postmortem — follow the debugging-and-error-recovery skill.
Securing AI / LLM Features
If your app calls an LLM — chatbots, summarizers, agents, RAG — it inherits a new attack surface. Map it to the OWASP Top 10 for LLM Applications (2025):
- Treat all model output as untrusted input (LLM05: Improper Output Handling). Never pass LLM output straight into
eval, SQL, a shell, innerHTML, or a file path. Validate and encode it exactly as you would raw user input.
- Assume prompts can be hijacked (LLM01: Prompt Injection). Untrusted text in the context window — a user message, a fetched web page, a PDF — can carry instructions. The system prompt is not a security boundary; enforce permissions in code, not in the prompt.
- Keep secrets and other users' data out of prompts (LLM02 / LLM07). Anything in the context can be echoed back. Don't put API keys, cross-tenant data, or the full system prompt where the model can repeat it.
- Constrain tool and agent permissions (LLM06: Excessive Agency). Scope tools to the minimum, require confirmation for destructive or irreversible actions, and validate every tool argument.
- Bound consumption (LLM10: Unbounded Consumption). Cap tokens, request rate, and loop/recursion depth so a crafted input can't run up cost or hang the system.
- Isolate retrieval data (LLM08: Vector and Embedding Weaknesses). In RAG, treat the vector store as a trust boundary: partition embeddings per tenant so one user can't retrieve another's data, and validate documents before indexing so poisoned content can't steer answers.
// BAD: trusting model output as a command or as markup
const sql = await llm.generate(`Write SQL for: ${userQuestion}`);
await db.query(sql); // arbitrary query execution
container.innerHTML = await llm.reply(userMessage); // stored XSS, via the model
// GOOD: model output is data — parse defensively, then validate, then encode
let intent;
try {
intent = CommandSchema.parse(JSON.parse(await llm.replyJson(userMessage)));
} catch {
throw new ValidationError('unexpected model output'); // JSON.parse or schema failed
}
await runAllowlistedAction(intent.action, intent.params);
container.textContent = await llm.reply(userMessage);
Security Review Checklist
### Authentication
- [ ] Passwords hashed with bcrypt/scrypt/argon2 (salt rounds ≥ 12)
- [ ] Session tokens are httpOnly, secure, sameSite
- [ ] Login has rate limiting
- [ ] Password reset tokens expire
### Authorization
- [ ] Every endpoint checks user permissions
- [ ] Users can only access their own resources
- [ ] Admin actions require admin role verification
### Input
- [ ] All user input validated at the boundary
- [ ] SQL queries are parameterized
- [ ] HTML output is encoded/escaped
- [ ] Server-side URL fetches are allowlisted (no SSRF to internal services)
### Data
- [ ] No secrets in code or version control
- [ ] Sensitive fields excluded from API responses
- [ ] PII encrypted at rest (if applicable)
- [ ] Personal data is classified, collected against a stated purpose, and minimized
- [ ] Personal data has a retention limit and a working deletion path (incl. backups/indexes)
- [ ] Export/delete (data-subject) requests are supported where required; sharing with third parties has consent
### Infrastructure
- [ ] Security headers configured (CSP, HSTS, etc.)
- [ ] CORS restricted to known origins
- [ ] Dependencies audited for vulnerabilities
- [ ] Error messages don't expose internals
### Supply Chain
- [ ] One authoritative lockfile committed; CI uses that manager's frozen/immutable install
- [ ] Native audit triaged by reachability and fix risk; dependency install scripts blocked unless explicitly approved
- [ ] New dependencies reviewed (ownership, provenance, release age, transitive graph)
### AI / LLM (if used)
- [ ] Model output treated as untrusted (no eval/SQL/innerHTML/shell)
- [ ] Secrets and other users' data kept out of prompts
- [ ] Tool/agent permissions scoped; destructive actions require confirmation
See Also
For detailed security checklists and pre-commit verification steps, see references/security-checklist.md.
Common Rationalizations
| Rationalization |
Reality |
| "This is an internal tool, security doesn't matter" |
Internal tools get compromised. Attackers target the weakest link. |
| "We'll add security later" |
Security retrofitting is 10x harder than building it in. Add it now. |
| "No one would try to exploit this" |
Automated scanners will find it. Security by obscurity is not security. |
| "The framework handles security" |
Frameworks provide tools, not guarantees. You still need to use them correctly. |
| "It's just a prototype" |
Prototypes become production. Security habits from day one. |
| "Threat modeling is overkill here" |
Five minutes of "how would I attack this?" prevents the design flaws no control can patch later. |
| "It's just LLM output, it's only text" |
That "text" can be a SQL statement, a script tag, or a shell command. Treat it like any untrusted input. |
| "The audit passed, so the dependency is safe" |
Audits match known advisories. They do not detect a newly malicious package or make unreviewed install scripts safe to execute. |
| "Collect it now, we might need it later" |
Data you don't hold can't be breached, subpoenaed, or mis-deleted. "Might need it" is breach scope, not a purpose. |
| "We'll handle deletion requests manually" |
Manual erasure misses backups, caches, and analytics copies. If the schema can't find a user's data, you can't honor the request — design for it. |
| "Compliance is legal's problem, not ours" |
Export, deletion, retention, and consent are schema and code. Legal can't bolt them on after you've smeared PII across ten systems. |
Red Flags
- User input passed directly to database queries, shell commands, or HTML rendering
- Secrets in source code or commit history
- API endpoints without authentication or authorization checks
- Missing CORS configuration or wildcard (
*) origins
- No rate limiting on authentication endpoints
- Stack traces or internal errors exposed to users
- Dependencies with known critical vulnerabilities, competing lockfiles at one installation boundary, non-reproducible installs, or blanket-approved scripts
- Server fetches user-supplied URLs without an allowlist (SSRF)
- LLM/model output passed into a query, the DOM, a shell, or
eval
- Secrets, PII, or the full system prompt placed inside an LLM context window
- Personal data collected with no stated purpose, retention limit, or deletion path
- PII sent to analytics/ad/LLM vendors with no consent or data-processing agreement
- "Delete my account" that only flips a flag while the personal data lingers in stores and backups
Verification
After implementing security-relevant code:
Derived Paths and Shared Limits
Treat filenames, other processes' arguments, and job-supplied paths as untrusted
when their writers are not trusted. Before destructive operations, resolve the
target below an allowlisted root, reject the root itself, verify ownership from
trusted state, and prevent symlink/check-use races. A writable marker alone is
not authorization; failure must not fall back to a broader target.
For multi-process or serverless rate limits, use a shared store or platform limiter;
process-local counters cannot enforce one global authentication limit.
1---2name: security-and-hardening3description: Harden authentication, input handling, storage, and integrations when implementing security controls or remediating concrete vulnerabilities.4license: MIT5---6
7# Security and Hardening
8
9## Overview
10
11Security-first development practices for web applications. Treat every external input as hostile, every secret as sacred, and every authorization check as mandatory. Security isn't a phase — it's a constraint on every line of code that touches user data, authentication, or external systems.
12
13## When to Use
14
15- Building anything that accepts user input
16- Implementing authentication or authorization
17- Storing or transmitting sensitive data
18- Integrating with external APIs or services
19- Adding file uploads, webhooks, or callbacks
20- Handling payment or PII data
21
22## Process: Threat Model First
23
24Controls bolted on without a threat model are guesses. Before hardening, spend five minutes thinking like an attacker:
25
261. **Map the trust boundaries.** Where does untrusted data cross into your system? HTTP requests, form fields, file uploads, webhooks, third-party APIs, message queues, and **LLM output**. Every boundary is attack surface.
272. **Name the assets.** What's worth stealing or breaking? Credentials, PII, payment data, admin actions, money movement.
283. **Run STRIDE over each boundary** — a quick lens, not a ceremony:
29
30| Threat | Ask | Typical mitigation |
31|---|---|---|
32| **S**poofing | Can someone impersonate a user/service? | Authentication, signature verification |
33| **T**ampering | Can data be altered in transit or at rest? | Integrity checks, parameterized queries, HTTPS |
34| **R**epudiation | Can an action be denied later? | Audit logging of security events |
35| **I**nformation disclosure | Can data leak? | Encryption, field allowlists, generic errors |
36| **D**enial of service | Can it be overwhelmed? | Rate limiting, input size caps, timeouts |
37| **E**levation of privilege | Can a user gain rights they shouldn't? | Authorization checks, least privilege |
38
394. **Write abuse cases next to use cases.** For each feature, ask "how would I misuse this?" — then make that your first test.
40
41If you can't name the trust boundaries for a feature, you're not ready to secure it. This is OWASP **A04: Insecure Design** — most breaches begin in design, not code.
42
43## The Three-Tier Boundary System
44
45### Always Do (No Exceptions)
46
47- **Validate all external input** at the system boundary (API routes, form handlers)
48- **Parameterize all database queries** — never concatenate user input into SQL
49- **Encode output** to prevent XSS (use framework auto-escaping, don't bypass it)
50- **Use HTTPS** for all external communication
51- **Hash passwords** with bcrypt/scrypt/argon2 (never store plaintext)
52- **Set security headers** (CSP, HSTS, X-Frame-Options, X-Content-Type-Options)
53- **Use httpOnly, secure, sameSite cookies** for sessions
54- **Run the detected package manager's native audit** against the committed lockfile before every release
55
56### Ask First (Requires Human Approval)
57
58- Adding new authentication flows or changing auth logic
59- Storing new categories of sensitive data (PII, payment info)
60- Adding new external service integrations
61- Changing CORS configuration
62- Adding file upload handlers
63- Modifying rate limiting or throttling
64- Granting elevated permissions or roles
65
66### Never Do
67
68- **Never commit secrets** to version control (API keys, passwords, tokens)
69- **Never log sensitive data** (passwords, tokens, full credit card numbers)
70- **Never trust client-side validation** as a security boundary
71- **Never disable security headers** for convenience
72- **Never use `eval()` or `innerHTML`** with user-provided data
73- **Never store sessions in client-accessible storage** (localStorage for auth tokens)
74- **Never expose stack traces** or internal error details to users
75
76## OWASP Top 10 Prevention Patterns
77
78These are prevention patterns, not a ranking. For the 2021 ordering, see the quick-reference table in `references/security-checklist.md`.
79
80### Injection (SQL, NoSQL, OS Command)
81
82```typescript
83// BAD: SQL injection via string concatenation
84const query = `SELECT * FROM users WHERE id = '${userId}'`;
85
86// GOOD: Parameterized query
87const user = await db.query('SELECT * FROM users WHERE id = $1', [userId]);
88
89// GOOD: ORM with parameterized input
90const user = await prisma.user.findUnique({ where: { id: userId } });
91```
92
93### Broken Authentication
94
95```typescript
96// Password hashing
97import { hash, compare } from 'bcrypt';
98
99const SALT_ROUNDS = 12;
100const hashedPassword = await hash(plaintext, SALT_ROUNDS);
101const isValid = await compare(plaintext, hashedPassword);
102
103// Session management
104app.use(session({
105 secret: process.env.SESSION_SECRET, // From environment, not code
106 resave: false,
107 saveUninitialized: false,
108 cookie: {
109 httpOnly: true, // Not accessible via JavaScript
110 secure: true, // HTTPS only
111 sameSite: 'lax', // CSRF protection
112 maxAge: 24 * 60 * 60 * 1000, // 24 hours
113 },
114}));
115```
116
117### Cross-Site Scripting (XSS)
118
119```typescript
120// BAD: Rendering user input as HTML
121element.innerHTML = userInput;
122
123// GOOD: Use framework auto-escaping (React does this by default)
124return <div>{userInput}</div>;
125
126// If you MUST render HTML, sanitize first
127import DOMPurify from 'dompurify';
128const clean = DOMPurify.sanitize(userInput);
129```
130
131### Broken Access Control
132
133```typescript
134// Always check authorization, not just authentication
135app.patch('/api/tasks/:id', authenticate, async (req, res) => {
136 const task = await taskService.findById(req.params.id);
137
138 // Check that the authenticated user owns this resource
139 if (task.ownerId !== req.user.id) {
140 return res.status(403).json({
141 error: { code: 'FORBIDDEN', message: 'Not authorized to modify this task' }
142 });
143 }
144
145 // Proceed with update
146 const updated = await taskService.update(req.params.id, req.body);
147 return res.json(updated);
148});
149```
150
151### Security Misconfiguration
152
153```typescript
154// Security headers (use helmet for Express)
155import helmet from 'helmet';
156app.use(helmet());
157
158// Content Security Policy
159app.use(helmet.contentSecurityPolicy({
160 directives: {
161 defaultSrc: ["'self'"],
162 scriptSrc: ["'self'"],
163 styleSrc: ["'self'", "'unsafe-inline'"], // Tighten if possible
164 imgSrc: ["'self'", 'data:', 'https:'],
165 connectSrc: ["'self'"],
166 },
167}));
168
169// CORS — restrict to known origins
170app.use(cors({
171 origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http://localhost:3000',
172 credentials: true,
173}));
174```
175
176### Sensitive Data Exposure
177
178```typescript
179// Never return sensitive fields in API responses
180function sanitizeUser(user: UserRecord): PublicUser {
181 const { passwordHash, resetToken, ...publicFields } = user;
182 return publicFields;
183}
184
185// Use environment variables for secrets
186const API_KEY = process.env.STRIPE_API_KEY;
187if (!API_KEY) throw new Error('STRIPE_API_KEY not configured');
188```
189
190### Server-Side Request Forgery (SSRF)
191
192Read [the detailed procedure and examples](EXTENDED.md#section-1) when working on this part of the task.
193
194## Input Validation Patterns
195
196### Schema Validation at Boundaries
197
198```typescript
199import { z } from 'zod';
200
201const CreateTaskSchema = z.object({
202 title: z.string().min(1).max(200).trim(),
203 description: z.string().max(2000).optional(),
204 priority: z.enum(['low', 'medium', 'high']).default('medium'),
205 dueDate: z.string().datetime().optional(),
206});
207
208// Validate at the route handler
209app.post('/api/tasks', async (req, res) => {
210 const result = CreateTaskSchema.safeParse(req.body);
211 if (!result.success) {
212 return res.status(422).json({
213 error: {
214 code: 'VALIDATION_ERROR',
215 message: 'Invalid input',
216 details: result.error.flatten(),
217 },
218 });
219 }
220 // result.data is now typed and validated
221 const task = await taskService.create(result.data);
222 return res.status(201).json(task);
223});
224```
225
226### File Upload Safety
227
228```typescript
229// Restrict file types and sizes
230const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
231const MAX_SIZE = 5 * 1024 * 1024; // 5MB
232
233function validateUpload(file: UploadedFile) {
234 if (!ALLOWED_TYPES.includes(file.mimetype)) {
235 throw new ValidationError('File type not allowed');
236 }
237 if (file.size > MAX_SIZE) {
238 throw new ValidationError('File too large (max 5MB)');
239 }
240 // Don't trust the file extension — check magic bytes if critical
241}
242```
243
244## Triaging Dependency Audit Results
245
246Package-manager audits report known advisories; they do not prove a package is trustworthy or that vulnerable code is reachable. Use this decision tree:
247
248```
249The native package-manager audit reports a vulnerability
250├── Severity: critical or high
251│ ├── Is the vulnerable code reachable in runtime, build, test, or deployment paths?
252│ │ ├── YES --> Fix immediately (update, patch, or replace the dependency)
253│ │ └── NO (confirmed unused across those paths) --> Fix soon, but not a blocker
254│ └── Is a fix available?
255│ ├── YES --> Update to the patched version
256│ └── NO --> Check for workarounds, consider replacing the dependency, or add to allowlist with a review date
257├── Severity: moderate
258│ ├── Reachable in production? --> Fix in the next release cycle
259│ └── Dev-only? --> Fix when convenient, track in backlog
260└── Severity: low
261 └── Track and fix during regular dependency updates
262```
263
264**Key questions:**
265- Is the vulnerable function actually called in your code path?
266- Is the dependency a runtime dependency or dev-only?
267- Is the vulnerability exploitable given your deployment context (e.g., a server-side vulnerability in a client-only app)?
268
269When you defer a fix, document the reason and set a review date.
270
271### Supply-Chain Hygiene
272
273Do not assume npm or treat the nearest manifest as the install root. Apply this order:
274
2751. **Find the installation boundary and manager.** Use the workspace root that owns the lockfile, or an independent nested project only when it is outside that workspace. There, corroborate `packageManager` (when present), the lockfile, and CI; stop on disagreement or competing lockfiles. Pin the manager version and use the matrix in `references/security-checklist.md`.
2762. **Block dependency scripts before first execution.** Bootstrap with scripts disabled or a documented fail-closed policy, inspect the pending script source, approve only the minimum required packages, commit the policy, then verify with a clean frozen/immutable install. Never blanket-approve scripts.
277
278Audits only find known advisories; they do not catch a newly malicious or typosquatted package. Therefore:
279
280- **Never apply forced audit remediation automatically** (`npm audit fix --force` or equivalent). Preview the remediation, read changelogs, and test each resulting upgrade; forced fixes may cross declared dependency ranges.
281- **Verify registry signatures and provenance where supported** (`npm audit signatures`, `pnpm audit signatures`) and treat absence as a signal to investigate, not automatic proof of compromise.
282- **Review new dependencies, lockfile diffs, and script-policy changes together** — ownership, maintenance, release age, provenance, transitive graph, and typosquats such as `cross-env` vs `crossenv` (OWASP **A06**, **LLM03**).
283
284## Rate Limiting
285
286```typescript
287import rateLimit from 'express-rate-limit';
288
289// General API rate limit
290app.use('/api/', rateLimit({
291 windowMs: 15 * 60 * 1000, // 15 minutes
292 max: 100, // 100 requests per window
293 standardHeaders: true,
294 legacyHeaders: false,
295}));
296
297// Stricter limit for auth endpoints
298app.use('/api/auth/', rateLimit({
299 windowMs: 15 * 60 * 1000,
300 max: 10, // 10 attempts per 15 minutes
301}));
302```
303
304## Secrets Management
305
306```
307.env files:
308 ├── .env.example → Committed (template with placeholder values)
309 ├── .env → NOT committed (contains real secrets)
310 └── .env.local → NOT committed (local overrides)
311
312.gitignore must include:
313 .env
314 .env.local
315 .env.*.local
316 *.pem
317 *.key
318```
319
320**Always check before committing:**
321```bash
322# Check for accidentally staged secrets
323git diff --cached | grep -i "password\|secret\|api_key\|token"
324```
325
326**If a secret is ever committed, rotate it.** Deleting the line or rewriting history is not enough — assume it's compromised the moment it reaches a remote. Revoke and reissue the key first, then purge it from history.
327
328## Data Privacy & Compliance
329
330Securing data is "can an attacker read it?" Privacy is "should *we* even hold it, and for how long?" — a separate question that hardening doesn't answer. The cheapest data to protect, breach, and comply over is the data you never collected. Treat personal data as a liability to minimize, not an asset to hoard.
331
332**Know what you hold.** You can't protect or honor a deletion request for data you can't find. Classify fields as you add them:
333
334| Class | Examples | Handling |
335|---|---|---|
336| **Non-personal** | Aggregates, anonymized counts | Normal handling |
337| **Personal (PII)** | Name, email, IP, device/user IDs | Minimize, access-control, include in export/delete |
338| **Sensitive** | Health, finance, location, biometrics, gov IDs, anything about minors | Extra basis to collect, stricter access, often encryption + audit logging |
339
340**Operating rules:**
341- **Minimize and set a purpose.** Collect a field only against a stated use. "It might be useful later" is not a purpose — it's latent breach scope. Don't log PII into telemetry (the `observability-and-instrumentation` skill makes the same point from the ops side).
342- **Set retention up front, then actually delete.** Every personal-data store needs a TTL and a working deletion path — including backups, caches, search indexes, and analytics copies. Data with no expiry is a breach scheduled for later.
343- **Support the data-subject rights your jurisdiction requires** (GDPR/CCPA and kin): export, correct, and delete on request. These are engineering features — design the schema so a user's data is *findable* and *erasable*, not smeared irreversibly across systems.
344- **Get consent before collection or third-party sharing**, and make it auditable. Sending PII to an analytics/ad/LLM vendor is "sharing" — the user's choice gates it, and the vendor needs a data-processing agreement.
345- **Localize defaults, don't hardcode one region's law.** Data-residency and rules differ by user location; make the policy a configurable boundary, not an assumption.
346
347When data crosses a trust boundary, validate it as untrusted (see Input Validation above); when a privacy incident exposes personal data, the breach-notification clock is part of the postmortem — follow the `debugging-and-error-recovery` skill.
348
349## Securing AI / LLM Features
350
351If your app calls an LLM — chatbots, summarizers, agents, RAG — it inherits a new attack surface. Map it to the [OWASP Top 10 for LLM Applications (2025)](https://genai.owasp.org/llm-top-10/):
352
353- **Treat all model output as untrusted input (LLM05: Improper Output Handling).** Never pass LLM output straight into `eval`, SQL, a shell, `innerHTML`, or a file path. Validate and encode it exactly as you would raw user input.
354- **Assume prompts can be hijacked (LLM01: Prompt Injection).** Untrusted text in the context window — a user message, a fetched web page, a PDF — can carry instructions. The system prompt is not a security boundary; enforce permissions in code, not in the prompt.
355- **Keep secrets and other users' data out of prompts (LLM02 / LLM07).** Anything in the context can be echoed back. Don't put API keys, cross-tenant data, or the full system prompt where the model can repeat it.
356- **Constrain tool and agent permissions (LLM06: Excessive Agency).** Scope tools to the minimum, require confirmation for destructive or irreversible actions, and validate every tool argument.
357- **Bound consumption (LLM10: Unbounded Consumption).** Cap tokens, request rate, and loop/recursion depth so a crafted input can't run up cost or hang the system.
358- **Isolate retrieval data (LLM08: Vector and Embedding Weaknesses).** In RAG, treat the vector store as a trust boundary: partition embeddings per tenant so one user can't retrieve another's data, and validate documents before indexing so poisoned content can't steer answers.
359
360```typescript
361// BAD: trusting model output as a command or as markup
362const sql = await llm.generate(`Write SQL for: ${userQuestion}`);
363await db.query(sql); // arbitrary query execution
364container.innerHTML = await llm.reply(userMessage); // stored XSS, via the model
365
366// GOOD: model output is data — parse defensively, then validate, then encode
367let intent;
368try {
369 intent = CommandSchema.parse(JSON.parse(await llm.replyJson(userMessage)));
370} catch {
371 throw new ValidationError('unexpected model output'); // JSON.parse or schema failed
372}
373await runAllowlistedAction(intent.action, intent.params);
374container.textContent = await llm.reply(userMessage);
375```
376
377## Security Review Checklist
378
379```markdown
380### Authentication
381- [ ] Passwords hashed with bcrypt/scrypt/argon2 (salt rounds ≥ 12)
382- [ ] Session tokens are httpOnly, secure, sameSite
383- [ ] Login has rate limiting
384- [ ] Password reset tokens expire
385
386### Authorization
387- [ ] Every endpoint checks user permissions
388- [ ] Users can only access their own resources
389- [ ] Admin actions require admin role verification
390
391### Input
392- [ ] All user input validated at the boundary
393- [ ] SQL queries are parameterized
394- [ ] HTML output is encoded/escaped
395- [ ] Server-side URL fetches are allowlisted (no SSRF to internal services)
396
397### Data
398- [ ] No secrets in code or version control
399- [ ] Sensitive fields excluded from API responses
400- [ ] PII encrypted at rest (if applicable)
401- [ ] Personal data is classified, collected against a stated purpose, and minimized
402- [ ] Personal data has a retention limit and a working deletion path (incl. backups/indexes)
403- [ ] Export/delete (data-subject) requests are supported where required; sharing with third parties has consent
404
405### Infrastructure
406- [ ] Security headers configured (CSP, HSTS, etc.)
407- [ ] CORS restricted to known origins
408- [ ] Dependencies audited for vulnerabilities
409- [ ] Error messages don't expose internals
410
411### Supply Chain
412- [ ] One authoritative lockfile committed; CI uses that manager's frozen/immutable install
413- [ ] Native audit triaged by reachability and fix risk; dependency install scripts blocked unless explicitly approved
414- [ ] New dependencies reviewed (ownership, provenance, release age, transitive graph)
415
416### AI / LLM (if used)
417- [ ] Model output treated as untrusted (no eval/SQL/innerHTML/shell)
418- [ ] Secrets and other users' data kept out of prompts
419- [ ] Tool/agent permissions scoped; destructive actions require confirmation
420```
421## See Also
422
423For detailed security checklists and pre-commit verification steps, see `references/security-checklist.md`.
424
425## Common Rationalizations
426
427| Rationalization | Reality |
428|---|---|
429| "This is an internal tool, security doesn't matter" | Internal tools get compromised. Attackers target the weakest link. |
430| "We'll add security later" | Security retrofitting is 10x harder than building it in. Add it now. |
431| "No one would try to exploit this" | Automated scanners will find it. Security by obscurity is not security. |
432| "The framework handles security" | Frameworks provide tools, not guarantees. You still need to use them correctly. |
433| "It's just a prototype" | Prototypes become production. Security habits from day one. |
434| "Threat modeling is overkill here" | Five minutes of "how would I attack this?" prevents the design flaws no control can patch later. |
435| "It's just LLM output, it's only text" | That "text" can be a SQL statement, a script tag, or a shell command. Treat it like any untrusted input. |
436| "The audit passed, so the dependency is safe" | Audits match known advisories. They do not detect a newly malicious package or make unreviewed install scripts safe to execute. |
437| "Collect it now, we might need it later" | Data you don't hold can't be breached, subpoenaed, or mis-deleted. "Might need it" is breach scope, not a purpose. |
438| "We'll handle deletion requests manually" | Manual erasure misses backups, caches, and analytics copies. If the schema can't find a user's data, you can't honor the request — design for it. |
439| "Compliance is legal's problem, not ours" | Export, deletion, retention, and consent are schema and code. Legal can't bolt them on after you've smeared PII across ten systems. |
440
441## Red Flags
442
443- User input passed directly to database queries, shell commands, or HTML rendering
444- Secrets in source code or commit history
445- API endpoints without authentication or authorization checks
446- Missing CORS configuration or wildcard (`*`) origins
447- No rate limiting on authentication endpoints
448- Stack traces or internal errors exposed to users
449- Dependencies with known critical vulnerabilities, competing lockfiles at one installation boundary, non-reproducible installs, or blanket-approved scripts
450- Server fetches user-supplied URLs without an allowlist (SSRF)
451- LLM/model output passed into a query, the DOM, a shell, or `eval`
452- Secrets, PII, or the full system prompt placed inside an LLM context window
453- Personal data collected with no stated purpose, retention limit, or deletion path
454- PII sent to analytics/ad/LLM vendors with no consent or data-processing agreement
455- "Delete my account" that only flips a flag while the personal data lingers in stores and backups
456
457## Verification
458
459After implementing security-relevant code:
460
461- [ ] The native audit has no unmitigated reachable critical/high findings; CI preserves the authoritative lockfile and blocks unreviewed dependency scripts
462- [ ] No secrets in source code or git history
463- [ ] All user input validated at system boundaries
464- [ ] Authentication and authorization checked on every protected endpoint
465- [ ] Security headers present in response (check with browser DevTools)
466- [ ] Error responses don't expose internal details
467- [ ] Rate limiting active on auth endpoints
468- [ ] Server-side URL fetches validated against an allowlist (no SSRF)
469- [ ] LLM/model output validated and encoded before use (if AI features present)
470- [ ] Personal data is classified, minimized to a stated purpose, and has a retention limit
471- [ ] Deletion and export requests work end-to-end (including backups, caches, and analytics copies)
472
473## Derived Paths and Shared Limits
474
475Treat filenames, other processes' arguments, and job-supplied paths as untrusted
476when their writers are not trusted. Before destructive operations, resolve the
477target below an allowlisted root, reject the root itself, verify ownership from
478trusted state, and prevent symlink/check-use races. A writable marker alone is
479not authorization; failure must not fall back to a broader target.
480For multi-process or serverless rate limits, use a shared store or platform limiter;
481process-local counters cannot enforce one global authentication limit.