技能创建器
skill-creator
创建、改进和评估自定义技能,把专业流程转化为可重复使用的 AI 能力。
security-best-practices【数据与研究】Security-focused development skill covering OWASP Top 10 and secure coding. Use when implementing authentication, handling user data, or security review. Keywords: security, auth, authentication, authorization, OWASP, XSS, SQL injection, CSRF, secure
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
Philosophy: Security is not optional. Build it in from the start.
Use this skill when:
Do NOT use this skill when:
Before starting:
What: Users can access data/functions they shouldn't.
Prevention:
// ❌ Bad: No authorization check
app.get('/users/:id', async (req, res) => {
const user = await db.users.findById(req.params.id);
res.json(user);
});
// ✅ Good: Check ownership
app.get('/users/:id', authorize(), async (req, res) => {
const user = await db.users.findById(req.params.id);
if (user.id !== req.user.id && req.user.role !== 'admin') {
throw new ForbiddenException();
}
res.json(user);
});
Checklist:
What: Weak crypto, exposed sensitive data.
Prevention:
// ❌ Bad: Weak hashing
const hash = crypto.createHash('md5').update(password).digest('hex');
// ✅ Good: Strong hashing with bcrypt
const hash = await bcrypt.hash(password, 12);
// ❌ Bad: Hardcoded secrets
const API_KEY = "sk_live_abc123";
// ✅ Good: Environment variables
const API_KEY = process.env.API_KEY;
Checklist:
What: Malicious data executed as code/query.
Prevention:
// ❌ Bad: SQL Injection
const query = `SELECT * FROM users WHERE email = '${email}'`;
// ✅ Good: Parameterized queries
const user = await db.query(
'SELECT * FROM users WHERE email = $1',
[email]
);
// ❌ Bad: Command injection
exec(`convert ${filename} output.png`);
// ✅ Good: Use library functions
await sharp(filename).toFile('output.png');
Types to Prevent:
Checklist:
What: Missing security in design phase.
Prevention:
# Security design considerations
threat_modeling:
assets:
- User credentials
- Payment information
- Personal data
threats:
- Authentication bypass
- Data theft
- Privilege escalation
mitigations:
- MFA for sensitive operations
- Encryption at rest
- Audit logging
Checklist:
What: Insecure settings, missing hardening.
Prevention:
// ❌ Bad: Debugging enabled in production
app.use(express.errorHandler({ dumpExceptions: true }));
// ✅ Good: Production-safe error handling
if (process.env.NODE_ENV === 'production') {
app.use((err, req, res, next) => {
console.error(err); // Log internally
res.status(500).json({ message: 'Internal error' }); // Don't expose details
});
}
Checklist:
Security Headers:
app.use(helmet());
// Or manually:
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader('Strict-Transport-Security', 'max-age=31536000');
res.setHeader('Content-Security-Policy', "default-src 'self'");
next();
});
What: Using libraries with known vulnerabilities.
Prevention:
# Check for vulnerabilities
npm audit
pip-audit
dotnet list package --vulnerable
# Fix vulnerabilities
npm audit fix
pip-audit --fix
Checklist:
What: Broken login, session management.
Prevention:
// Password requirements
const passwordPolicy = {
minLength: 12,
requireUppercase: true,
requireLowercase: true,
requireNumber: true,
requireSpecial: true,
preventCommon: true,
};
// Rate limiting login attempts
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 attempts
message: 'Too many login attempts'
});
// Session configuration
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: true, // HTTPS only
httpOnly: true, // No JS access
sameSite: 'strict', // CSRF protection
maxAge: 3600000 // 1 hour
}
}));
Checklist:
What: Insecure updates, CI/CD pipeline attacks.
Prevention:
# Verify package integrity
package-lock.json # Lock versions
npm ci # Install exact versions
# CI/CD security
ci_security:
- Verify source code integrity
- Sign releases
- Secure deployment pipeline
- Review third-party actions
Checklist:
What: Insufficient logging for security events.
Prevention:
// Security event logging
const securityLogger = {
loginSuccess: (userId: string, ip: string) => {
logger.info('LOGIN_SUCCESS', { userId, ip, timestamp: new Date() });
},
loginFailure: (email: string, ip: string, reason: string) => {
logger.warn('LOGIN_FAILURE', { email, ip, reason, timestamp: new Date() });
},
accessDenied: (userId: string, resource: string, ip: string) => {
logger.warn('ACCESS_DENIED', { userId, resource, ip, timestamp: new Date() });
},
suspiciousActivity: (details: object) => {
logger.error('SUSPICIOUS_ACTIVITY', { ...details, timestamp: new Date() });
}
};
// Log what to log
// ✅ Login attempts (success and failure)
// ✅ Access control failures
// ✅ Input validation failures
// ✅ Security configuration changes
// ✅ High-value transactions
// ❌ Don't log
// Passwords
// Session tokens
// Credit card numbers
// Personal data (unless necessary)
Checklist:
What: Server-Side Request Forgery.
Prevention:
// ❌ Bad: User-controlled URL
const response = await fetch(req.body.url);
// ✅ Good: Validate and restrict
const ALLOWED_DOMAINS = ['api.example.com', 'cdn.example.com'];
async function fetchUrl(userUrl: string) {
const parsed = new URL(userUrl);
if (!ALLOWED_DOMAINS.includes(parsed.hostname)) {
throw new Error('Domain not allowed');
}
if (parsed.protocol !== 'https:') {
throw new Error('HTTPS required');
}
return fetch(userUrl);
}
Checklist:
// Validation with Zod
const UserSchema = z.object({
email: z.string().email().toLowerCase().trim(),
password: z.string().min(12).max(128),
name: z.string().min(2).max(50).regex(/^[a-zA-Z\s]+$/),
age: z.number().int().min(13).max(120).optional(),
});
// Validation with class-validator
class CreateUserDto {
@IsEmail()
@Transform(({ value }) => value.toLowerCase().trim())
email: string;
@IsString()
@MinLength(12)
@MaxLength(128)
@Matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])/)
password: string;
@IsString()
@MinLength(2)
@MaxLength(50)
name: string;
}
// ❌ Bad: Raw HTML output
element.innerHTML = userInput;
// ✅ Good: Text content only
element.textContent = userInput;
// ✅ Good: Sanitize if HTML needed
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);
security_tests:
authentication:
- Test login with invalid credentials
- Test brute force protection
- Test session timeout
- Test logout clears session
- Test password reset flow
authorization:
- Test accessing other users' data
- Test admin functions as normal user
- Test direct object references
- Test privilege escalation
input_validation:
- Test SQL injection payloads
- Test XSS payloads
- Test command injection
- Test path traversal
- Test file upload restrictions
configuration:
- Test HTTPS enforcement
- Test security headers present
- Test error messages sanitized
- Test debugging disabled
Before considering code secure:
skills/kilo-kit/development/backend/ - For API securityskills/kilo-kit/quality/code-review/ - For security reviewskills/kilo-kit/debugging/root-cause/ - For security incident analysisSecurity Best Practices Skill v1.0.0 — Security is everyone's job