security-and-hardening – Security skill for AI agents
Hardens code against vulnerabilities. Use when handling user input, authentication, data storage, or external integrations. Use when building any feature that accepts untrusted data, manages user sessions, or interacts with third-party services.
Install the security-and-hardening skill with one command
Pick the tool you use, copy the command and paste it in your terminal. The skill lands in that tool's skills folder and is ready in your next session.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/security-and-hardening-5e07d.tgz | tar xz -C ~/.claude/skills
Call it in Claude Code: /security-and-hardening – then describe the task you want done.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/security-and-hardening-5e07d.tgz | tar xz -C ~/.codex/skills
Call it in Codex: $security-and-hardening – then describe the task you want done.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/security-and-hardening-5e07d.tgz | tar xz -C ~/.hermes/skills
Call it in Hermes Agent: /security-and-hardening – then describe the task you want done.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/security-and-hardening-5e07d.tgz | tar xz -C ~/.deepcode/skills
Call it in DeepSeek: /security-and-hardening – then describe the task you want done.
SKILL.md content
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
Integration boundaries
Code blocks are independent sketches with missing application imports/adapters, not a complete tested server. Review executable code before running it, use isolated synthetic fixtures, and bound provider/network/production effects to user authority. Runtime validation, tenant checks, authorization, CSRF, output allowlists and atomic write predicates belong in the actual implementation. A green scanner/checklist is not security certification.
Process: Threat Model First
Controls bolted on without a threat model are guesses. Before hardening, spend five minutes thinking like an attacker:
1. 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.
2. Name the assets. What's worth stealing or breaking? Credentials, PII, payment data, admin actions, money movement.
3. 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 |
4. 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. Insecure design is a relevant risk category; the exact OWASP edition/category numbering must be verified before citing it. No majority-of-breaches claim is established here.
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
npm audit(or equivalent) before every release
Confirm scope for sensitive changes
Existing explicit authorization covers the requested implementation; do not ask repeatedly for routine steps already included. New sensitive-data categories, data destinations, permission grants and production effects need the appropriate owner authority.
Changes requiring a clear authorized scope include:
- 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()orinnerHTMLwith user-provided data <!-- security-allowlist: defensive hardening guidance --> - 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 a task-focused review checklist, see 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: require trusted proxy/TLS configuration when appropriate,
// rotate the session identifier on login/privilege changes and enforce revocation.
app.use(session({
secret: requiredSessionSecret, // validate high-entropy configured secret at startup
store: productionSessionStore, // do not use express-session MemoryStore in production
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true, // Not accessible via JavaScript
secure: true, // HTTPS only
sameSite: 'lax', // Defense in depth; add CSRF protection for cookie-authenticated writes
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 || task.ownerId !== req.user.id) {
return res.status(403).json({
error: { code: 'FORBIDDEN', message: 'Not authorized to modify this task' }
});
}
// Proceed with update
const input = UpdateTaskSchema.safeParse(req.body); // Schema allowlists mutable fields only.
if (!input.success) return res.status(422).json({ error: 'Invalid input' });
// The service must atomically enforce ownerId in its update predicate.
const updated = await taskService.updateOwned(req.params.id, req.user.id, input.data);
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: approvedOrigins, // validate an explicit nonempty production list at startup
// No implicit development-origin fallback in production.
credentials: true,
}));Sensitive Data Exposure
// Never return sensitive fields in API responses
function sanitizeUser(user: UserRecord): PublicUser {
return { id: user.id, displayName: user.displayName }; // Explicit public-field allowlist.
}
// 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)
Any time the server fetches a URL the user influenced — webhooks, "import from URL", image proxies, link previews — an attacker can aim it at internal services (cloud metadata, localhost, private IPs).
// BAD: fetch whatever the user gives you
await fetch(req.body.webhookUrl);
// PARTIAL CHECK ONLY: this has the DNS rebinding gap described below.
// Do not deploy the direct fetch as a complete SSRF defense.
import { lookup } from 'node:dns/promises';
import ipaddr from 'ipaddr.js';
const ALLOWED_HOSTS = new Set(['hooks.example.com']);
async function assertSafeUrl(raw: string): Promise<URL> {
const url = new URL(raw);
if (url.protocol !== 'https:' || url.username || url.password || (url.port &… (full content is in the download package)
Related skills
- security-arsenal – Security payloads, bypass tables, wordlists, gf pattern names, always-rejected bug list…
- security-audit – Comprehensive security auditing workflow covering web application testing, API security…
- security-auditor – Expert security auditor specializing in DevSecOps, comprehensive cybersecurity, and…
- security-automation – Automate security workflows and remediation. Build security pipelines, automate…
- security-bluebook-builder – Build a minimal but real security policy for sensitive apps. The output is a single…
- security-checklist – Review a scoped architecture against evidence-based network, identity, data, secrets…
- security-compliance-compliance-check – You are a compliance expert specializing in regulatory requirements for software systems…
- security-requirement-extraction – Derive security requirements from threat models and business context. Use when…