Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | /** * Security Domain Service - Domain Layer * * Contains security logic for validation, policy enforcement, and threat detection. * * @module v3/security/domain/services */ import { SecurityContext, PermissionLevel } from '../entities/security-context.js'; /** * Validation result */ export interface ValidationResult { valid: boolean; errors: string[]; warnings: string[]; sanitized?: string; } /** * Threat detection result */ export interface ThreatDetectionResult { safe: boolean; threats: Array<{ type: string; severity: 'low' | 'medium' | 'high' | 'critical'; description: string; location?: string; }>; } /** * Security Domain Service */ export class SecurityDomainService { // Dangerous patterns for path traversal private static readonly PATH_TRAVERSAL_PATTERNS = [ /\.\./, /~\//, /^\/etc\//, /^\/tmp\//, /^\/var\/log\//, /^C:\\Windows/i, /^C:\\Users\\[^\\]+\\AppData/i, ]; // Dangerous command patterns private static readonly DANGEROUS_COMMANDS = [ /^rm\s+-rf\s+\//, /^rm\s+-rf\s+\*/, /^dd\s+if=/, /^mkfs\./, /^format\s+/i, /^del\s+\/s\s+\/q/i, />\s*\/dev\/sd[a-z]/, /\|\s*bash$/, /\|\s*sh$/, /eval\s*\(/, /exec\s*\(/, ]; // SQL injection patterns private static readonly SQL_INJECTION_PATTERNS = [ /'\s*OR\s+'1'\s*=\s*'1/i, /'\s*OR\s+1\s*=\s*1/i, /;\s*DROP\s+TABLE/i, /;\s*DELETE\s+FROM/i, /UNION\s+SELECT/i, /--\s*$/, ]; // XSS patterns private static readonly XSS_PATTERNS = [ /<script[\s>]/i, /javascript:/i, /on\w+\s*=/i, /<iframe/i, /<object/i, /<embed/i, ]; /** * Validate a file path */ validatePath(path: string, context: SecurityContext): ValidationResult { const errors: string[] = []; const warnings: string[] = []; // Check path traversal for (const pattern of SecurityDomainService.PATH_TRAVERSAL_PATTERNS) { if (pattern.test(path)) { errors.push(`Path traversal detected: ${pattern.source}`); } } // Check context permissions if (!context.canAccessPath(path)) { errors.push(`Access denied to path: ${path}`); } // Check for suspicious paths if (path.includes('..')) { warnings.push('Path contains parent directory reference'); } return { valid: errors.length === 0, errors, warnings, sanitized: this.sanitizePath(path), }; } /** * Validate a command */ validateCommand(command: string, context: SecurityContext): ValidationResult { const errors: string[] = []; const warnings: string[] = []; // Check dangerous commands for (const pattern of SecurityDomainService.DANGEROUS_COMMANDS) { if (pattern.test(command)) { errors.push(`Dangerous command pattern detected: ${pattern.source}`); } } // Check context permissions if (!context.canExecuteCommand(command)) { errors.push(`Command execution denied: ${command}`); } if (!context.hasPermission('execute')) { errors.push('Execute permission required'); } // Check for shell injection if (/[;&|`$(){}]/.test(command)) { warnings.push('Command contains shell metacharacters'); } return { valid: errors.length === 0, errors, warnings, sanitized: this.sanitizeCommand(command), }; } /** * Validate user input */ validateInput(input: string): ValidationResult { const errors: string[] = []; const warnings: string[] = []; // Check for SQL injection for (const pattern of SecurityDomainService.SQL_INJECTION_PATTERNS) { if (pattern.test(input)) { errors.push(`SQL injection pattern detected`); break; } } // Check for XSS for (const pattern of SecurityDomainService.XSS_PATTERNS) { if (pattern.test(input)) { errors.push(`XSS pattern detected`); break; } } // Check length if (input.length > 10000) { warnings.push('Input exceeds recommended length'); } return { valid: errors.length === 0, errors, warnings, sanitized: this.sanitizeInput(input), }; } /** * Detect threats in content */ detectThreats(content: string): ThreatDetectionResult { const threats: ThreatDetectionResult['threats'] = []; // Check for various threat patterns if (/<script/i.test(content)) { threats.push({ type: 'xss', severity: 'high', description: 'Script tag detected', }); } if (/password\s*[:=]\s*["'][^"']+["']/i.test(content)) { threats.push({ type: 'credential-exposure', severity: 'critical', description: 'Hardcoded password detected', }); } if (/api[_-]?key\s*[:=]\s*["'][^"']+["']/i.test(content)) { threats.push({ type: 'credential-exposure', severity: 'critical', description: 'API key detected', }); } if (/eval\s*\(/.test(content)) { threats.push({ type: 'code-injection', severity: 'high', description: 'Eval statement detected', }); } return { safe: threats.length === 0, threats, }; } /** * Sanitize path */ private sanitizePath(path: string): string { return path .replace(/\.\./g, '') .replace(/\/\//g, '/') .replace(/^~\//, '') .trim(); } /** * Sanitize command */ private sanitizeCommand(command: string): string { return command .replace(/[;&|`$]/g, '') .replace(/\$\([^)]*\)/g, '') .trim(); } /** * Sanitize user input */ private sanitizeInput(input: string): string { return input .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, ''') .replace(/\//g, '/'); } /** * Create security context for agent */ createAgentContext( agentId: string, role: string, customPaths?: string[] ): SecurityContext { // Default permissions based on role const rolePermissions: Record<string, PermissionLevel[]> = { 'queen-coordinator': ['read', 'write', 'execute', 'admin'], 'security-architect': ['read', 'write', 'execute', 'admin'], 'coder': ['read', 'write', 'execute'], 'reviewer': ['read'], 'tester': ['read', 'execute'], default: ['read'], }; const permissions = rolePermissions[role] ?? rolePermissions.default; return SecurityContext.create({ principalId: agentId, principalType: 'agent', permissions, allowedPaths: customPaths ?? ['./src', './tests', './docs'], blockedPaths: ['/etc', '/var', '~/', '../'], allowedCommands: ['npm', 'npx', 'node', 'git', 'vitest'], blockedCommands: ['rm -rf /', 'dd', 'mkfs', 'format'], }); } } |