security-and-hardening – skill Bảo mật cho agent AI
Tăng cường bảo mật mã nguồn chống lại lỗ hổng. Dùng khi xử lý input người dùng, xác thực, lưu trữ dữ liệu hoặc tích hợp bên ngoài. Dùng khi xây dựng bất kỳ tính năng nào nhận dữ liệu không đáng tin cậy, quản lý phiên người dùng hoặc tương tác với dịch vụ bên thứ ba.
Cài skill security-and-hardening bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/security-and-hardening-5e07d.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /security-and-hardening – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/security-and-hardening-5e07d.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $security-and-hardening – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/security-and-hardening-5e07d.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /security-and-hardening – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/security-and-hardening-5e07d.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /security-and-hardening – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
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 &… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- security-arsenal – Payload bảo mật, bảng bypass, wordlist, tên pattern gf, danh sách lỗi luôn bị từ chối và…
- security-audit – Quy trình kiểm toán bảo mật toàn diện, bao gồm kiểm thử ứng dụng web, bảo mật API, kiểm…
- security-auditor – Chuyên gia kiểm toán bảo mật chuyên về DevSecOps, an ninh mạng toàn diện và các khung…
- security-automation – Tự động hóa quy trình bảo mật và khắc phục. Xây dựng pipeline bảo mật, tự động kiểm tra…
- security-bluebook-builder – Xây dựng chính sách bảo mật tối thiểu nhưng thực tế cho ứng dụng nhạy cảm. Đầu ra là một…
- security-checklist – Rà soát kiến trúc trong phạm vi xác định theo các kiểm soát dựa trên bằng chứng: mạng…
- security-compliance-compliance-check – Bạn là chuyên gia tuân thủ, am hiểu các yêu cầu pháp lý cho hệ thống phần mềm như GDPR…
- security-requirement-extraction – Suy ra yêu cầu bảo mật từ mô hình mối đe dọa và bối cảnh kinh doanh. Dùng khi chuyển mối…