Secure Development Practices
Overview
Comprehensive secure development practices that integrate OWASP compliance, automated patch generation, security compliance checking, and security-first coding patterns.
OWASP Top 10 Detection and Prevention
Detection Framework
// security/owasp-detector.ts
interface OWASPVulnerability {
id: string;
name: string;
severity: 'low' | 'medium' | 'high' | 'critical';
detector: (code: string, ast: any) => VulnerabilityInstance[];
fixer: (instance: VulnerabilityInstance) => string;
}
export const OWASP_TOP_10: OWASPVulnerability[] = [
{ id: 'A01:2021', name: 'Broken Access Control', severity: 'critical' },
{ id: 'A02:2021', name: 'Cryptographic Failures', severity: 'high' },
{ id: 'A03:2021', name: 'Injection', severity: 'critical' },
{ id: 'A04:2021', name: 'Insecure Design', severity: 'high' },
{ id: 'A05:2021', name: 'Security Misconfiguration', severity: 'medium' },
{ id: 'A06:2021', name: 'Vulnerable and Outdated Components', severity: 'high' },
{ id: 'A07:2021', name: 'Identification and Authentication Failures', severity: 'critical' },
{ id: 'A08:2021', name: 'Software and Data Integrity Failures', severity: 'high' },
{ id: 'A09:2021', name: 'Security Logging and Monitoring Failures', severity: 'medium' },
{ id: 'A10:2021', name: 'Server-Side Request Forgery (SSRF)', severity: 'high' }
];Injection Prevention (A03:2021)
// Detection
function detectInjection(code: string, ast: ts.SourceFile): VulnerabilityInstance[] {
const vulnerabilities: VulnerabilityInstance[] = [];
function visit(node: ts.Node) {
// SQL Injection Detection
if (ts.isCallExpression(node)) {
const expression = node.expression;
if (ts.isPropertyAccessExpression(expression)) {
const methodName = expression.name.getText();
const dbMethods = ['query', 'execute', 'exec', 'run'];
if (dbMethods.includes(methodName)) {
const args = node.arguments;
if (args.length > 0 && ts.isTemplateExpression(args[0])) {
vulnerabilities.push({
type: 'SQL_INJECTION',
location: getNodeLocation(ast, node),
message: 'Potential SQL injection vulnerability',
node: node
});
}
}
}
}
ts.forEachChild(node, visit);
}
visit(ast);
return vulnerabilities;
}
// Prevention Pattern
function generateSQLInjectionFix(instance: VulnerabilityInstance): string {
return `
// Fixed SQL Injection vulnerability
// Use parameterized queries
const query = 'SELECT * FROM users WHERE id = ? AND status = ?';
const params = [userId, status];
await db.query(query, params);
// Or use a query builder
const result = await db
.select('*')
.from('users')
.where('id', userId)
.where('status', status);
`;
}Authentication Security (A07:2021)
// Strong Password Policy
const passwordPolicy = {
minLength: 12,
requireUppercase: true,
requireLowercase: true,
requireNumbers: true,
requireSpecialChars: true,
preventCommonPasswords: true
};
function validatePassword(password: string): ValidationResult {
const errors: string[] = [];
if (password.length < passwordPolicy.minLength) {
errors.push(`Password must be at least ${passwordPolicy.minLength} characters`);
}
if (passwordPolicy.requireUppercase && !/[A-Z]/.test(password)) {
errors.push('Password must contain uppercase letters');
}
if (passwordPolicy.requireNumbers && !/\d/.test(password)) {
errors.push('Password must contain numbers');
}
return { valid: errors.length === 0, errors };
}
// Secure Session Management
const sessionConfig = {
secret: process.env.SESSION_SECRET,
name: 'sessionId',
cookie: {
httpOnly: true,
secure: true, // HTTPS only
sameSite: 'strict',
maxAge: 1000 * 60 * 60 * 2 // 2 hours
},
resave: false,
saveUninitialized: false
};
// Rate Limiting
import rateLimit from 'express-rate-limit';
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // Limit each IP to 5 requests per windowMs
message: 'Too many login attempts, please try again later',
skipSuccessfulRequests: true
});
app.post('/api/login', loginLimiter, loginHandler);Automated Security Patch Generation
Patch Generation Workflow
// .claude/security-patch-generator.ts
import { ClaudeSDK } from '@claude/sdk';
class SecurityPatchGenerator {
constructor(private claude: ClaudeSDK) {}
async generatePatch(vulnerability: any): Promise<SecurityPatch> {
const context = await this.gatherContext(vulnerability);
const patchPrompt = `
Vulnerability: ${vulnerability.type}
File: ${vulnerability.file}
Line: ${vulnerability.line}
Issue: ${vulnerability.description}
Generate a secure patch that:
1. Fixes the vulnerability
2. Maintains backward compatibility
3. Follows TypeScript best practices
4. Includes proper error handling
`;
const response = await this.claude.generateCode(patchPrompt);
const tests = await this.generateTests(vulnerability, response.code);
return {
vulnerability: vulnerability.id,
file: vulnerability.file,
patch: response.code,
confidence: response.confidence,
testing: tests
};
}
async generateTests(vulnerability: any, patch: string): Promise<any> {
const testPrompt = `
Generate comprehensive tests for this security patch:
Vulnerability: ${vulnerability.type}
Patch: ${patch}
Include:
1. Unit tests for the patched function
2. Integration tests for affected flows
3. Security-specific tests
4. Edge cases and error conditions
`;
const response = await this.claude.generateCode(testPrompt);
return {
unitTests: response.unitTests,
integrationTests: response.integrationTests,
securityTests: response.securityTests
};
}
}Automated Testing Framework
class AutomatedSecurityTesting {
async testSecurityPatch(patch: SecurityPatch): Promise<TestResults> {
const results: TestResults = {
passed: [],
failed: [],
skipped: []
};
// Phase 1: Static validation
const staticTests = [
this.validateNoNewVulnerabilities,
this.validateSecureCodingPractices,
this.validateInputSanitization
];
for (const test of staticTests) {
const result = await test(patch);
results[result.status].push(result);
}
// Phase 2: Dynamic testing
const dynamicTests = [
this.fuzzTesting,
this.injectionTesting,
this.authenticationTesting
];
for (const test of dynamicTests) {
const result = await test(patch);
results[result.status].push(result);
}
// Phase 3: Performance testing
const perfResult = await this.performanceImpactTest(patch);
if (perfResult.degradation > 10) {
results.failed.push({
test: 'Performance Impact',
reason: `Patch causes ${perfResult.degradation}% performance degradation`
});
}
return results;
}
}Security Compliance Automation
Compliance Framework
// security/compliance-checker.ts
interface ComplianceFramework {
name: string;
controls: ComplianceControl[];
validator: (code: string, config: any) => ComplianceResult;
}
export class ComplianceChecker {
private frameworks: Map<string, ComplianceFramework> = new Map([
['SOC2', new SOC2Framework()],
['HIPAA', new HIPAAFramework()],
['PCI-DSS', new PCIDSSFramework()],
['GDPR', new GDPRFramework()]
]);
async checkCompliance(
framework: string,
codebase: string
): Promise<ComplianceReport> {
const checker = this.frameworks.get(framework);
const violations: ComplianceViolation[] = [];
for (const control of checker.controls) {
const result = await this.checkControl(control, codebase);
if (!result.compliant) {
violations.push({
control: control.id,
description: control.description,
severity: control.severity,
findings: result.findings,
remediation: result.remediation
});
}
}
return this.generateReport(framework, violations);
}
}SOC2 Compliance Example
class SOC2Framework implements ComplianceFramework {
controls = [
{
id: 'CC6.1',
category: 'Logical Access Controls',
check: async (code: string) => {
// Check for proper authentication
const hasAuth = code.includes('authenticate');
const hasMFA = code.includes('mfa') || code.includes('2fa');
return {
compliant: hasAuth && hasMFA,
findings: !hasMFA ? ['Missing multi-factor authentication'] : []
};
}
},
{
id: 'CC7.2',
category: 'System Monitoring',
check: async (code: string) => {
// Check for logging and monitoring
const hasLogging = code.includes('logger') || code.includes('log');
const hasMonitoring = code.includes('monitor') || code.includes('alert');
return {
compliant: hasLogging && hasMonitoring,
findings: !hasLogging ? ['Insufficient logging'] : []
};
}
}
];
}PCI-DSS Compliance
class PCIDSSFramework implements ComplianceFramework {
controls = [
{
id: 'PCI-DSS 3.4',
category: 'Card Data Protection',
check: async (code: string) => {
// Check for unencrypted card data
const cardPatterns = [
/\b\d{13,19}\b/, // Card numbers
/cvv|cvc|cid/i, // CVV codes
/expiry|exp_date/i // Expiry dates
];
const violations = [];
for (const pattern of cardPatterns) {
if (pattern.test(code) && !code.includes('encrypt')) {
violations.push('Potential unencrypted card data');
}
}
return {
compliant: violations.length === 0,
findings: violations
};
}
}
];
}Secure Coding Patterns
1. Input Validation Pattern
class InputValidator {
static sanitizeHTML(input: string): string {
return DOMPurify.sanitize(input, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
ALLOWED_ATTR: ['href']
});
}
static validateEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email) && email.length < 255;
}
static validateURL(url: string): boolean {
try {
const parsed = new URL(url);
return ['http:', 'https:'].includes(parsed.protocol);
} catch {
return false;
}
}
}2. Secure Data Handling
class SecureDataHandler {
// Encrypt sensitive data at rest
async encryptData(data: string): Promise<string> {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
let encrypted = cipher.update(data, 'utf8', 'hex');
encrypted += cipher.final('hex');
const authTag = cipher.getAuthTag();
return iv.toString('hex') + ':' + authTag.toString('hex') + ':' + encrypted;
}
// Secure deletion
async secureDelete(data: Buffer): Promise<void> {
crypto.randomFillSync(data);
data.fill(0);
}
}3. Error Handling Without Information Leakage
class SecureErrorHandler {
handle(error: Error, req: Request, res: Response): void {
// Log detailed error internally
logger.error('Application error', {
error: error.message,
stack: error.stack,
request: {
url: req.url,
method: req.method,
ip: req.ip
}
});
// Return generic error to client
const isProduction = process.env.NODE_ENV === 'production';
res.status(500).json({
error: isProduction ? 'Internal server error' : error.message,
requestId: req.id // For support reference
});
}
}Security Pipeline Integration
// .claude/security-pipeline.ts
export const securityPipeline: Pipeline = {
name: 'security-compliance',
triggers: ['push', 'pull_request', 'schedule:0 0 * * 0'],
stages: [
{
name: 'owasp-scan',
steps: [
{
name: 'detect-vulnerabilities',
command: 'npm run security:owasp-scan'
},
{
name: 'generate-patches',
command: 'npm run security:generate-patches'
}
]
},
{
name: 'compliance-check',
steps: [
{
name: 'soc2-check',
command: 'npm run compliance:soc2'
},
{
name: 'pci-check',
command: 'npm run compliance:pci',
condition: 'hasPaymentProcessing'
}
]
},
{
name: 'security-testing',
steps: [
{
name: 'unit-tests',
command: 'npm run test:security'
},
{
name: 'penetration-tests',
command: 'npm run test:penetration'
}
]
}
]
};Best Practices
- Security by Design: Consider security from the start
- Defense in Depth: Layer multiple security controls
- Least Privilege: Grant minimum necessary permissions
- Fail Securely: Handle errors without exposing sensitive data
- Regular Updates: Keep dependencies and security patches current
See Also
Verifications
This documentation has been verified against:
-
OWASP Top 10 2021 Official Documentation (https://owasp.org/www-project-top-ten/) - The vulnerability list and categorization accurately reflects the official OWASP Top 10 2021, including all 10 categories (A01-A10) with their correct names and severity levels.
-
OWASP Node.js Security Cheat Sheet (https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet.html) - The TypeScript/Node.js prevention patterns align with OWASP’s official guidance for Node.js security, including proper input validation, parameterized queries, and secure session management.
-
Current Security Best Practices - The code examples follow 2025 security standards including:
- Use of DOMPurify for HTML sanitization
- Proper httpOnly, Secure, and SameSite cookie flags
- Rate limiting for authentication endpoints
- Encryption at rest using AES-256-GCM
- Multi-factor authentication implementation
Note: OWASP is planning to release the OWASP Top 10:2025 in late summer/early fall 2025, which may introduce new categories focusing on “secure-by-design” principles and potentially include Algorithmic Denial of Service and HTTP Request Smuggling.