원클릭으로
security
加固代码以抵御漏洞。在处理用户输入、认证、数据存储或外部集成时使用。在构建任何接收不可信数据、管理用户会话或与第三方服务交互的 feature 时使用。
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
加固代码以抵御漏洞。在处理用户输入、认证、数据存储或外部集成时使用。在构建任何接收不可信数据、管理用户会话或与第三方服务交互的 feature 时使用。
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
FDD 主流程 step 1(规划与拆解)。覆盖两段——plan(与用户弄清需求、经 investigator 调查代码库、定出 milestone、写出 plan.md 并呈现)与 features(把 milestone 拆成 features.json 并过 coverage 闸)。中间的 contract 段交给 harness-stack:fdd-validation-contract。由 harness-stack:fdd 调用。
构建新特性的主流程编排器。契约优先的多 agent 架构——捕获一个 plan,定义可测试的断言,拆解为多个 feature,再用全新上下文的 implementer/reviewer/validator subagent 驱动一个里程碑设闸的执行循环。当一处改动触及多个文件、有多条验收标准、或跨越多个 feature 时使用。主流程分三步,分发给 fdd-planning(含 fdd-validation-contract)/ fdd-execution / fdd-validate。
为一个 plan 撰写 validation contract——把 definition of done 落成一组可测试、用户可观测的 assertion(VAL-<AREA>-NNN),带 persona 与声明的 Evidence。它是 fdd step 1(规划)里的 contract 阶段。契约通过逐 area 的 investigation subagent 与若干轮 adversarial review 构建,而非一人独写。产出 .harness-runtime/plans/<slug>/validation-contract.md,并经由 fdd init-state 播种 validation-state.json。在项目内首次使用时,还会 bootstrap 项目级约定文档 docs/user-test-patterns.md。
规范 git 工作流实践。任何代码改动都适用。在提交、开分支、解决冲突,或需要把多条并行工作线组织起来时使用。
harness-stack 框架的引导纲要(bootstrap doctrine)。在会话开始时自动加载,用以介绍 lifecycle map、golden rules,以及如何挑选正确的 harness-stack:* skill。在一次会话中首次调用任何 harness-stack:* skill 之前,先读它。
复盘一次 harness-stack 使用,把值得上报的摩擦、缺陷或建议提成 GitHub Issue 反馈给上游。在完成一项任务、用完某个 skill 后有意见或改进想法,或想为框架本身留下改进线索时使用。
SOC 직업 분류 기준
| name | security |
| description | 加固代码以抵御漏洞。在处理用户输入、认证、数据存储或外部集成时使用。在构建任何接收不可信数据、管理用户会话或与第三方服务交互的 feature 时使用。 |
面向 Web 应用的安全优先开发实践。把每一份外部输入都当作敌意输入,把每一个 secret 都当作机密,把每一次授权检查都当作强制项。安全不是一个阶段——它是一道约束,贯穿每一行触及用户数据、认证或外部系统的代码。
与 FDD 的分工: 深度威胁建模由
harness-stack:security-auditor子代理执行。在fdd流程内,它会在 milestone 边界、当 diff 触及敏感面(auth/secrets/crypto/裸查询/shell/依赖升级)时自动并行派发。本技能是 FDD 之外 的独立手动安全审计与加固路径(就像review-request之于 code-review)。
npm audit(或等价工具)eval() 或 innerHTML// 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 } });
// 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
},
}));
// 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);
// 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 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,
}));
// 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');
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);
});
// 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
}
并非所有 audit 发现都需要立即处理。用这棵决策树:
npm audit reports a vulnerability
├── Severity: critical or high
│ ├── Is the vulnerable code reachable in your app?
│ │ ├── YES --> Fix immediately (update, patch, or replace the dependency)
│ │ └── NO (dev-only dep, unused code path) --> 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
关键问题:
当你推迟修复时,记录原因并设定一个复查日期。
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
}));
.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
提交前务必检查:
# Check for accidentally staged secrets
git diff --cached | grep -i "password\|secret\|api_key\|token"
### 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
### Data
- [ ] No secrets in code or version control
- [ ] Sensitive fields excluded from API responses
- [ ] PII encrypted at rest (if applicable)
### Infrastructure
- [ ] Security headers configured (CSP, HSTS, etc.)
- [ ] CORS restricted to known origins
- [ ] Dependencies audited for vulnerabilities
- [ ] Error messages don't expose internals
详细的安全检查清单与提交前验证步骤,见 references/security-checklist.md。
| 借口 | 现实 |
|---|---|
| 「这是内部工具,安全无所谓。」 | 内部工具一样会被攻破。攻击者专挑最薄弱的环节。 |
| 「安全我们以后再加。」 | 事后补安全比一开始就做难 10 倍。现在就加。 |
| 「没人会来攻击这个。」 | 自动化扫描器会找到它。靠隐蔽求安全不是安全。 |
| 「框架会处理安全。」 | 框架提供工具,不提供保证。你仍然得正确地使用它们。 |
| 「这只是个原型。」 | 原型会变成生产。从第一天起就养成安全习惯。 |
*)源实现安全相关代码后:
npm audit 没有报出 critical 或 high 漏洞