deepscan-cli 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +174 -59
  3. package/dist/bin/deepscan.js +189 -71
  4. package/dist/bin/deepscan.js.map +1 -1
  5. package/dist/{chunk-OSYJXVNF.js → chunk-KITQQYNW.js} +5071 -596
  6. package/dist/chunk-KITQQYNW.js.map +1 -0
  7. package/dist/index.d.ts +61 -5
  8. package/dist/index.js +13 -3
  9. package/package.json +23 -5
  10. package/rules/built-in/default-config.yml +28 -3
  11. package/rules/built-in/operations.yml +287 -0
  12. package/rules/built-in/security.yml +12 -6
  13. package/dist/chunk-OSYJXVNF.js.map +0 -1
  14. package/rules/built-in/converted-semgrep.yml +0 -37
  15. package/rules/built-in/semgrep-apex.yml +0 -336
  16. package/rules/built-in/semgrep-bash.yml +0 -362
  17. package/rules/built-in/semgrep-c.yml +0 -429
  18. package/rules/built-in/semgrep-clojure.yml +0 -166
  19. package/rules/built-in/semgrep-csharp.yml +0 -1260
  20. package/rules/built-in/semgrep-dart.yml +0 -21
  21. package/rules/built-in/semgrep-dockerfile.yml +0 -874
  22. package/rules/built-in/semgrep-elixir.yml +0 -146
  23. package/rules/built-in/semgrep-generic.yml +0 -2945
  24. package/rules/built-in/semgrep-go.yml +0 -2898
  25. package/rules/built-in/semgrep-hcl.yml +0 -8181
  26. package/rules/built-in/semgrep-html.yml +0 -94
  27. package/rules/built-in/semgrep-java.yml +0 -4219
  28. package/rules/built-in/semgrep-javascript.yml +0 -6243
  29. package/rules/built-in/semgrep-json.yml +0 -360
  30. package/rules/built-in/semgrep-kotlin.yml +0 -540
  31. package/rules/built-in/semgrep-lua.yml +0 -46
  32. package/rules/built-in/semgrep-ocaml.yml +0 -773
  33. package/rules/built-in/semgrep-php.yml +0 -1638
  34. package/rules/built-in/semgrep-python.yml +0 -11240
  35. package/rules/built-in/semgrep-regex.yml +0 -6444
  36. package/rules/built-in/semgrep-ruby.yml +0 -2687
  37. package/rules/built-in/semgrep-rust.yml +0 -278
  38. package/rules/built-in/semgrep-scala.yml +0 -807
  39. package/rules/built-in/semgrep-sh.yml +0 -46
  40. package/rules/built-in/semgrep-solidity.yml +0 -1046
  41. package/rules/built-in/semgrep-swift.yml +0 -200
  42. package/rules/built-in/semgrep-terraform.yml +0 -147
  43. package/rules/built-in/semgrep-typescript.yml +0 -6212
  44. package/rules/built-in/semgrep-xml.yml +0 -31
  45. package/rules/built-in/semgrep-yaml.yml +0 -2785
  46. package/rules/examples/custom-api-security.yml +0 -66
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rules/rule-engine.ts","../src/config/schema.ts","../src/config/defaults.ts","../src/core/pipeline.ts","../src/core/file-discovery.ts","../src/languages/registry.ts","../src/core/ai-validator.ts","../src/core/ast-parser.ts","../src/config/loader.ts","../src/reporters/console-reporter.ts","../src/reporters/base-reporter.ts","../src/reporters/json-reporter.ts","../src/reporters/csv-reporter.ts","../src/reporters/sarif-reporter.ts","../src/reporters/html-reporter.ts","../src/reporters/index.ts","../src/scanners/base-scanner.ts","../src/core/taint-tracker.ts","../src/scanners/security/analyzers/injection.ts","../src/scanners/security/analyzers/xss.ts","../src/scanners/security/analyzers/secrets.ts","../src/scanners/security/analyzers/auth.ts","../src/scanners/security/analyzers/crypto.ts","../src/scanners/security/analyzers/file-ops.ts","../src/scanners/security/analyzers/api-sec.ts","../src/scanners/security/index.ts","../src/scanners/quality/analyzers/complexity.ts","../src/scanners/quality/analyzers/code-smells.ts","../src/scanners/quality/analyzers/duplication.ts","../src/scanners/quality/analyzers/metrics.ts","../src/scanners/quality/index.ts","../src/scanners/cve/parsers/package-parser.ts","../src/scanners/cve/vulnerability-db.ts","../src/scanners/cve/index.ts"],"sourcesContent":["import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';\nimport { resolve, join, extname } from 'node:path';\nimport yaml from 'js-yaml';\nimport { consola } from 'consola';\nimport { RuleFileSchema } from '../config/schema.js';\nimport type { Rule, RuleFile } from '../types/rule.js';\nimport type { DeepScanConfig } from '../types/config.js';\nimport { resolveBuiltInPath } from '../config/defaults.js';\n\n/**\n * Rule Engine - loads, validates, filters, and manages rules\n */\nexport class RuleEngine {\n private rules: Map<string, Rule> = new Map();\n private config: DeepScanConfig;\n\n constructor(config: DeepScanConfig) {\n this.config = config;\n }\n\n /**\n * Initialize the rule engine by loading built-in and custom rules\n */\n async initialize(): Promise<void> {\n // Load built-in rules\n await this.loadBuiltInRules();\n\n // Load custom rules\n for (const customPath of this.config.rules.custom) {\n await this.loadRulesFromPath(resolve(customPath));\n }\n\n // Apply include/exclude filters\n this.applyFilters();\n\n consola.info(`Loaded ${this.rules.size} rules`);\n }\n\n /**\n * Get all active rules\n */\n getAllRules(): Rule[] {\n return Array.from(this.rules.values()).filter(r => r.enabled !== false);\n }\n\n /**\n * Get rules for a specific language\n */\n getRulesForLanguage(language: string): Rule[] {\n return this.getAllRules().filter(\n r => r.languages.includes(language) || r.languages.includes('*')\n );\n }\n\n /**\n * Get rules for a specific scanner type\n */\n getRulesForScanner(scannerType: 'security' | 'quality'): Rule[] {\n return this.getAllRules().filter(r => {\n const category = r.category;\n if (scannerType === 'security') {\n return ['injection', 'xss', 'secrets', 'auth', 'crypto', 'file-ops'].includes(category);\n }\n return ['complexity', 'duplication', 'code-smells', 'naming', 'metrics'].includes(category);\n });\n }\n\n /**\n * Get a specific rule by ID\n */\n getRule(id: string): Rule | undefined {\n return this.rules.get(id);\n }\n\n /**\n * Load built-in rules from the rules directory\n */\n private async loadBuiltInRules(): Promise<void> {\n try {\n const securityRulesPath = resolveBuiltInPath('security.yml');\n const qualityRulesPath = resolveBuiltInPath('quality.yml');\n\n await this.loadRuleFile(securityRulesPath);\n await this.loadRuleFile(qualityRulesPath);\n } catch (error) {\n consola.error('Failed to load built-in rules from YAML files:', error);\n }\n }\n\n /**\n * Load rules from a file or directory\n */\n private async loadRulesFromPath(rulesPath: string): Promise<void> {\n if (!existsSync(rulesPath)) {\n consola.warn(`Rules path not found: ${rulesPath}`);\n return;\n }\n\n try {\n const stat = statSync(rulesPath);\n\n if (stat.isDirectory()) {\n const files = readdirSync(rulesPath);\n for (const file of files) {\n if (file.endsWith('.yml') || file.endsWith('.yaml')) {\n await this.loadRuleFile(join(rulesPath, file));\n }\n }\n } else {\n await this.loadRuleFile(rulesPath);\n }\n } catch (error) {\n consola.error(`Failed to load rules from: ${rulesPath}`, error);\n }\n }\n\n /**\n * Load and validate a single rule YAML file\n */\n private async loadRuleFile(filePath: string): Promise<void> {\n try {\n const content = readFileSync(filePath, 'utf-8');\n const raw = yaml.load(content) as Record<string, unknown>;\n const validated = RuleFileSchema.parse(raw);\n\n for (const rule of validated.rules) {\n if (this.rules.has(rule.id)) {\n consola.debug(`Rule ${rule.id} overridden by: ${filePath}`);\n }\n this.rules.set(rule.id, rule as Rule);\n }\n\n consola.debug(`Loaded ${validated.rules.length} rules from: ${filePath}`);\n } catch (error) {\n consola.error(`Failed to parse rule file: ${filePath}`, error);\n }\n }\n\n /**\n * Apply include/exclude filters from configuration\n */\n private applyFilters(): void {\n const { include, exclude } = this.config.rules;\n\n // If include is not wildcard, filter to only included rules\n if (include.length > 0 && !include.includes('*')) {\n for (const [id] of this.rules) {\n const matches = include.some(pattern => matchRulePattern(id, pattern));\n if (!matches) {\n this.rules.delete(id);\n }\n }\n }\n\n // Remove excluded rules\n for (const pattern of exclude) {\n for (const [id] of this.rules) {\n if (matchRulePattern(id, pattern)) {\n this.rules.delete(id);\n }\n }\n }\n }\n}\n\n/**\n * Match a rule ID against a pattern (supports wildcards and category prefixes)\n */\nfunction matchRulePattern(ruleId: string, pattern: string): boolean {\n if (pattern === '*') return true;\n if (pattern === ruleId) return true;\n\n // Support category prefix: \"security/*\" matches \"security/sql-injection\"\n if (pattern.endsWith('/*')) {\n const prefix = pattern.slice(0, -2);\n return ruleId.startsWith(prefix + '/');\n }\n\n // Support glob-like matching\n const regex = new RegExp(\n '^' + pattern.replace(/\\*/g, '.*').replace(/\\?/g, '.') + '$'\n );\n return regex.test(ruleId);\n}\n\n// ─── Rule Engine Helpers ──────────────────────────────────────────────────\n\nexport { matchRulePattern };\n","import { z } from 'zod';\n\n/** Zod schema for validating DeepScan configuration files */\n\nconst SeveritySchema = z.enum(['critical', 'high', 'medium', 'low']);\nconst OutputFormatSchema = z.enum(['json', 'csv', 'html', 'sarif', 'console']);\n\nconst SecurityScannerSchema = z.object({\n enabled: z.boolean().default(true),\n severity: z.array(SeveritySchema).default(['critical', 'high', 'medium', 'low']),\n}).default({});\n\nconst QualityThresholdsSchema = z.object({\n maxComplexity: z.number().min(1).default(15),\n maxCognitiveComplexity: z.number().min(1).default(20),\n maxFileLength: z.number().min(10).default(500),\n maxFunctionLength: z.number().min(5).default(50),\n maxNestingDepth: z.number().min(1).default(4),\n minCommentRatio: z.number().min(0).max(1).default(0.1),\n}).default({});\n\nconst QualityScannerSchema = z.object({\n enabled: z.boolean().default(true),\n thresholds: QualityThresholdsSchema,\n}).default({});\n\nconst CVEScannerSchema = z.object({\n enabled: z.boolean().default(true),\n sources: z.array(z.string()).default(['osv']),\n failOnSeverity: SeveritySchema.optional(),\n}).default({});\n\nconst ScannersSchema = z.object({\n security: SecurityScannerSchema,\n quality: QualityScannerSchema,\n cve: CVEScannerSchema,\n}).default({});\n\nconst RulesSchema = z.object({\n include: z.array(z.string()).default(['*']),\n exclude: z.array(z.string()).default([]),\n custom: z.array(z.string()).default([]),\n}).default({});\n\nconst PathsSchema = z.object({\n include: z.array(z.string()).default(['**/*']),\n exclude: z.array(z.string()).default([\n 'node_modules/', '.git/',\n '**/node_modules/**', '**/.git/**',\n '**/*.min.js', '**/*.min.css', '**/*.map', '**/*.lock', '**/package-lock.json',\n ]),\n}).default({});\n\nconst OutputSchema = z.object({\n format: OutputFormatSchema.default('console'),\n file: z.string().optional(),\n verbose: z.boolean().default(false),\n colors: z.boolean().default(true),\n}).default({});\n\nconst AISchema = z.object({\n enabled: z.boolean().default(false),\n provider: z.enum(['openai', 'anthropic', 'ollama', 'google']).default('openai'),\n model: z.string().optional(),\n apiKey: z.string().optional(),\n baseUrl: z.string().optional(),\n maxFindings: z.number().min(1).default(20),\n temperature: z.number().min(0).max(2).default(0.1),\n}).default({});\n\nconst ContextSchema = z.object({\n projectType: z.enum(['web', 'api', 'library', 'mobile', 'cli', 'auto']).default('auto'),\n frameworks: z.array(z.string()).default([]),\n sensitivePatterns: z.array(z.string()).default([]),\n}).default({});\n\n/** Main configuration schema */\nexport const DeepScanConfigSchema = z.object({\n version: z.string().default('1.0'),\n scanners: ScannersSchema,\n rules: RulesSchema,\n languages: z.array(z.string()).default(['auto']),\n paths: PathsSchema,\n output: OutputSchema,\n ai: AISchema,\n context: ContextSchema,\n parallel: z.number().min(1).max(32).default(4),\n incremental: z.boolean().default(false),\n deep: z.boolean().default(false),\n});\n\n/** Rule YAML schema validation */\nconst RulePatternSchema = z.object({\n pattern: z.string().optional(),\n message: z.string().optional(),\n regex: z.string().optional(),\n regexFlags: z.string().optional(),\n}).refine(data => data.pattern || data.regex, {\n message: 'Either pattern or regex must be provided',\n});\n\nconst RuleConditionSchema = z.object({\n type: z.enum(['taint-check', 'context-check', 'scope-check', 'ast-check']),\n source: z.string().optional(),\n sink: z.string().optional(),\n in: z.array(z.string()).optional(),\n notIn: z.array(z.string()).optional(),\n scope: z.string().optional(),\n});\n\nconst RuleFixSchema = z.object({\n description: z.string(),\n replacement: z.string().optional(),\n});\n\nexport const RuleSchema = z.object({\n id: z.string().min(1),\n name: z.string().min(1),\n description: z.string(),\n category: z.string(),\n subcategory: z.string().optional(),\n severity: SeveritySchema,\n confidence: z.enum(['high', 'medium', 'low']),\n cwe: z.array(z.string()).optional(),\n owasp: z.array(z.string()).optional(),\n languages: z.array(z.string()),\n patterns: z.array(RulePatternSchema),\n conditions: z.array(RuleConditionSchema).optional(),\n fix: RuleFixSchema.optional(),\n tags: z.array(z.string()).optional(),\n references: z.array(z.string()).optional(),\n enabled: z.boolean().default(true),\n});\n\nexport const RuleFileSchema = z.object({\n rules: z.array(RuleSchema),\n});\n\nexport type ValidatedConfig = z.infer<typeof DeepScanConfigSchema>;\nexport type ValidatedRule = z.infer<typeof RuleSchema>;\n","import { readFileSync, existsSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport { dirname, resolve } from 'node:path';\nimport yaml from 'js-yaml';\nimport type { DeepScanConfig } from '../types/config.js';\n\n/**\n * Resolve the path of a built-in resource (YAML files) across development and production\n */\nexport function resolveBuiltInPath(filename: string): string {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n\n const searchPaths = [\n resolve(__dirname, `../../rules/built-in/${filename}`), // from dist/bin/\n resolve(__dirname, `../rules/built-in/${filename}`), // from dist/\n resolve(process.cwd(), `rules/built-in/${filename}`), // in dev mode\n ];\n\n for (const p of searchPaths) {\n if (existsSync(p)) return p;\n }\n throw new Error(`Built-in resource not found: ${filename}`);\n}\n\n/**\n * Synchronously load the default configuration from YAML\n */\nfunction loadDefaultConfig(): DeepScanConfig {\n try {\n const configPath = resolveBuiltInPath('default-config.yml');\n const content = readFileSync(configPath, 'utf-8');\n return yaml.load(content) as DeepScanConfig;\n } catch (error) {\n console.error('Failed to load default configuration from YAML:', error);\n // Hard fallback config in case resource loading completely fails\n return {\n version: '1.0',\n scanners: {\n security: { enabled: true, severity: ['critical', 'high', 'medium', 'low'] },\n quality: {\n enabled: false,\n thresholds: { maxComplexity: 15, maxCognitiveComplexity: 20, maxFileLength: 500, maxFunctionLength: 50, maxNestingDepth: 4, minCommentRatio: 0.1 }\n },\n cve: { enabled: false, sources: ['osv'], failOnSeverity: 'critical' }\n },\n rules: { include: ['*'], exclude: [], custom: [] },\n languages: ['auto'],\n paths: {\n include: ['**/*'],\n exclude: [\n 'node_modules/', '.git/',\n '**/node_modules/**', '**/.git/**',\n '**/*.min.js', '**/*.min.css', '**/*.map', '**/*.lock', '**/package-lock.json',\n ]\n },\n output: { format: 'console', verbose: false, colors: true },\n ai: { enabled: false },\n context: { projectType: 'auto', frameworks: [], sensitivePatterns: [] }\n } as unknown as DeepScanConfig;\n }\n}\n\nexport const DEFAULT_CONFIG = loadDefaultConfig();\n\n/** Preset configurations for common project types */\nexport const PRESETS: Record<string, Partial<DeepScanConfig>> = {\n 'node-api': {\n languages: ['javascript', 'typescript'],\n context: {\n projectType: 'api',\n frameworks: ['express', 'fastify', 'koa', 'nestjs'],\n sensitivePatterns: ['password', 'token', 'secret', 'api_key', 'authorization'],\n },\n paths: {\n include: ['src/**/*', 'lib/**/*', 'routes/**/*', 'controllers/**/*'],\n exclude: ['node_modules/', 'dist/', 'test/', '**/node_modules/**', '**/dist/**', '**/test/**', '**/*.test.*', '**/*.spec.*'],\n },\n },\n 'python-web': {\n languages: ['python'],\n context: {\n projectType: 'web',\n frameworks: ['django', 'flask', 'fastapi'],\n sensitivePatterns: ['password', 'secret_key', 'database_url', 'api_key'],\n },\n paths: {\n include: ['**/*.py'],\n exclude: ['__pycache__/**', '.venv/**', 'venv/**', 'tests/**', 'test/**'],\n },\n },\n 'java-spring': {\n languages: ['java'],\n context: {\n projectType: 'api',\n frameworks: ['spring', 'spring-boot'],\n sensitivePatterns: ['password', 'secret', 'credentials', 'apiKey'],\n },\n paths: {\n include: ['src/main/**/*.java'],\n exclude: ['target/**', 'src/test/**'],\n },\n },\n minimal: {\n scanners: {\n security: { enabled: true, severity: ['critical', 'high'] },\n quality: {\n enabled: false,\n thresholds: {\n maxComplexity: 15, maxCognitiveComplexity: 20,\n maxFileLength: 500, maxFunctionLength: 50,\n maxNestingDepth: 4, minCommentRatio: 0.1,\n },\n },\n cve: { enabled: false, sources: ['osv'] },\n },\n },\n};\n","import { createHash } from 'node:crypto';\nimport { consola } from 'consola';\nimport type { Finding, ScanResult, ScanSummary, Severity } from '../types/finding.js';\nimport type { DeepScanConfig } from '../types/config.js';\nimport type { IScanner, DiscoveredFile, PipelineOptions, ProgressCallback, ScanFileContext } from '../types/scanner.js';\nimport { discoverFiles, readFileContent } from './file-discovery.js';\nimport { RuleEngine } from '../rules/rule-engine.js';\nimport { getLanguageConfig } from '../languages/registry.js';\nimport { AIValidator } from './ai-validator.js';\nimport { ASTParser } from './ast-parser.js';\n\n/** DeepScan version */\nconst VERSION = '1.0.0';\n\n/**\n * Main scanning pipeline orchestrator\n */\nexport class ScanPipeline {\n private config: DeepScanConfig;\n private scanners: IScanner[] = [];\n private ruleEngine: RuleEngine;\n private astParser: ASTParser;\n private findings: Finding[] = [];\n\n constructor(config: DeepScanConfig) {\n this.config = config;\n this.ruleEngine = new RuleEngine(config);\n this.astParser = new ASTParser();\n }\n\n /**\n * Register a scanner engine\n */\n addScanner(scanner: IScanner): void {\n this.scanners.push(scanner);\n }\n\n /**\n * Run the full scanning pipeline\n */\n async run(options: PipelineOptions): Promise<ScanResult> {\n const startTime = Date.now();\n const { targetPath, onProgress } = options;\n\n consola.start('DeepScan v' + VERSION);\n consola.info(`Target: ${targetPath}`);\n\n // Step 1: Initialize rule engine\n await this.ruleEngine.initialize();\n\n // Step 1.5: Initialize AST parser (non-blocking, degrades gracefully)\n await this.astParser.initialize();\n\n // Step 2: Initialize all scanners\n for (const scanner of this.scanners) {\n await scanner.initialize(this.config);\n }\n\n // Step 3: Discover files\n const files = await discoverFiles(\n targetPath,\n this.config.paths,\n this.config.languages,\n );\n\n if (files.length === 0) {\n consola.warn('No files found to scan');\n return this.buildResult(targetPath, startTime, files.length);\n }\n\n // Step 4: Scan each file\n let processed = 0;\n const totalFiles = files.length;\n\n for (const file of files) {\n try {\n await this.scanFile(file);\n } catch (error) {\n consola.debug(`Error scanning ${file.relativePath}:`, error);\n }\n\n processed++;\n if (onProgress) {\n onProgress(processed, totalFiles, file.relativePath);\n }\n }\n\n // Step 4.5: AI Validation (if enabled)\n if (this.config.ai?.enabled) {\n try {\n const aiValidator = new AIValidator(this.config.ai);\n if (aiValidator.isAvailable()) {\n this.findings = await aiValidator.validateFindings(this.findings);\n // Filter out findings evaluated as false positives\n this.findings = this.findings.filter(f => !f.aiValidation || f.aiValidation.isValid !== false);\n }\n } catch (error) {\n consola.error('AI Validation failed:', error);\n }\n }\n\n // Step 5: Cleanup\n for (const scanner of this.scanners) {\n await scanner.destroy();\n }\n await this.astParser.destroy();\n\n // Step 6: Build and return result\n const result = this.buildResult(targetPath, startTime, files.length);\n\n consola.success(\n `Scan complete: ${result.summary.totalFindings} findings in ${result.summary.filesScanned} files (${result.summary.scanDuration}ms)`\n );\n\n return result;\n }\n\n /**\n * Scan a single file with all registered scanners\n */\n private async scanFile(file: DiscoveredFile): Promise<void> {\n const content = readFileContent(file.path);\n if (!content) return;\n\n // Get language-specific rules\n const rules = this.ruleEngine.getRulesForLanguage(file.language);\n\n // Build scan context\n // Parse AST tree for context-aware analysis (degrades gracefully if grammar unavailable)\n const tree = await this.astParser.parse(content, file.language, file.path);\n\n const context: ScanFileContext = {\n filePath: file.path,\n content,\n language: file.language,\n tree,\n parser: this.astParser.getParser(),\n config: this.config,\n rules,\n };\n\n // Run each scanner\n for (const scanner of this.scanners) {\n try {\n // Skip disabled scanners\n if (scanner.type === 'security' && !this.config.scanners.security.enabled) continue;\n if (scanner.type === 'quality' && !this.config.scanners.quality.enabled) continue;\n if (scanner.type === 'cve' && !this.config.scanners.cve.enabled) continue;\n\n // CVE scanner only processes dependency files\n if (scanner.type === 'cve' && !file.isDependencyFile) continue;\n\n // Security scanner skips lock files, vendor/bundle files, and minified files\n // These produce massive false positives with no real security value\n if (scanner.type === 'security') {\n if (file.isLockFile || file.isVendorFile || file.isMinified) continue;\n }\n\n const findings = await scanner.scanFile(context);\n\n // Filter by configured severity\n const filteredFindings = findings.filter(f => {\n if (scanner.type === 'security') {\n return this.config.scanners.security.severity.includes(f.severity);\n }\n return true;\n });\n\n this.findings.push(...filteredFindings);\n } catch (error) {\n consola.debug(`Scanner ${scanner.name} failed on ${file.relativePath}:`, error);\n }\n }\n }\n\n /**\n * Build the final scan result\n */\n private buildResult(targetPath: string, startTime: number, filesScanned: number): ScanResult {\n const duration = Date.now() - startTime;\n\n // Deduplicate findings by fingerprint AND smart line+category grouping for security scanner\n const seenFingerprints = new Set<string>();\n const groupedSecurityFindings = new Map<string, Finding[]>();\n const deduped: Finding[] = [];\n\n for (const finding of this.findings) {\n if (seenFingerprints.has(finding.metadata.fingerprint)) {\n continue;\n }\n seenFingerprints.add(finding.metadata.fingerprint);\n\n if (finding.scanner === 'security') {\n // Group by file, line, and category to catch rules that overlap\n const key = `${finding.location.file}:${finding.location.startLine}:${finding.category}`;\n if (!groupedSecurityFindings.has(key)) {\n groupedSecurityFindings.set(key, []);\n }\n groupedSecurityFindings.get(key)!.push(finding);\n } else {\n deduped.push(finding);\n }\n }\n\n for (const [_, group] of groupedSecurityFindings.entries()) {\n if (group.length === 1) {\n deduped.push(group[0]);\n } else {\n // Sort to find the best finding to keep:\n // 1. Prefer specific rules (e.g. starting with SEC-) over generic ones (starting with security/)\n // 2. Prefer higher severity (critical > high > medium > low)\n // 3. Prefer longer/more descriptive message\n group.sort((a, b) => {\n const isGenericA = a.ruleId.startsWith('security/');\n const isGenericB = b.ruleId.startsWith('security/');\n \n if (isGenericA && !isGenericB) return 1;\n if (!isGenericA && isGenericB) return -1;\n \n const severityOrder: Record<Severity, number> = { critical: 0, high: 1, medium: 2, low: 3 };\n const aSev = severityOrder[a.severity] ?? 4;\n const bSev = severityOrder[b.severity] ?? 4;\n const sevDiff = aSev - bSev;\n if (sevDiff !== 0) return sevDiff;\n \n return b.message.length - a.message.length;\n });\n \n deduped.push(group[0]);\n }\n }\n\n // Sort findings: critical first, then by file\n deduped.sort((a, b) => {\n const severityOrder: Record<Severity, number> = { critical: 0, high: 1, medium: 2, low: 3 };\n const sevDiff = severityOrder[a.severity] - severityOrder[b.severity];\n if (sevDiff !== 0) return sevDiff;\n return a.location.file.localeCompare(b.location.file);\n });\n\n // Build summary\n const filesWithFindings = new Set(deduped.map(f => f.location.file)).size;\n const summary: ScanSummary = {\n totalFindings: deduped.length,\n bySeverity: {\n critical: deduped.filter(f => f.severity === 'critical').length,\n high: deduped.filter(f => f.severity === 'high').length,\n medium: deduped.filter(f => f.severity === 'medium').length,\n low: deduped.filter(f => f.severity === 'low').length,\n },\n byScanner: {\n security: deduped.filter(f => f.scanner === 'security').length,\n quality: deduped.filter(f => f.scanner === 'quality').length,\n cve: deduped.filter(f => f.scanner === 'cve').length,\n },\n byCategory: {},\n filesScanned,\n filesWithFindings,\n scanDuration: duration,\n timestamp: new Date().toISOString(),\n };\n\n // Count by category\n for (const finding of deduped) {\n summary.byCategory[finding.category] = (summary.byCategory[finding.category] || 0) + 1;\n }\n\n return {\n version: VERSION,\n tool: { name: 'DeepScan', version: VERSION },\n target: targetPath,\n config: this.config.version,\n summary,\n findings: deduped,\n };\n }\n}\n\n/**\n * Generate a unique fingerprint for a finding (for deduplication across scans)\n */\nexport function generateFingerprint(\n ruleId: string,\n filePath: string,\n line: number,\n snippet: string,\n): string {\n const hash = createHash('sha256');\n hash.update(`${ruleId}:${filePath}:${line}:${snippet.trim().slice(0, 100)}`);\n return hash.digest('hex').slice(0, 16);\n}\n","import { readFileSync, statSync } from 'node:fs';\nimport { resolve, relative, extname, basename } from 'node:path';\nimport { glob } from 'glob';\nimport ignore, { type Ignore } from 'ignore';\nimport { consola } from 'consola';\nimport type { DiscoveredFile } from '../types/scanner.js';\nimport type { PathsConfig } from '../types/config.js';\nimport { getLanguageByExtension } from '../languages/registry.js';\n\n/** Dependency manifest files that trigger CVE scanning */\nconst DEPENDENCY_FILES = new Set([\n 'package.json', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',\n 'requirements.txt', 'Pipfile', 'Pipfile.lock', 'poetry.lock', 'setup.py', 'setup.cfg', 'pyproject.toml',\n 'pom.xml', 'build.gradle', 'build.gradle.kts', 'gradle.lockfile',\n 'go.mod', 'go.sum',\n 'Cargo.toml', 'Cargo.lock',\n 'Gemfile', 'Gemfile.lock',\n 'composer.json', 'composer.lock',\n 'packages.config', 'Directory.Packages.props',\n]);\n\n/** Lock files — should be scanned for CVE but NOT for security patterns */\nconst LOCK_FILES = new Set([\n 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml',\n 'Pipfile.lock', 'poetry.lock', 'composer.lock',\n 'Cargo.lock', 'Gemfile.lock', 'gradle.lockfile',\n 'go.sum',\n]);\n\n/** Vendor/third-party directory patterns */\nconst VENDOR_DIR_PATTERN = /(?:^|[\\\\/])(?:vendor|third[_-]?party|bower_components|externals?)[\\\\/]/i;\n\n/** Known vendor/bundled files by filename */\nconst KNOWN_VENDOR_FILES_PATTERN = /(?:jquery|lodash|underscore|backbone|angular|react\\.production|vue\\.global|bootstrap|popper|moment(?:\\.min)?|d3|select2|sweetalert|highlight|firebug)(?:[\\.-][\\w.]+)?\\.js$/i;\n\n/** Minified file patterns */\nconst MINIFIED_PATTERN = /\\.min\\.(?:js|css)$/i;\n\n/** Test file/directory patterns */\nconst TEST_PATH_PATTERN = /(?:^|[\\\\/])(?:tests?|__tests__|spec|__spec__|fixtures?|mocks?|__mocks__|e2e|integration|cypress|playwright)[\\\\/]/i;\nconst TEST_FILE_PATTERN = /\\.(?:test|spec|mock|fixture|e2e|cy)\\./i;\n\nfunction classifyFile(relPath: string, name: string): {\n isLockFile: boolean;\n isVendorFile: boolean;\n isMinified: boolean;\n isTestFile: boolean;\n} {\n return {\n isLockFile: LOCK_FILES.has(name),\n isVendorFile: VENDOR_DIR_PATTERN.test(relPath) || KNOWN_VENDOR_FILES_PATTERN.test(name),\n isMinified: MINIFIED_PATTERN.test(name),\n isTestFile: TEST_PATH_PATTERN.test(relPath) || TEST_FILE_PATTERN.test(name),\n };\n}\n\n/** Binary/generated file extensions to always skip */\nconst SKIP_EXTENSIONS = new Set([\n '.exe', '.dll', '.so', '.dylib', '.o', '.obj', '.class',\n '.jar', '.war', '.ear', '.zip', '.tar', '.gz', '.rar',\n '.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg', '.bmp', '.webp',\n '.mp3', '.mp4', '.wav', '.avi', '.mov', '.wmv',\n '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',\n '.woff', '.woff2', '.ttf', '.eot', '.otf',\n '.pyc', '.pyo', '.wasm',\n]);\n\n/**\n * Discover all files to scan in the target directory\n */\nexport async function discoverFiles(\n targetPath: string,\n paths: PathsConfig,\n languages: string[],\n): Promise<DiscoveredFile[]> {\n const absoluteTarget = resolve(targetPath);\n\n // If targetPath is a file, return it directly if it matches language and size limits\n try {\n const stat = statSync(absoluteTarget);\n if (stat.isFile()) {\n const ext = extname(absoluteTarget).toLowerCase();\n const name = basename(absoluteTarget);\n \n // Skip binary files\n if (SKIP_EXTENSIONS.has(ext)) {\n return [];\n }\n \n const language = getLanguageByExtension(ext);\n if (!language && !DEPENDENCY_FILES.has(name)) {\n return [];\n }\n\n // Filter by configured languages\n if (\n languages.length > 0 &&\n !languages.includes('auto') &&\n language &&\n !languages.includes(language)\n ) {\n return [];\n }\n\n // Skip very large files (>5MB)\n if (stat.size > 5 * 1024 * 1024) {\n consola.debug(`Skipping large file: ${name} (${(stat.size / 1024 / 1024).toFixed(1)}MB)`);\n return [];\n }\n\n consola.info(`Discovered 1 file to scan`);\n const classification = classifyFile(name, name);\n return [{\n path: absoluteTarget,\n relativePath: name,\n language: language || 'unknown',\n size: stat.size,\n isDependencyFile: DEPENDENCY_FILES.has(name),\n ...classification,\n }];\n }\n } catch {\n // If file/directory doesn't exist, proceed to globbing which will handle/log\n }\n\n // Load .gitignore and .deepscanignore\n const ig = ignore();\n loadIgnoreFile(absoluteTarget, '.gitignore', ig);\n loadIgnoreFile(absoluteTarget, '.deepscanignore', ig);\n\n // Add configured exclude patterns\n for (const pattern of paths.exclude) {\n ig.add(pattern);\n }\n\n // Find all matching files\n const files = await glob(paths.include, {\n cwd: absoluteTarget,\n nodir: true,\n dot: false,\n absolute: false,\n });\n\n const discovered: DiscoveredFile[] = [];\n\n for (const relPath of files) {\n // Check ignore patterns\n if (ig.ignores(relPath)) continue;\n\n const ext = extname(relPath).toLowerCase();\n const name = basename(relPath);\n const absPath = resolve(absoluteTarget, relPath);\n\n // Skip binary files\n if (SKIP_EXTENSIONS.has(ext)) continue;\n\n // Detect language\n const language = getLanguageByExtension(ext);\n if (!language && !DEPENDENCY_FILES.has(name)) continue;\n\n // Filter by configured languages\n if (\n languages.length > 0 &&\n !languages.includes('auto') &&\n language &&\n !languages.includes(language)\n ) {\n continue;\n }\n\n // Get file size\n let size = 0;\n try {\n const stat = statSync(absPath);\n size = stat.size;\n\n // Skip very large files (>5MB)\n if (size > 5 * 1024 * 1024) {\n consola.debug(`Skipping large file: ${relPath} (${(size / 1024 / 1024).toFixed(1)}MB)`);\n continue;\n }\n } catch {\n continue;\n }\n\n const classification = classifyFile(relPath, name);\n discovered.push({\n path: absPath,\n relativePath: relPath,\n language: language || 'unknown',\n size,\n isDependencyFile: DEPENDENCY_FILES.has(name),\n ...classification,\n });\n }\n\n consola.info(`Discovered ${discovered.length} files to scan`);\n return discovered;\n}\n\n/**\n * Load an ignore file (.gitignore or .deepscanignore)\n */\nfunction loadIgnoreFile(\n dir: string,\n fileName: string,\n ig: Ignore,\n): void {\n try {\n const filePath = resolve(dir, fileName);\n const content = readFileSync(filePath, 'utf-8');\n ig.add(content);\n } catch {\n // File doesn't exist, skip\n }\n}\n\n/**\n * Read file content safely\n */\nexport function readFileContent(filePath: string): string | null {\n try {\n return readFileSync(filePath, 'utf-8');\n } catch (error) {\n consola.debug(`Failed to read file: ${filePath}`, error);\n return null;\n }\n}\n","import type { LanguageConfig } from '../types/scanner.js';\n\n// ─── Language Configurations ───────────────────────────────────────────────\n\nconst LANGUAGES: LanguageConfig[] = [\n {\n id: 'javascript',\n name: 'JavaScript',\n extensions: ['.js', '.jsx', '.mjs', '.cjs'],\n treeSitterLanguage: 'javascript',\n taintSources: [\n { pattern: 'req.body', type: 'user_input', description: 'Express request body' },\n { pattern: 'req.query', type: 'user_input', description: 'Express query parameters' },\n { pattern: 'req.params', type: 'user_input', description: 'Express route parameters' },\n { pattern: 'req.headers', type: 'user_input', description: 'HTTP request headers' },\n { pattern: 'document.location', type: 'user_input', description: 'Browser URL' },\n { pattern: 'window.location', type: 'user_input', description: 'Browser URL' },\n { pattern: 'document.cookie', type: 'user_input', description: 'Browser cookies' },\n { pattern: 'process.env', type: 'environment', description: 'Environment variables' },\n { pattern: 'localStorage.getItem', type: 'user_input', description: 'Local storage' },\n { pattern: 'document.getElementById', type: 'user_input', description: 'DOM element value' },\n ],\n taintSinks: [\n { pattern: 'eval($TAINTED)', type: 'code_injection', description: 'eval() call' },\n { pattern: 'innerHTML', type: 'xss', description: 'innerHTML assignment' },\n { pattern: 'document.write($TAINTED)', type: 'xss', description: 'document.write' },\n { pattern: 'exec($TAINTED)', type: 'command_injection', description: 'child_process.exec' },\n { pattern: 'execSync($TAINTED)', type: 'command_injection', description: 'child_process.execSync' },\n { pattern: 'query($TAINTED)', type: 'sql_injection', description: 'SQL query' },\n { pattern: 'raw($TAINTED)', type: 'sql_injection', description: 'Raw SQL query' },\n ],\n sanitizers: [\n { pattern: 'encodeURIComponent($X)', cleanses: ['xss'], description: 'URL encoding' },\n { pattern: 'escape($X)', cleanses: ['xss', 'sql_injection'], description: 'Generic escape' },\n { pattern: 'DOMPurify.sanitize($X)', cleanses: ['xss'], description: 'DOMPurify sanitizer' },\n { pattern: 'parseInt($X)', cleanses: ['sql_injection', 'xss'], description: 'Integer parsing' },\n ],\n namingConventions: {\n variables: 'camelCase',\n functions: 'camelCase',\n classes: 'PascalCase',\n constants: 'UPPER_SNAKE_CASE',\n },\n frameworks: ['express', 'react', 'vue', 'angular', 'next', 'nestjs', 'fastify', 'koa'],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n {\n id: 'typescript',\n name: 'TypeScript',\n extensions: ['.ts', '.tsx', '.mts', '.cts'],\n treeSitterLanguage: 'typescript',\n taintSources: [\n { pattern: 'req.body', type: 'user_input', description: 'Express request body' },\n { pattern: 'req.query', type: 'user_input', description: 'Express query parameters' },\n { pattern: 'req.params', type: 'user_input', description: 'Express route parameters' },\n { pattern: 'req.headers', type: 'user_input', description: 'HTTP request headers' },\n { pattern: 'process.env', type: 'environment', description: 'Environment variables' },\n ],\n taintSinks: [\n { pattern: 'eval($TAINTED)', type: 'code_injection', description: 'eval() call' },\n { pattern: 'innerHTML', type: 'xss', description: 'innerHTML assignment' },\n { pattern: 'exec($TAINTED)', type: 'command_injection', description: 'child_process.exec' },\n { pattern: 'query($TAINTED)', type: 'sql_injection', description: 'SQL query' },\n ],\n sanitizers: [\n { pattern: 'encodeURIComponent($X)', cleanses: ['xss'], description: 'URL encoding' },\n { pattern: 'parseInt($X)', cleanses: ['sql_injection', 'xss'], description: 'Integer parsing' },\n ],\n namingConventions: {\n variables: 'camelCase',\n functions: 'camelCase',\n classes: 'PascalCase',\n constants: 'UPPER_SNAKE_CASE',\n },\n frameworks: ['express', 'react', 'vue', 'angular', 'next', 'nestjs', 'fastify'],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n {\n id: 'python',\n name: 'Python',\n extensions: ['.py', '.pyw'],\n treeSitterLanguage: 'python',\n taintSources: [\n { pattern: 'request.form', type: 'user_input', description: 'Flask form data' },\n { pattern: 'request.args', type: 'user_input', description: 'Flask query args' },\n { pattern: 'request.json', type: 'user_input', description: 'Flask JSON body' },\n { pattern: 'request.data', type: 'user_input', description: 'Django request data' },\n { pattern: 'request.GET', type: 'user_input', description: 'Django GET params' },\n { pattern: 'request.POST', type: 'user_input', description: 'Django POST data' },\n { pattern: 'input()', type: 'user_input', description: 'Console input' },\n { pattern: 'os.environ', type: 'environment', description: 'Environment variables' },\n { pattern: 'sys.argv', type: 'user_input', description: 'CLI arguments' },\n ],\n taintSinks: [\n { pattern: 'eval($TAINTED)', type: 'code_injection', description: 'eval() call' },\n { pattern: 'exec($TAINTED)', type: 'code_injection', description: 'exec() call' },\n { pattern: 'os.system($TAINTED)', type: 'command_injection', description: 'OS command execution' },\n { pattern: 'subprocess.call($TAINTED)', type: 'command_injection', description: 'Subprocess call' },\n { pattern: 'cursor.execute($TAINTED)', type: 'sql_injection', description: 'SQL query' },\n { pattern: 'open($TAINTED)', type: 'path_traversal', description: 'File open' },\n { pattern: 'pickle.loads($TAINTED)', type: 'deserialization', description: 'Pickle deserialization' },\n ],\n sanitizers: [\n { pattern: 'bleach.clean($X)', cleanses: ['xss'], description: 'Bleach HTML sanitizer' },\n { pattern: 'escape($X)', cleanses: ['xss'], description: 'HTML escape' },\n { pattern: 'int($X)', cleanses: ['sql_injection'], description: 'Integer conversion' },\n { pattern: 'shlex.quote($X)', cleanses: ['command_injection'], description: 'Shell quoting' },\n ],\n namingConventions: {\n variables: 'snake_case',\n functions: 'snake_case',\n classes: 'PascalCase',\n constants: 'UPPER_SNAKE_CASE',\n },\n frameworks: ['django', 'flask', 'fastapi', 'tornado', 'pyramid', 'starlette'],\n commentPatterns: { single: '#', multiStart: '\"\"\"', multiEnd: '\"\"\"' },\n },\n {\n id: 'java',\n name: 'Java',\n extensions: ['.java'],\n treeSitterLanguage: 'java',\n taintSources: [\n { pattern: 'request.getParameter', type: 'user_input', description: 'Servlet parameter' },\n { pattern: 'request.getHeader', type: 'user_input', description: 'HTTP header' },\n { pattern: 'request.getInputStream', type: 'user_input', description: 'Request body' },\n { pattern: '@RequestParam', type: 'user_input', description: 'Spring request param' },\n { pattern: '@RequestBody', type: 'user_input', description: 'Spring request body' },\n { pattern: '@PathVariable', type: 'user_input', description: 'Spring path variable' },\n { pattern: 'Scanner.nextLine', type: 'user_input', description: 'Console input' },\n ],\n taintSinks: [\n { pattern: 'Runtime.exec($TAINTED)', type: 'command_injection', description: 'Runtime exec' },\n { pattern: 'Statement.execute($TAINTED)', type: 'sql_injection', description: 'SQL statement' },\n { pattern: 'Statement.executeQuery($TAINTED)', type: 'sql_injection', description: 'SQL query' },\n { pattern: 'new File($TAINTED)', type: 'path_traversal', description: 'File path' },\n { pattern: 'ObjectInputStream.readObject', type: 'deserialization', description: 'Deserialization' },\n ],\n sanitizers: [\n { pattern: 'PreparedStatement', cleanses: ['sql_injection'], description: 'Prepared statements' },\n { pattern: 'Integer.parseInt($X)', cleanses: ['sql_injection'], description: 'Integer parsing' },\n { pattern: 'ESAPI.encoder().encodeForHTML($X)', cleanses: ['xss'], description: 'ESAPI encoding' },\n ],\n namingConventions: {\n variables: 'camelCase',\n functions: 'camelCase',\n classes: 'PascalCase',\n constants: 'UPPER_SNAKE_CASE',\n },\n frameworks: ['spring', 'spring-boot', 'struts', 'jakarta', 'quarkus', 'micronaut'],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n {\n id: 'go',\n name: 'Go',\n extensions: ['.go'],\n treeSitterLanguage: 'go',\n taintSources: [\n { pattern: 'r.URL.Query', type: 'user_input', description: 'HTTP query params' },\n { pattern: 'r.FormValue', type: 'user_input', description: 'Form value' },\n { pattern: 'r.Body', type: 'user_input', description: 'Request body' },\n { pattern: 'r.Header.Get', type: 'user_input', description: 'HTTP header' },\n { pattern: 'os.Args', type: 'user_input', description: 'CLI arguments' },\n { pattern: 'os.Getenv', type: 'environment', description: 'Environment variable' },\n ],\n taintSinks: [\n { pattern: 'exec.Command($TAINTED)', type: 'command_injection', description: 'OS command' },\n { pattern: 'db.Query($TAINTED)', type: 'sql_injection', description: 'SQL query' },\n { pattern: 'db.Exec($TAINTED)', type: 'sql_injection', description: 'SQL exec' },\n { pattern: 'fmt.Fprintf(w, $TAINTED)', type: 'xss', description: 'HTTP response write' },\n { pattern: 'template.HTML($TAINTED)', type: 'xss', description: 'Unescaped HTML' },\n { pattern: 'os.Open($TAINTED)', type: 'path_traversal', description: 'File open' },\n ],\n sanitizers: [\n { pattern: 'template.HTMLEscapeString($X)', cleanses: ['xss'], description: 'HTML escaping' },\n { pattern: 'url.QueryEscape($X)', cleanses: ['xss'], description: 'URL escaping' },\n { pattern: 'strconv.Atoi($X)', cleanses: ['sql_injection'], description: 'String to int' },\n ],\n namingConventions: {\n variables: 'camelCase',\n functions: 'camelCase',\n classes: 'PascalCase',\n constants: 'camelCase',\n },\n frameworks: ['gin', 'echo', 'fiber', 'chi', 'gorilla', 'net/http'],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n {\n id: 'c',\n name: 'C',\n extensions: ['.c', '.h'],\n treeSitterLanguage: 'c',\n taintSources: [\n { pattern: 'argv', type: 'user_input', description: 'CLI arguments' },\n { pattern: 'scanf', type: 'user_input', description: 'Standard input' },\n { pattern: 'gets', type: 'user_input', description: 'Standard input (unsafe)' },\n { pattern: 'fgets', type: 'user_input', description: 'File/stdin input' },\n { pattern: 'getenv', type: 'environment', description: 'Environment variable' },\n { pattern: 'recv', type: 'network', description: 'Network receive' },\n ],\n taintSinks: [\n { pattern: 'system($TAINTED)', type: 'command_injection', description: 'System command' },\n { pattern: 'exec($TAINTED)', type: 'command_injection', description: 'Exec command' },\n { pattern: 'printf($TAINTED)', type: 'format_string', description: 'Format string' },\n { pattern: 'strcpy($BUF, $TAINTED)', type: 'buffer_overflow', description: 'Buffer copy' },\n { pattern: 'strcat($BUF, $TAINTED)', type: 'buffer_overflow', description: 'Buffer concat' },\n ],\n sanitizers: [],\n namingConventions: {\n variables: 'snake_case',\n functions: 'snake_case',\n classes: 'PascalCase',\n constants: 'UPPER_SNAKE_CASE',\n },\n frameworks: [],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n {\n id: 'cpp',\n name: 'C++',\n extensions: ['.cpp', '.cc', '.cxx', '.hpp', '.hh', '.hxx'],\n treeSitterLanguage: 'cpp',\n taintSources: [\n { pattern: 'argv', type: 'user_input', description: 'CLI arguments' },\n { pattern: 'cin', type: 'user_input', description: 'Standard input' },\n { pattern: 'getline', type: 'user_input', description: 'Line input' },\n { pattern: 'getenv', type: 'environment', description: 'Environment variable' },\n ],\n taintSinks: [\n { pattern: 'system($TAINTED)', type: 'command_injection', description: 'System command' },\n { pattern: 'strcpy($BUF, $TAINTED)', type: 'buffer_overflow', description: 'Buffer copy' },\n { pattern: 'sprintf($BUF, $TAINTED)', type: 'buffer_overflow', description: 'Sprintf' },\n ],\n sanitizers: [],\n namingConventions: {\n variables: 'camelCase',\n functions: 'camelCase',\n classes: 'PascalCase',\n constants: 'UPPER_SNAKE_CASE',\n },\n frameworks: ['qt', 'boost', 'poco'],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n {\n id: 'csharp',\n name: 'C#',\n extensions: ['.cs'],\n treeSitterLanguage: 'c_sharp',\n taintSources: [\n { pattern: 'Request.QueryString', type: 'user_input', description: 'Query string' },\n { pattern: 'Request.Form', type: 'user_input', description: 'Form data' },\n { pattern: 'Request.Headers', type: 'user_input', description: 'HTTP headers' },\n ],\n taintSinks: [\n { pattern: 'Process.Start($TAINTED)', type: 'command_injection', description: 'Process start' },\n { pattern: 'SqlCommand($TAINTED)', type: 'sql_injection', description: 'SQL command' },\n ],\n sanitizers: [\n { pattern: 'HttpUtility.HtmlEncode($X)', cleanses: ['xss'], description: 'HTML encoding' },\n ],\n namingConventions: {\n variables: 'camelCase',\n functions: 'PascalCase',\n classes: 'PascalCase',\n constants: 'PascalCase',\n },\n frameworks: ['aspnet', 'blazor', 'maui'],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n {\n id: 'php',\n name: 'PHP',\n extensions: ['.php', '.phtml'],\n treeSitterLanguage: 'php',\n taintSources: [\n { pattern: '$_GET', type: 'user_input', description: 'GET parameters' },\n { pattern: '$_POST', type: 'user_input', description: 'POST data' },\n { pattern: '$_REQUEST', type: 'user_input', description: 'Request data' },\n { pattern: '$_COOKIE', type: 'user_input', description: 'Cookie data' },\n { pattern: '$_SERVER', type: 'user_input', description: 'Server variables' },\n { pattern: '$_FILES', type: 'user_input', description: 'Uploaded files' },\n ],\n taintSinks: [\n { pattern: 'eval($TAINTED)', type: 'code_injection', description: 'eval()' },\n { pattern: 'exec($TAINTED)', type: 'command_injection', description: 'exec()' },\n { pattern: 'system($TAINTED)', type: 'command_injection', description: 'system()' },\n { pattern: 'mysql_query($TAINTED)', type: 'sql_injection', description: 'MySQL query' },\n { pattern: 'echo $TAINTED', type: 'xss', description: 'Echo output' },\n { pattern: 'include($TAINTED)', type: 'file_inclusion', description: 'File inclusion' },\n ],\n sanitizers: [\n { pattern: 'htmlspecialchars($X)', cleanses: ['xss'], description: 'HTML encoding' },\n { pattern: 'mysqli_real_escape_string($X)', cleanses: ['sql_injection'], description: 'SQL escaping' },\n { pattern: 'intval($X)', cleanses: ['sql_injection'], description: 'Integer conversion' },\n ],\n namingConventions: {\n variables: 'camelCase',\n functions: 'camelCase',\n classes: 'PascalCase',\n constants: 'UPPER_SNAKE_CASE',\n },\n frameworks: ['laravel', 'symfony', 'wordpress', 'drupal'],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n {\n id: 'ruby',\n name: 'Ruby',\n extensions: ['.rb', '.rake'],\n treeSitterLanguage: 'ruby',\n taintSources: [\n { pattern: 'params', type: 'user_input', description: 'Rails parameters' },\n { pattern: 'request.body', type: 'user_input', description: 'Request body' },\n { pattern: 'request.headers', type: 'user_input', description: 'HTTP headers' },\n { pattern: 'ENV', type: 'environment', description: 'Environment variables' },\n ],\n taintSinks: [\n { pattern: 'eval($TAINTED)', type: 'code_injection', description: 'eval()' },\n { pattern: 'system($TAINTED)', type: 'command_injection', description: 'system()' },\n { pattern: 'exec($TAINTED)', type: 'command_injection', description: 'exec()' },\n { pattern: '.where($TAINTED)', type: 'sql_injection', description: 'ActiveRecord where' },\n { pattern: 'raw($TAINTED)', type: 'xss', description: 'Raw HTML output' },\n { pattern: 'Marshal.load($TAINTED)', type: 'deserialization', description: 'Marshal deserialization' },\n ],\n sanitizers: [\n { pattern: 'sanitize($X)', cleanses: ['xss'], description: 'Rails sanitize' },\n { pattern: 'h($X)', cleanses: ['xss'], description: 'HTML escape helper' },\n ],\n namingConventions: {\n variables: 'snake_case',\n functions: 'snake_case',\n classes: 'PascalCase',\n constants: 'UPPER_SNAKE_CASE',\n },\n frameworks: ['rails', 'sinatra', 'hanami'],\n commentPatterns: { single: '#', multiStart: '=begin', multiEnd: '=end' },\n },\n {\n id: 'rust',\n name: 'Rust',\n extensions: ['.rs'],\n treeSitterLanguage: 'rust',\n taintSources: [\n { pattern: 'std::env::args', type: 'user_input', description: 'CLI arguments' },\n { pattern: 'std::io::stdin', type: 'user_input', description: 'Standard input' },\n { pattern: 'std::env::var', type: 'environment', description: 'Environment variable' },\n ],\n taintSinks: [\n { pattern: 'Command::new($TAINTED)', type: 'command_injection', description: 'OS command' },\n { pattern: 'format!($TAINTED)', type: 'format_string', description: 'Format string' },\n ],\n sanitizers: [],\n namingConventions: {\n variables: 'snake_case',\n functions: 'snake_case',\n classes: 'PascalCase',\n constants: 'UPPER_SNAKE_CASE',\n },\n frameworks: ['actix', 'rocket', 'axum', 'warp', 'tokio'],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n {\n id: 'kotlin',\n name: 'Kotlin',\n extensions: ['.kt', '.kts'],\n treeSitterLanguage: 'kotlin',\n taintSources: [\n { pattern: 'request.queryParams', type: 'user_input', description: 'Query parameters' },\n { pattern: 'call.receive', type: 'user_input', description: 'Ktor request body' },\n ],\n taintSinks: [\n { pattern: 'Runtime.exec($TAINTED)', type: 'command_injection', description: 'Runtime exec' },\n { pattern: 'createQuery($TAINTED)', type: 'sql_injection', description: 'JPA query' },\n ],\n sanitizers: [],\n namingConventions: {\n variables: 'camelCase',\n functions: 'camelCase',\n classes: 'PascalCase',\n constants: 'UPPER_SNAKE_CASE',\n },\n frameworks: ['ktor', 'spring-boot', 'android'],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n {\n id: 'swift',\n name: 'Swift',\n extensions: ['.swift'],\n treeSitterLanguage: 'swift',\n taintSources: [\n { pattern: 'URLRequest', type: 'network', description: 'URL request' },\n { pattern: 'UserDefaults', type: 'user_input', description: 'User defaults' },\n ],\n taintSinks: [\n { pattern: 'Process.launch', type: 'command_injection', description: 'Process launch' },\n ],\n sanitizers: [],\n namingConventions: {\n variables: 'camelCase',\n functions: 'camelCase',\n classes: 'PascalCase',\n constants: 'camelCase',\n },\n frameworks: ['vapor', 'swiftui', 'uikit'],\n commentPatterns: { single: '//', multiStart: '/*', multiEnd: '*/' },\n },\n];\n\n// ─── Registry Functions ────────────────────────────────────────────────────\n\n/** Extension to language ID mapping (built from LANGUAGES) */\nconst EXTENSION_MAP = new Map<string, string>();\nfor (const lang of LANGUAGES) {\n for (const ext of lang.extensions) {\n EXTENSION_MAP.set(ext, lang.id);\n }\n}\n\n/**\n * Get language ID by file extension\n */\nexport function getLanguageByExtension(ext: string): string | null {\n return EXTENSION_MAP.get(ext.toLowerCase()) ?? null;\n}\n\n/**\n * Get full language configuration by ID\n */\nexport function getLanguageConfig(id: string): LanguageConfig | null {\n return LANGUAGES.find(l => l.id === id) ?? null;\n}\n\n/**\n * Get all registered languages\n */\nexport function getAllLanguages(): LanguageConfig[] {\n return LANGUAGES;\n}\n\n/**\n * Get all supported file extensions\n */\nexport function getSupportedExtensions(): string[] {\n return Array.from(EXTENSION_MAP.keys());\n}\n\n/**\n * Check if a language is supported\n */\nexport function isLanguageSupported(id: string): boolean {\n return LANGUAGES.some(l => l.id === id);\n}\n","import { consola } from 'consola';\nimport type { Finding, AIValidationResult } from '../types/finding.js';\nimport type { AIConfig } from '../types/config.js';\n\n/**\n * AI Validator - Uses LLM to validate findings and reduce false positives\n *\n * This is an OPTIONAL feature (OFF by default).\n * When enabled, it sends code context and finding details to an LLM\n * to validate whether the finding is a true positive.\n */\n\nexport class AIValidator {\n private config: AIConfig;\n private enabled: boolean;\n\n constructor(config: AIConfig) {\n this.config = config;\n this.enabled = config.enabled && !!this.getApiKey();\n }\n\n /**\n * Check if AI validation is available\n */\n isAvailable(): boolean {\n return this.enabled;\n }\n\n /**\n * Validate a batch of findings using AI\n */\n async validateFindings(findings: Finding[]): Promise<Finding[]> {\n if (!this.enabled) return findings;\n\n const toValidate = findings.slice(0, this.config.maxFindings || 20);\n consola.info(`AI validating ${toValidate.length} findings...`);\n\n const validated: Finding[] = [];\n\n for (const finding of toValidate) {\n try {\n const result = await this.validateSingleFinding(finding);\n validated.push({\n ...finding,\n aiValidation: result,\n });\n } catch (error) {\n consola.debug(`AI validation failed for ${finding.id}:`, error);\n validated.push(finding);\n }\n }\n\n // Add remaining unvalidated findings\n for (let i = toValidate.length; i < findings.length; i++) {\n validated.push(findings[i]);\n }\n\n return validated;\n }\n\n /**\n * Validate a single finding\n */\n private async validateSingleFinding(finding: Finding): Promise<AIValidationResult> {\n const prompt = this.buildPrompt(finding);\n\n try {\n const response = await this.callLLM(prompt);\n return this.parseResponse(response);\n } catch (error) {\n consola.debug('LLM call failed:', error);\n return {\n isValid: true,\n explanation: 'AI validation unavailable - treating as valid finding',\n confidence: 0,\n };\n }\n }\n\n /**\n * Build the LLM prompt for finding validation\n */\n private buildPrompt(finding: Finding): string {\n return `You are a security code reviewer. Analyze the following code finding and determine if it is a TRUE POSITIVE (real vulnerability/issue) or FALSE POSITIVE (not actually a problem).\n\n**Finding:**\n- Rule: ${finding.ruleId}\n- Title: ${finding.title}\n- Severity: ${finding.severity}\n- Category: ${finding.category}\n- Message: ${finding.message}\n\n**Code:**\nFile: ${finding.location.file} (line ${finding.location.startLine})\n\\`\\`\\`\n${finding.location.snippet}\n\\`\\`\\`\n\n${finding.taintFlow ? `**Data Flow:**\\n${finding.taintFlow.map(s => `${s.kind}: ${s.label} (${s.location.file}:${s.location.startLine})`).join('\\n')}` : ''}\n\n${finding.context ? `**Context:** This code is in a ${finding.context.type} context` : ''}\n\n**Respond in JSON format:**\n{\n \"isValid\": true/false,\n \"explanation\": \"Brief explanation of why this is or isn't a real issue\",\n \"confidence\": 0.0-1.0,\n \"fixSuggestion\": \"Optional: how to fix if it's a real issue\"\n}`;\n }\n\n /**\n * Call the LLM API\n */\n private async callLLM(prompt: string): Promise<string> {\n const apiKey = this.getApiKey();\n if (!apiKey) {\n throw new Error('No API key configured for AI validation');\n }\n\n switch (this.config.provider) {\n case 'openai':\n return this.callOpenAI(prompt, apiKey);\n case 'anthropic':\n return this.callAnthropic(prompt, apiKey);\n case 'ollama':\n return this.callOllama(prompt);\n case 'google':\n return this.callGoogle(prompt, apiKey);\n default:\n throw new Error(`Unknown AI provider: ${this.config.provider}`);\n }\n }\n\n /**\n * Call OpenAI API\n */\n private async callOpenAI(prompt: string, apiKey: string): Promise<string> {\n const baseUrl = this.config.baseUrl || 'https://api.openai.com/v1';\n const model = this.config.model || 'gpt-4o-mini';\n\n const response = await fetch(`${baseUrl}/chat/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model,\n messages: [\n { role: 'system', content: 'You are a security code reviewer. Respond only in valid JSON.' },\n { role: 'user', content: prompt },\n ],\n temperature: this.config.temperature || 0.1,\n max_tokens: 500,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`OpenAI API error: ${response.status} ${response.statusText}`);\n }\n\n const data = await response.json() as { choices: Array<{ message: { content: string } }> };\n return data.choices[0]?.message?.content || '';\n }\n\n /**\n * Call Anthropic API\n */\n private async callAnthropic(prompt: string, apiKey: string): Promise<string> {\n const baseUrl = this.config.baseUrl || 'https://api.anthropic.com/v1';\n const model = this.config.model || 'claude-3-haiku-20240307';\n\n const response = await fetch(`${baseUrl}/messages`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': '2023-06-01',\n },\n body: JSON.stringify({\n model,\n max_tokens: 500,\n messages: [{ role: 'user', content: prompt }],\n temperature: this.config.temperature || 0.1,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Anthropic API error: ${response.status} ${response.statusText}`);\n }\n\n const data = await response.json() as { content: Array<{ text: string }> };\n return data.content[0]?.text || '';\n }\n\n /**\n * Call Ollama local API\n */\n private async callOllama(prompt: string): Promise<string> {\n const baseUrl = this.config.baseUrl || 'http://localhost:11434';\n const model = this.config.model || 'llama3';\n\n const response = await fetch(`${baseUrl}/api/generate`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n model,\n prompt,\n stream: false,\n options: { temperature: this.config.temperature || 0.1 },\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Ollama API error: ${response.status}`);\n }\n\n const data = await response.json() as { response: string };\n return data.response || '';\n }\n\n /**\n * Parse LLM response into validation result\n */\n private parseResponse(response: string): AIValidationResult {\n try {\n // Extract JSON from response (may be wrapped in markdown code blocks)\n const jsonMatch = response.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) {\n return {\n isValid: true,\n explanation: 'Could not parse AI response',\n confidence: 0,\n };\n }\n\n const parsed = JSON.parse(jsonMatch[0]);\n return {\n isValid: parsed.isValid ?? true,\n explanation: parsed.explanation || 'No explanation provided',\n confidence: typeof parsed.confidence === 'number' ? parsed.confidence : 0.5,\n fixSuggestion: parsed.fixSuggestion,\n };\n } catch {\n return {\n isValid: true,\n explanation: 'AI response parsing failed',\n confidence: 0,\n };\n }\n }\n\n /**\n * Get API key from config or environment\n */\n private getApiKey(): string | undefined {\n if (this.config.apiKey) return this.config.apiKey;\n\n switch (this.config.provider) {\n case 'openai':\n return process.env.OPENAI_API_KEY;\n case 'anthropic':\n return process.env.ANTHROPIC_API_KEY;\n case 'ollama':\n return 'local'; // Ollama doesn't need an API key\n case 'google':\n return process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY;\n default:\n return undefined;\n }\n }\n\n /**\n * Call Google Gemini API (via OpenAI compatibility endpoint)\n */\n private async callGoogle(prompt: string, apiKey: string): Promise<string> {\n const baseUrl = this.config.baseUrl || 'https://generativelanguage.googleapis.com/v1beta/openai';\n const model = this.config.model || 'gemini-2.5-flash';\n\n const response = await fetch(`${baseUrl}/chat/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model,\n messages: [\n { role: 'system', content: 'You are a security code reviewer. Respond only in valid JSON.' },\n { role: 'user', content: prompt },\n ],\n temperature: this.config.temperature || 0.1,\n max_tokens: 500,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Google Gemini API error: ${response.status} ${response.statusText}`);\n }\n\n const data = await response.json() as { choices: Array<{ message: { content: string } }> };\n return data.choices[0]?.message?.content || '';\n }\n}\n","// ─── AST Parser ─────────────────────────────────────────────────────────────\n// Tree-sitter based AST parsing for context-aware analysis.\n// Uses web-tree-sitter (WASM) for cross-platform compatibility.\n\nimport { Parser, Language, Tree, Node } from 'web-tree-sitter';\nimport { resolve, join } from 'node:path';\nimport { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';\nimport { consola } from 'consola';\n\n/** Supported language grammars and their npm package names */\nconst LANGUAGE_GRAMMAR_MAP: Record<string, string> = {\n javascript: 'tree-sitter-javascript',\n typescript: 'tree-sitter-typescript',\n typescriptreact: 'tree-sitter-typescript',\n python: 'tree-sitter-python',\n java: 'tree-sitter-java',\n go: 'tree-sitter-go',\n php: 'tree-sitter-php',\n ruby: 'tree-sitter-ruby',\n c: 'tree-sitter-c',\n cpp: 'tree-sitter-cpp',\n csharp: 'tree-sitter-c-sharp',\n rust: 'tree-sitter-rust',\n};\n\n/** Cache directory for downloaded grammars */\nconst GRAMMAR_CACHE_DIR = resolve('node_modules', '.cache', 'deepscan', 'grammars');\n\n/**\n * AST Parser manager using web-tree-sitter.\n * Provides utilities to parse source code and query AST node context.\n */\nexport class ASTParser {\n private parser: Parser | null = null;\n private languages: Map<string, Language> = new Map();\n private initialized = false;\n\n /**\n * Initialize the tree-sitter WASM runtime.\n */\n async initialize(): Promise<void> {\n if (this.initialized) return;\n\n try {\n await Parser.init();\n this.parser = new Parser();\n this.initialized = true;\n consola.debug('AST Parser initialized (web-tree-sitter WASM)');\n } catch (error) {\n consola.debug('Failed to initialize tree-sitter:', error);\n this.parser = null;\n }\n }\n\n /**\n * Parse source code into an AST tree.\n * Returns null if the language grammar is not available.\n */\n async parse(content: string, language: string, filePath?: string): Promise<Tree | null> {\n if (!this.parser) return null;\n\n const isTsx = filePath?.endsWith('.tsx') ?? false;\n const langKey = isTsx ? 'typescriptreact' : language;\n const lang = await this.loadLanguage(langKey);\n if (!lang) return null;\n\n try {\n this.parser.setLanguage(lang);\n return this.parser.parse(content);\n } catch (error) {\n console.error(`Failed to parse ${language} code:`, error);\n return null;\n }\n }\n\n /**\n * Get the inner parser instance.\n */\n getParser(): Parser | null {\n return this.parser;\n }\n\n /**\n * Get the AST node at a specific (0-indexed) line and column position.\n */\n getNodeAt(tree: Tree, line: number, column: number): Node | null {\n try {\n return tree.rootNode.descendantForPosition({ row: line, column });\n } catch {\n return null;\n }\n }\n\n /**\n * Check if a (1-indexed) position falls inside a string literal AST node.\n */\n isInStringLiteral(tree: Tree, line: number, column: number): boolean {\n const node = this.getNodeAt(tree, line - 1, column - 1);\n return node ? this.isStringNode(node) : false;\n }\n\n /**\n * Check if a (1-indexed) position falls inside a comment AST node.\n */\n isInComment(tree: Tree, line: number, column: number): boolean {\n const node = this.getNodeAt(tree, line - 1, column - 1);\n return node ? this.isCommentNode(node) : false;\n }\n\n /**\n * Check if a (1-indexed) position falls inside an import/require statement.\n */\n isInImport(tree: Tree, line: number, column: number): boolean {\n const node = this.getNodeAt(tree, line - 1, column - 1);\n if (!node) return false;\n\n let current: Node | null = node;\n while (current) {\n const type = current.type;\n if (\n type === 'import_statement' ||\n type === 'import_declaration' ||\n type === 'import_from_statement' ||\n type === 'import' ||\n type === 'require' ||\n type === 'call_expression' && current.firstChild?.text === 'require'\n ) {\n return true;\n }\n current = current.parent;\n }\n return false;\n }\n\n /**\n * Check if a (1-indexed) position falls inside a type annotation.\n */\n isInTypeAnnotation(tree: Tree, line: number, column: number): boolean {\n const node = this.getNodeAt(tree, line - 1, column - 1);\n if (!node) return false;\n\n let current: Node | null = node;\n while (current) {\n const type = current.type;\n if (\n type === 'type_annotation' ||\n type === 'type_alias_declaration' ||\n type === 'interface_declaration' ||\n type === 'type_parameter' ||\n type === 'type_parameters'\n ) {\n return true;\n }\n current = current.parent;\n }\n return false;\n }\n\n /**\n * Check if a position is in a \"safe\" AST context (string, comment, import, type).\n * Returns false if no tree is available (falls back to regex heuristics).\n */\n isInSafeContext(tree: Tree | null, line: number, column: number): boolean {\n if (!tree) return false;\n\n const node = this.getNodeAt(tree, line - 1, column - 1);\n if (!node) return false;\n\n // Walk up ancestors to check context\n let current: Node | null = node;\n while (current) {\n const type = current.type;\n\n // Comments\n if (type === 'comment' || type === 'line_comment' || type === 'block_comment') return true;\n\n // Bare string statements (docstrings and directives)\n if (\n this.isStringNode(current) &&\n (current.parent?.type === 'expression_statement' || current.parent?.parent?.type === 'expression_statement')\n ) return true;\n\n // Import/require statements\n if (\n type === 'import_statement' || type === 'import_declaration' ||\n type === 'import_from_statement'\n ) return true;\n\n // Type annotations (TypeScript)\n if (\n type === 'type_annotation' || type === 'type_alias_declaration' ||\n type === 'interface_declaration'\n ) return true;\n\n current = current.parent;\n }\n return false;\n }\n\n /**\n * Clean up resources.\n */\n async destroy(): Promise<void> {\n if (this.parser) {\n this.parser.delete();\n this.parser = null;\n }\n this.languages.clear();\n this.initialized = false;\n }\n\n // ─── Private Helpers ──────────────────────────────────────────────────────\n\n /**\n * Load a language grammar WASM. Try local node_modules first, then cache.\n */\n private async loadLanguage(language: string): Promise<Language | null> {\n // Check cache\n if (this.languages.has(language)) {\n return this.languages.get(language)!;\n }\n\n const grammarName = LANGUAGE_GRAMMAR_MAP[language];\n if (!grammarName) {\n consola.debug(`No tree-sitter grammar available for: ${language}`);\n return null;\n }\n\n try {\n // Try loading from node_modules (if installed as a dependency)\n let wasmPath: string | null = null;\n let wasmFileName = `${grammarName}.wasm`;\n if (language === 'typescriptreact') {\n wasmFileName = 'tree-sitter-tsx.wasm';\n }\n\n // For TypeScript, the WASM is usually at tree-sitter-typescript/tree-sitter-typescript.wasm\n const possiblePaths = [\n resolve('node_modules', grammarName, wasmFileName),\n resolve('node_modules', grammarName, `${language}.wasm`),\n resolve('node_modules', grammarName, 'wasm', wasmFileName),\n join(GRAMMAR_CACHE_DIR, wasmFileName),\n ];\n\n for (const p of possiblePaths) {\n if (existsSync(p)) {\n wasmPath = p;\n break;\n }\n }\n\n if (!wasmPath) {\n consola.debug(`Grammar WASM not found for ${language}. Checked: ${possiblePaths.join(', ')}`);\n return null;\n }\n\n const lang = await Language.load(wasmPath);\n this.languages.set(language, lang);\n consola.debug(`Loaded tree-sitter grammar: ${language}`);\n return lang;\n } catch (error) {\n console.error(`Failed to load grammar for ${language} at ${grammarName}:`, error);\n return null;\n }\n }\n\n /** Check if a node is a string literal */\n private isStringNode(node: Node): boolean {\n const type = node.type;\n return (\n type === 'string' ||\n type === 'string_literal' ||\n type === 'template_string' ||\n type === 'string_content' ||\n type === 'concatenated_string' ||\n type === 'interpreted_string_literal'\n );\n }\n\n /** Check if a node is a comment */\n private isCommentNode(node: Node): boolean {\n const type = node.type;\n return type === 'comment' || type === 'line_comment' || type === 'block_comment';\n }\n\n /** Check if a template string has interpolation (${...}) */\n private isTemplateWithInterpolation(node: Node): boolean {\n if (node.type !== 'template_string') return false;\n // If it has template_substitution children, it has interpolation\n for (let i = 0; i < node.childCount; i++) {\n if (node.child(i)?.type === 'template_substitution') return true;\n }\n return false;\n }\n}\n\n/** Singleton instance */\nlet astParserInstance: ASTParser | null = null;\n\n/**\n * Get the singleton AST parser instance.\n */\nexport function getASTParser(): ASTParser {\n if (!astParserInstance) {\n astParserInstance = new ASTParser();\n }\n return astParserInstance;\n}\n","import { readFileSync, existsSync } from 'node:fs';\nimport { resolve, dirname } from 'node:path';\nimport yaml from 'js-yaml';\nimport { consola } from 'consola';\nimport { DeepScanConfigSchema } from './schema.js';\nimport { DEFAULT_CONFIG, PRESETS } from './defaults.js';\nimport type { DeepScanConfig } from '../types/config.js';\n\n/** Config file names to search for (in priority order) */\nconst CONFIG_FILES = [\n '.deepscan.yml',\n '.deepscan.yaml',\n '.deepscan.json',\n '.deepscan.config.js',\n 'deepscan.config.yml',\n 'deepscan.config.yaml',\n 'deepscan.config.json',\n];\n\n/**\n * Load and merge configuration from multiple sources.\n * Priority: CLI args > project config file > preset > defaults\n */\nexport async function loadConfig(options: {\n configPath?: string;\n targetPath?: string;\n cliOverrides?: Partial<DeepScanConfig>;\n preset?: string;\n}): Promise<DeepScanConfig> {\n const { configPath, targetPath, cliOverrides, preset } = options;\n\n // Step 1: Start with defaults\n let config: Record<string, unknown> = structuredClone(DEFAULT_CONFIG) as unknown as Record<string, unknown>;\n\n // Step 2: Apply preset if specified\n if (preset && PRESETS[preset]) {\n config = deepMerge(config, PRESETS[preset] as Record<string, unknown>);\n consola.debug(`Applied preset: ${preset}`);\n }\n\n // Step 2.5: Dynamically detect and apply ecosystem-specific path exclusions\n const searchDir = targetPath ? resolve(targetPath) : process.cwd();\n const detectedExcludes = detectEcosystemExcludes(searchDir);\n if (detectedExcludes.length > 0) {\n if (!config.paths) config.paths = { include: ['**/*'], exclude: [] };\n const currentExclude = (config.paths as any).exclude || [];\n (config.paths as any).exclude = [...new Set([...currentExclude, ...detectedExcludes])];\n consola.debug(`Applied ${detectedExcludes.length} auto-detected ecosystem path exclusions`);\n }\n\n // Step 3: Load project config file\n const projectConfig = await loadProjectConfig(configPath, targetPath);\n if (projectConfig) {\n config = deepMerge(config, projectConfig);\n consola.debug(`Loaded config from file`);\n }\n\n // Step 4: Apply CLI overrides\n if (cliOverrides) {\n config = deepMerge(config, cliOverrides as Record<string, unknown>);\n }\n\n // Step 5: Resolve environment variables\n config = resolveEnvVars(config);\n\n // Step 6: Validate with Zod\n const validated = DeepScanConfigSchema.parse(config);\n\n return validated as DeepScanConfig;\n}\n\n/**\n * Find and load project configuration file\n */\nasync function loadProjectConfig(\n explicitPath?: string,\n targetPath?: string,\n): Promise<Record<string, unknown> | null> {\n // If explicit path provided, use it\n if (explicitPath) {\n if (!existsSync(explicitPath)) {\n consola.warn(`Config file not found: ${explicitPath}`);\n return null;\n }\n return parseConfigFile(explicitPath);\n }\n\n // Search for config file in target directory and parents\n const searchDir = targetPath ? resolve(targetPath) : process.cwd();\n const configPath = findConfigFile(searchDir);\n\n if (configPath) {\n return parseConfigFile(configPath);\n }\n\n return null;\n}\n\n/**\n * Search for config file in directory and parent directories\n */\nfunction findConfigFile(startDir: string): string | null {\n let currentDir = startDir;\n\n // Traverse up to 10 levels\n for (let i = 0; i < 10; i++) {\n for (const fileName of CONFIG_FILES) {\n const filePath = resolve(currentDir, fileName);\n if (existsSync(filePath)) {\n return filePath;\n }\n }\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) break; // Reached root\n currentDir = parentDir;\n }\n\n return null;\n}\n\n/**\n * Parse a configuration file (YAML or JSON)\n */\nfunction parseConfigFile(filePath: string): Record<string, unknown> | null {\n try {\n const content = readFileSync(filePath, 'utf-8');\n\n if (filePath.endsWith('.json')) {\n return JSON.parse(content);\n }\n\n if (filePath.endsWith('.yml') || filePath.endsWith('.yaml')) {\n return yaml.load(content) as Record<string, unknown>;\n }\n\n consola.warn(`Unsupported config format: ${filePath}`);\n return null;\n } catch (error) {\n consola.error(`Failed to parse config file: ${filePath}`, error);\n return null;\n }\n}\n\n/**\n * Deep merge two objects (source overrides target)\n */\nfunction deepMerge(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): Record<string, unknown> {\n const result = { ...target };\n\n for (const key of Object.keys(source)) {\n const sourceVal = source[key];\n const targetVal = target[key];\n\n if (\n sourceVal !== null &&\n typeof sourceVal === 'object' &&\n !Array.isArray(sourceVal) &&\n targetVal !== null &&\n typeof targetVal === 'object' &&\n !Array.isArray(targetVal)\n ) {\n result[key] = deepMerge(\n targetVal as Record<string, unknown>,\n sourceVal as Record<string, unknown>,\n );\n } else {\n result[key] = sourceVal;\n }\n }\n\n return result;\n}\n\n/**\n * Resolve environment variable references in config values.\n * Supports ${ENV_VAR} and ${ENV_VAR:default} syntax.\n */\nfunction resolveEnvVars(obj: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(obj)) {\n if (typeof value === 'string') {\n result[key] = value.replace(\n /\\$\\{(\\w+)(?::([^}]*))?\\}/g,\n (_match, envName: string, defaultVal?: string) => {\n return process.env[envName] ?? defaultVal ?? '';\n },\n );\n } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result[key] = resolveEnvVars(value as Record<string, unknown>);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Dynamically detect ecosystems and return relevant path exclusions\n */\nfunction detectEcosystemExcludes(targetPath: string): string[] {\n const excludes: string[] = [];\n\n // 1. Node.js / JavaScript / TypeScript Ecosystem\n if (\n existsSync(resolve(targetPath, 'package.json')) ||\n existsSync(resolve(targetPath, 'package-lock.json')) ||\n existsSync(resolve(targetPath, 'yarn.lock')) ||\n existsSync(resolve(targetPath, 'pnpm-lock.yaml'))\n ) {\n excludes.push(\n 'dist/', '**/dist/**',\n 'build/', '**/build/**',\n '.next/', '**/.next/**',\n '.nuxt/', '**/.nuxt/**',\n '.cache/', '**/.cache/**',\n '.turbo/', '**/.turbo/**',\n 'assets/', '**/assets/**',\n 'public/build/', '**/public/build/**',\n 'public/hot/', '**/public/hot/**',\n 'public/storage/', '**/public/storage/**'\n );\n }\n\n // 2. PHP / Laravel Ecosystem\n if (\n existsSync(resolve(targetPath, 'composer.json')) ||\n existsSync(resolve(targetPath, 'composer.lock')) ||\n existsSync(resolve(targetPath, 'artisan'))\n ) {\n excludes.push(\n 'vendor/', '**/vendor/**',\n 'storage/', '**/storage/**',\n 'bootstrap/cache/', '**/bootstrap/cache/**',\n 'public/build/', '**/public/build/**',\n 'public/hot/', '**/public/hot/**',\n 'public/storage/', '**/public/storage/**'\n );\n }\n\n // 3. Python Ecosystem\n if (\n existsSync(resolve(targetPath, 'requirements.txt')) ||\n existsSync(resolve(targetPath, 'pyproject.toml')) ||\n existsSync(resolve(targetPath, 'Pipfile')) ||\n existsSync(resolve(targetPath, 'setup.py'))\n ) {\n excludes.push(\n '__pycache__/', '**/__pycache__/**',\n '.venv/', '**/.venv/**',\n 'venv/', '**/venv/**',\n 'tmp/', 'temp/', '.temp/', '.tmp/', '**/tmp/**', '**/temp/**', '**/.temp/**', '**/.tmp/**'\n );\n }\n\n // 4. Java / Maven / Gradle / .NET Ecosystem\n if (\n existsSync(resolve(targetPath, 'pom.xml')) ||\n existsSync(resolve(targetPath, 'build.gradle')) ||\n existsSync(resolve(targetPath, 'build.gradle.kts')) ||\n existsSync(resolve(targetPath, 'Directory.Build.props'))\n ) {\n excludes.push(\n 'target/', '**/target/**',\n 'bin/', '**/bin/**',\n 'obj/', '**/obj/**'\n );\n }\n\n return excludes;\n}\n\nexport { findConfigFile, parseConfigFile, deepMerge, detectEcosystemExcludes };\n","// ─── Console Reporter ──────────────────────────────────────────────────────\n// Beautiful terminal output with colour-coded severity, code snippets,\n// grouped findings, and a summary table.\n\nimport chalk from 'chalk';\nimport type { ScanResult, Finding, Severity } from '../types/finding.js';\nimport type { OutputFormat } from '../types/config.js';\nimport { BaseReporter } from './base-reporter.js';\n\n/** Severity → chalk colour mapping */\nconst SEVERITY_COLOURS: Record<Severity, (text: string) => string> = {\n critical: chalk.bgRed.white.bold,\n high: chalk.red.bold,\n medium: chalk.yellow.bold,\n low: chalk.blue.bold,\n};\n\n/** Severity badge labels (fixed width for alignment) */\nconst SEVERITY_BADGES: Record<Severity, string> = {\n critical: ' CRITICAL ',\n high: ' HIGH ',\n medium: ' MEDIUM ',\n low: ' LOW ',\n};\n\n/** Unicode symbols */\nconst SYM = {\n bullet: '●',\n arrowRight: '→',\n bar: '█',\n barLight: '░',\n check: '✔',\n cross: '✖',\n line: '─',\n corner: '└',\n tee: '├',\n pipe: '│',\n} as const;\n\n/**\n * Console Reporter – renders findings directly to the terminal.\n *\n * Supports two modes controlled via the `verbose` / `quiet` options on the\n * ScanResult's config:\n *\n * - **Verbose**: shows full code snippets, taint traces, and fix suggestions.\n * - **Quiet** (default inverse of verbose): shows a compact one-line-per-finding\n * view plus the summary table.\n *\n * The `generate` method returns the ANSI-formatted string; `writeToFile` strips\n * ANSI codes before writing so log files stay readable.\n */\nexport class ConsoleReporter extends BaseReporter {\n readonly format: OutputFormat = 'console';\n\n /** If true, output full details; if false, compact mode. */\n private verbose = false;\n\n setVerbose(flag: boolean): void {\n this.verbose = flag;\n }\n\n async generate(result: ScanResult): Promise<string> {\n const lines: string[] = [];\n\n lines.push('');\n lines.push(this.renderHeader(result));\n lines.push('');\n\n if (result.findings.length === 0) {\n lines.push(chalk.green.bold(` ${SYM.check} No findings detected – your code looks great!`));\n lines.push('');\n lines.push(this.renderScanMeta(result));\n return lines.join('\\n');\n }\n\n // Group findings by file\n const grouped = this.groupByFile(result.findings);\n\n for (const [filePath, findings] of grouped) {\n lines.push(this.renderFileHeader(filePath, findings.length));\n // Sort findings within each file by severity weight, then by line number\n findings.sort(\n (a, b) =>\n this.severityWeight(a.severity) - this.severityWeight(b.severity) ||\n a.location.startLine - b.location.startLine,\n );\n for (const finding of findings) {\n lines.push(this.renderFinding(finding));\n }\n lines.push('');\n }\n\n lines.push(this.renderSummaryTable(result));\n lines.push('');\n lines.push(this.renderProgressBar(result));\n lines.push('');\n lines.push(this.renderScanMeta(result));\n\n return lines.join('\\n');\n }\n\n // ── Section Renderers ──────────────────────────────────────────────────\n\n private renderHeader(result: ScanResult): string {\n const divider = chalk.dim(SYM.line.repeat(60));\n const title = chalk.bold.cyan(' ⬡ DeepScan Security Report');\n const target = chalk.dim(` Target: ${result.target}`);\n const timestamp = chalk.dim(` Time: ${result.summary.timestamp}`);\n return [divider, title, target, timestamp, divider].join('\\n');\n }\n\n private renderFileHeader(filePath: string, count: number): string {\n const badge = chalk.bgBlue.white.bold(` ${count} `);\n return ` ${chalk.underline.white(filePath)} ${badge}`;\n }\n\n private renderFinding(f: Finding): string {\n const lines: string[] = [];\n const sev = SEVERITY_COLOURS[f.severity](SEVERITY_BADGES[f.severity]);\n const location = chalk.dim(`${f.location.file}:${f.location.startLine}:${f.location.startColumn}`);\n const rule = chalk.dim(`[${f.ruleId}]`);\n const title = chalk.white.bold(f.title);\n\n lines.push(` ${sev} ${title} ${rule}`);\n lines.push(` ${location}`);\n lines.push(` ${chalk.gray(f.message)}`);\n\n // Code snippet\n if (f.location.snippet && this.verbose) {\n lines.push(this.renderSnippet(f));\n } else if (f.location.snippet) {\n // Compact snippet: show just the offending line\n const snippetLine = f.location.snippet.split('\\n')[0]?.trim() ?? '';\n if (snippetLine) {\n lines.push(` ${chalk.dim(SYM.pipe)} ${chalk.yellow(snippetLine)}`);\n }\n }\n\n // Fix suggestion (verbose only)\n if (this.verbose && f.fix) {\n lines.push(` ${chalk.green(SYM.arrowRight)} ${chalk.green('Fix:')} ${f.fix.description}`);\n if (f.fix.suggestion) {\n lines.push(` ${chalk.greenBright(f.fix.suggestion)}`);\n }\n }\n\n // CWE / OWASP tags\n if (this.verbose) {\n const tags: string[] = [];\n if (f.cwe?.length) tags.push(...f.cwe.map((c) => chalk.magenta(`CWE-${c}`)));\n if (f.owasp?.length) tags.push(...f.owasp.map((o) => chalk.magenta(o)));\n if (tags.length) {\n lines.push(` ${tags.join(' ')}`);\n }\n }\n\n // Taint flow (verbose only)\n if (this.verbose && f.taintFlow?.length) {\n lines.push(` ${chalk.cyan('Taint flow:')}`);\n for (let i = 0; i < f.taintFlow.length; i++) {\n const step = f.taintFlow[i]!;\n const connector = i < f.taintFlow.length - 1 ? SYM.tee : SYM.corner;\n const kindBadge =\n step.kind === 'source'\n ? chalk.red('SRC')\n : step.kind === 'sink'\n ? chalk.red('SNK')\n : step.kind === 'sanitizer'\n ? chalk.green('SAN')\n : chalk.yellow('PRO');\n lines.push(\n ` ${chalk.dim(connector)} ${kindBadge} ${step.label} ${chalk.dim(\n `@ ${step.location.file}:${step.location.startLine}`,\n )}`,\n );\n }\n }\n\n lines.push('');\n return lines.join('\\n');\n }\n\n private renderSnippet(f: Finding): string {\n const snippetLines = f.location.snippet.split('\\n');\n const startLine = f.location.startLine;\n const rendered = snippetLines.map((line, idx) => {\n const lineNo = String(startLine + idx).padStart(5);\n const isTarget =\n startLine + idx >= f.location.startLine && startLine + idx <= f.location.endLine;\n const prefix = isTarget ? chalk.red(SYM.arrowRight) : ' ';\n const lineContent = isTarget ? chalk.yellow(line) : chalk.dim(line);\n return ` ${prefix} ${chalk.dim(lineNo)} ${chalk.dim(SYM.pipe)} ${lineContent}`;\n });\n return rendered.join('\\n');\n }\n\n private renderSummaryTable(result: ScanResult): string {\n const s = result.summary;\n const divider = chalk.dim(SYM.line.repeat(60));\n const header = chalk.bold.white(' Summary');\n\n const rows: string[] = [\n divider,\n header,\n divider,\n this.tableRow('Critical', s.bySeverity.critical, chalk.bgRed.white.bold),\n this.tableRow('High', s.bySeverity.high, chalk.red.bold),\n this.tableRow('Medium', s.bySeverity.medium, chalk.yellow.bold),\n this.tableRow('Low', s.bySeverity.low, chalk.blue.bold),\n divider,\n ` ${chalk.bold('Total')}: ${chalk.white.bold(String(s.totalFindings))} findings in ${chalk.white(\n String(s.filesWithFindings),\n )} files (${chalk.white(String(s.filesScanned))} scanned)`,\n ` ${chalk.bold('Duration')}: ${chalk.white(this.formatDuration(s.scanDuration))}`,\n ];\n\n return rows.join('\\n');\n }\n\n private tableRow(\n label: string,\n count: number,\n colorFn: (text: string) => string,\n ): string {\n const countStr = String(count).padStart(5);\n const bar = count > 0 ? colorFn(SYM.bar.repeat(Math.min(count, 40))) : chalk.dim('none');\n return ` ${colorFn(label.padEnd(10))} ${countStr} ${bar}`;\n }\n\n private renderProgressBar(result: ScanResult): string {\n const s = result.summary;\n const total = s.totalFindings || 1;\n const barWidth = 40;\n\n const segments: { count: number; color: (text: string) => string }[] = [\n { count: s.bySeverity.critical, color: chalk.bgRed },\n { count: s.bySeverity.high, color: chalk.bgRedBright },\n { count: s.bySeverity.medium, color: chalk.bgYellow },\n { count: s.bySeverity.low, color: chalk.bgBlue },\n ];\n\n let bar = '';\n for (const seg of segments) {\n const width = Math.round((seg.count / total) * barWidth);\n if (width > 0) {\n bar += seg.color(' '.repeat(width));\n }\n }\n // Fill remainder\n const usedWidth = segments.reduce(\n (sum, seg) => sum + Math.round((seg.count / total) * barWidth),\n 0,\n );\n if (usedWidth < barWidth) {\n bar += chalk.bgGray(' '.repeat(barWidth - usedWidth));\n }\n\n return ` Severity Distribution: ${bar}`;\n }\n\n private renderScanMeta(result: ScanResult): string {\n return chalk.dim(\n ` ${result.tool.name} v${result.tool.version} ${SYM.bullet} ${result.summary.timestamp}`,\n );\n }\n\n // ── Helpers ────────────────────────────────────────────────────────────\n\n private groupByFile(findings: Finding[]): Map<string, Finding[]> {\n const map = new Map<string, Finding[]>();\n for (const f of findings) {\n const key = f.location.file;\n const arr = map.get(key);\n if (arr) {\n arr.push(f);\n } else {\n map.set(key, [f]);\n }\n }\n return map;\n }\n}\n","// ─── Base Reporter ─────────────────────────────────────────────────────────\n// Abstract base class providing common utilities for all reporter implementations.\n\nimport { writeFileSync, mkdirSync, existsSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { IReporter } from '../types/scanner.js';\nimport type { ScanResult } from '../types/finding.js';\nimport type { OutputFormat } from '../types/config.js';\n\n/**\n * Abstract base reporter class that implements `IReporter`.\n * Provides common file-writing utilities and ensures output directories exist.\n * Subclasses must implement the `generate` method for their specific format.\n */\nexport abstract class BaseReporter implements IReporter {\n abstract readonly format: OutputFormat;\n\n /**\n * Generate the report content as a string.\n * Each reporter subclass produces its own format (JSON, CSV, HTML, etc.).\n */\n abstract generate(result: ScanResult): Promise<string>;\n\n /**\n * Write the generated report to the specified file path.\n * Automatically creates parent directories if they do not exist.\n */\n async writeToFile(result: ScanResult, filePath: string): Promise<void> {\n const content = await this.generate(result);\n this.ensureDirectoryExists(filePath);\n writeFileSync(filePath, content, 'utf-8');\n }\n\n // ── Utility Helpers ────────────────────────────────────────────────────\n\n /**\n * Ensure the parent directory for a file path exists, creating it recursively\n * if necessary.\n */\n protected ensureDirectoryExists(filePath: string): void {\n const dir = dirname(filePath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n }\n\n /**\n * Format a duration in milliseconds to a human-readable string.\n * Examples: \"1.23s\", \"45.6s\", \"2m 15s\"\n */\n protected formatDuration(ms: number): string {\n if (ms < 1000) {\n return `${ms}ms`;\n }\n const seconds = ms / 1000;\n if (seconds < 60) {\n return `${seconds.toFixed(2)}s`;\n }\n const minutes = Math.floor(seconds / 60);\n const remainingSeconds = (seconds % 60).toFixed(0);\n return `${minutes}m ${remainingSeconds}s`;\n }\n\n /**\n * Map severity strings to numeric sort weight.\n * Lower weight = higher priority.\n */\n protected severityWeight(severity: string): number {\n const weights: Record<string, number> = {\n critical: 0,\n error: 1,\n warning: 2,\n info: 3,\n };\n return weights[severity] ?? 4;\n }\n}\n","// ─── JSON Reporter ─────────────────────────────────────────────────────────\n// Outputs the complete ScanResult as formatted JSON with 2-space indentation.\n\nimport type { ScanResult } from '../types/finding.js';\nimport type { OutputFormat } from '../types/config.js';\nimport { BaseReporter } from './base-reporter.js';\n\n/**\n * JSON Reporter – emits the full `ScanResult` object as a JSON document.\n *\n * Features:\n * - Pretty-printed with 2-space indentation for readability\n * - Includes all metadata (tool info, summary, findings, AI validations, etc.)\n * - Deterministic output (no custom serialisation logic)\n */\nexport class JsonReporter extends BaseReporter {\n readonly format: OutputFormat = 'json';\n\n async generate(result: ScanResult): Promise<string> {\n // Construct an enriched output envelope so downstream consumers get\n // explicit schema hints alongside the raw scan data.\n const output = {\n $schema: 'https://deepscan.dev/schemas/scan-result-v1.json',\n ...result,\n generatedAt: new Date().toISOString(),\n };\n\n return JSON.stringify(output, null, 2) + '\\n';\n }\n}\n","// ─── CSV Reporter ──────────────────────────────────────────────────────────\n// Outputs findings as a CSV file with proper escaping and UTF-8 BOM.\n\nimport type { ScanResult, Finding } from '../types/finding.js';\nimport type { OutputFormat } from '../types/config.js';\nimport { BaseReporter } from './base-reporter.js';\n\n/** UTF-8 byte-order mark so Excel correctly detects the encoding. */\nconst UTF8_BOM = '\\uFEFF';\n\n/** CSV column headers. */\nconst HEADERS = [\n 'ID',\n 'Rule',\n 'Scanner',\n 'Severity',\n 'Confidence',\n 'Category',\n 'File',\n 'Line',\n 'Title',\n 'Message',\n] as const;\n\n/**\n * CSV Reporter – produces a standards-compliant CSV file.\n *\n * Features:\n * - UTF-8 BOM prefix for seamless Excel / Google Sheets import\n * - RFC 4180 compliant quoting: fields containing commas, double-quotes,\n * or newlines are quoted; embedded double-quotes are doubled.\n * - One row per finding with the most useful columns\n */\nexport class CsvReporter extends BaseReporter {\n readonly format: OutputFormat = 'csv';\n\n async generate(result: ScanResult): Promise<string> {\n const rows: string[] = [];\n\n // Header row\n rows.push(HEADERS.join(','));\n\n // Data rows\n for (const finding of result.findings) {\n rows.push(this.findingToRow(finding));\n }\n\n return UTF8_BOM + rows.join('\\r\\n') + '\\r\\n';\n }\n\n // ── Private helpers ────────────────────────────────────────────────────\n\n /**\n * Convert a single Finding to a CSV row string.\n */\n private findingToRow(f: Finding): string {\n const cells: string[] = [\n f.id,\n f.ruleId,\n f.scanner,\n f.severity,\n f.confidence,\n f.category,\n f.location.file,\n String(f.location.startLine),\n f.title,\n f.message,\n ];\n\n return cells.map(CsvReporter.escapeField).join(',');\n }\n\n /**\n * Escape a CSV field following RFC 4180 rules.\n * If the value contains a comma, double-quote, or newline the entire field\n * is wrapped in double-quotes and any embedded double-quotes are doubled.\n */\n private static escapeField(value: string): string {\n if (\n value.includes(',') ||\n value.includes('\"') ||\n value.includes('\\n') ||\n value.includes('\\r')\n ) {\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n }\n return value;\n }\n}\n","// ─── SARIF Reporter ────────────────────────────────────────────────────────\n// Produces SARIF v2.1.0 compliant output for integration with GitHub Code\n// Scanning, Azure DevOps, and other SARIF-compatible tools.\n\nimport type { ScanResult, Finding, Severity } from '../types/finding.js';\nimport type { OutputFormat } from '../types/config.js';\nimport { BaseReporter } from './base-reporter.js';\n\n// ── SARIF type definitions (subset) ──────────────────────────────────────\n\ninterface SarifMessage {\n text: string;\n}\n\ninterface SarifArtifactLocation {\n uri: string;\n uriBaseId?: string;\n}\n\ninterface SarifRegion {\n startLine: number;\n startColumn: number;\n endLine: number;\n endColumn: number;\n snippet?: { text: string };\n}\n\ninterface SarifPhysicalLocation {\n artifactLocation: SarifArtifactLocation;\n region: SarifRegion;\n}\n\ninterface SarifLocation {\n physicalLocation: SarifPhysicalLocation;\n}\n\ninterface SarifCodeFlow {\n threadFlows: SarifThreadFlow[];\n}\n\ninterface SarifThreadFlow {\n locations: SarifThreadFlowLocation[];\n}\n\ninterface SarifThreadFlowLocation {\n location: SarifLocation;\n kinds?: string[];\n message?: SarifMessage;\n}\n\ninterface SarifFix {\n description: SarifMessage;\n}\n\ninterface SarifResult {\n ruleId: string;\n ruleIndex: number;\n level: 'error' | 'warning' | 'note' | 'none';\n message: SarifMessage;\n locations: SarifLocation[];\n fingerprints?: Record<string, string>;\n codeFlows?: SarifCodeFlow[];\n fixes?: SarifFix[];\n properties?: Record<string, unknown>;\n}\n\ninterface SarifReportingDescriptor {\n id: string;\n name: string;\n shortDescription: SarifMessage;\n fullDescription?: SarifMessage;\n helpUri?: string;\n defaultConfiguration?: { level: string };\n properties?: Record<string, unknown>;\n relationships?: SarifRelationship[];\n}\n\ninterface SarifRelationship {\n target: {\n id: string;\n guid?: string;\n toolComponent: { name: string };\n };\n kinds: string[];\n}\n\ninterface SarifToolComponent {\n name: string;\n version: string;\n informationUri?: string;\n rules: SarifReportingDescriptor[];\n}\n\ninterface SarifTaxon {\n id: string;\n name: string;\n shortDescription?: SarifMessage;\n}\n\ninterface SarifTaxonomy {\n name: string;\n version?: string;\n informationUri?: string;\n organization?: string;\n shortDescription?: SarifMessage;\n taxa: SarifTaxon[];\n guid?: string;\n isComprehensive?: boolean;\n}\n\ninterface SarifRun {\n tool: { driver: SarifToolComponent };\n results: SarifResult[];\n taxonomies?: SarifTaxonomy[];\n invocations?: SarifInvocation[];\n}\n\ninterface SarifInvocation {\n executionSuccessful: boolean;\n startTimeUtc?: string;\n endTimeUtc?: string;\n toolExecutionNotifications?: unknown[];\n}\n\ninterface SarifLog {\n $schema: string;\n version: '2.1.0';\n runs: SarifRun[];\n}\n\n// ── Severity → SARIF level mapping ───────────────────────────────────────\n\nconst SARIF_LEVEL: Record<Severity, 'error' | 'warning' | 'note'> = {\n critical: 'error',\n high: 'error',\n medium: 'warning',\n low: 'note',\n};\n\n/**\n * SARIF Reporter – produces a SARIF v2.1.0 JSON log.\n *\n * Features:\n * - Full tool metadata (name, version, rules array)\n * - CWE taxonomy references when CWE data is available\n * - Code-flow traces mapped from taint-flow data\n * - Fix suggestions as SARIF `fixes`\n * - Fingerprints for result matching / deduplication\n */\nexport class SarifReporter extends BaseReporter {\n readonly format: OutputFormat = 'sarif';\n\n async generate(result: ScanResult): Promise<string> {\n // Collect unique rules from findings\n const ruleMap = this.collectRules(result.findings);\n const rules = Array.from(ruleMap.values());\n const ruleIndex = new Map<string, number>();\n rules.forEach((r, idx) => ruleIndex.set(r.id, idx));\n\n // Build CWE taxonomy if any finding references CWEs\n const cweTaxa = this.collectCweTaxa(result.findings);\n const taxonomies: SarifTaxonomy[] = [];\n if (cweTaxa.length > 0) {\n taxonomies.push({\n name: 'CWE',\n version: '4.13',\n organization: 'MITRE',\n shortDescription: { text: 'The MITRE Common Weakness Enumeration' },\n informationUri: 'https://cwe.mitre.org/',\n isComprehensive: false,\n taxa: cweTaxa,\n });\n }\n\n // Attach CWE relationships to rules\n if (cweTaxa.length > 0) {\n for (const rule of rules) {\n const cweIds = (rule.properties?.['cwe'] as string[] | undefined) ?? [];\n if (cweIds.length > 0) {\n rule.relationships = cweIds.map((id) => ({\n target: {\n id,\n toolComponent: { name: 'CWE' },\n },\n kinds: ['superset'],\n }));\n }\n }\n }\n\n // Build SARIF results\n const sarifResults = result.findings.map((f) =>\n this.findingToResult(f, ruleIndex),\n );\n\n // Compute invocation timestamps\n const endTime = new Date(result.summary.timestamp);\n const startTime = new Date(endTime.getTime() - result.summary.scanDuration);\n\n const sarifLog: SarifLog = {\n $schema: 'https://json.schemastore.org/sarif-2.1.0.json',\n version: '2.1.0',\n runs: [\n {\n tool: {\n driver: {\n name: result.tool.name,\n version: result.tool.version,\n informationUri: 'https://github.com/deepscan/deepscan',\n rules,\n },\n },\n invocations: [\n {\n executionSuccessful: true,\n startTimeUtc: startTime.toISOString(),\n endTimeUtc: endTime.toISOString(),\n },\n ],\n results: sarifResults,\n ...(taxonomies.length > 0 ? { taxonomies } : {}),\n },\n ],\n };\n\n return JSON.stringify(sarifLog, null, 2) + '\\n';\n }\n\n // ── Private helpers ────────────────────────────────────────────────────\n\n /**\n * Collect unique rule descriptors from the findings array.\n */\n private collectRules(findings: Finding[]): Map<string, SarifReportingDescriptor> {\n const map = new Map<string, SarifReportingDescriptor>();\n\n for (const f of findings) {\n if (map.has(f.ruleId)) continue;\n\n const descriptor: SarifReportingDescriptor = {\n id: f.ruleId,\n name: f.title,\n shortDescription: { text: f.title },\n fullDescription: { text: f.message },\n defaultConfiguration: { level: SARIF_LEVEL[f.severity] },\n properties: {\n category: f.category,\n ...(f.cwe?.length ? { cwe: f.cwe } : {}),\n ...(f.owasp?.length ? { owasp: f.owasp } : {}),\n tags: [f.scanner, f.category, ...(f.metadata.tags ?? [])],\n },\n };\n\n map.set(f.ruleId, descriptor);\n }\n\n return map;\n }\n\n /**\n * Collect unique CWE taxa from all findings.\n */\n private collectCweTaxa(findings: Finding[]): SarifTaxon[] {\n const seen = new Set<string>();\n const taxa: SarifTaxon[] = [];\n\n for (const f of findings) {\n if (!f.cwe) continue;\n for (const cweId of f.cwe) {\n if (seen.has(cweId)) continue;\n seen.add(cweId);\n taxa.push({\n id: cweId,\n name: `CWE-${cweId}`,\n shortDescription: { text: `Common Weakness Enumeration ${cweId}` },\n });\n }\n }\n\n return taxa;\n }\n\n /**\n * Map a Finding to a SARIF Result.\n */\n private findingToResult(\n f: Finding,\n ruleIndex: Map<string, number>,\n ): SarifResult {\n const result: SarifResult = {\n ruleId: f.ruleId,\n ruleIndex: ruleIndex.get(f.ruleId) ?? 0,\n level: SARIF_LEVEL[f.severity],\n message: { text: `${f.title}: ${f.message}` },\n locations: [\n {\n physicalLocation: {\n artifactLocation: {\n uri: this.normaliseUri(f.location.file),\n uriBaseId: '%SRCROOT%',\n },\n region: {\n startLine: f.location.startLine,\n startColumn: f.location.startColumn,\n endLine: f.location.endLine,\n endColumn: f.location.endColumn,\n ...(f.location.snippet\n ? { snippet: { text: f.location.snippet } }\n : {}),\n },\n },\n },\n ],\n fingerprints: {\n 'deepscan/v1': f.metadata.fingerprint,\n },\n properties: {\n confidence: f.confidence,\n scanner: f.scanner,\n category: f.category,\n ...(f.subcategory ? { subcategory: f.subcategory } : {}),\n ...(f.aiValidation\n ? {\n aiValidation: {\n isValid: f.aiValidation.isValid,\n confidence: f.aiValidation.confidence,\n },\n }\n : {}),\n },\n };\n\n // Taint flow → code flows\n if (f.taintFlow?.length) {\n result.codeFlows = [\n {\n threadFlows: [\n {\n locations: f.taintFlow.map((step) => ({\n location: {\n physicalLocation: {\n artifactLocation: {\n uri: this.normaliseUri(step.location.file),\n uriBaseId: '%SRCROOT%',\n },\n region: {\n startLine: step.location.startLine,\n startColumn: step.location.startColumn,\n endLine: step.location.endLine,\n endColumn: step.location.endColumn,\n },\n },\n },\n kinds: [step.kind],\n message: { text: step.label },\n })),\n },\n ],\n },\n ];\n }\n\n // Fix suggestions\n if (f.fix) {\n result.fixes = [\n {\n description: { text: f.fix.description },\n },\n ];\n }\n\n return result;\n }\n\n /**\n * Normalise a file path to a forward-slash URI suitable for SARIF.\n */\n private normaliseUri(filePath: string): string {\n return filePath.replace(/\\\\/g, '/');\n }\n}\n","// ─── HTML Reporter ─────────────────────────────────────────────────────────\n// Generates a beautiful, self-contained single HTML file with embedded CSS/JS.\n// Light theme, modern design, interactive dashboard with filtering and search.\n\nimport type { ScanResult, Finding, Severity } from '../types/finding.js';\nimport type { OutputFormat } from '../types/config.js';\nimport { BaseReporter } from './base-reporter.js';\n\n/** Severity colour palette for the light theme */\nconst SEVERITY_COLORS: Record<Severity, string> = {\n critical: '#cf222e',\n high: '#d1242f',\n medium: '#bf8700',\n low: '#0969da',\n};\n\n/**\n * HTML Reporter – generates a premium, self-contained HTML report.\n *\n * Features:\n * - Fully self-contained (no CDN links, no external dependencies)\n * - Dark theme with GitHub-inspired colour palette\n * - Dashboard summary cards with severity breakdown\n * - CSS-only severity distribution bar chart\n * - Interactive findings table with sort, filter, and search\n * - Expandable rows showing code snippets and fix suggestions\n * - Responsive design using CSS Grid & Flexbox\n */\nexport class HtmlReporter extends BaseReporter {\n readonly format: OutputFormat = 'html';\n\n async generate(result: ScanResult): Promise<string> {\n const findingsJson = JSON.stringify(\n result.findings.map((f) => this.serializeFinding(f)),\n ).replace(/<\\//g, '<\\\\/');\n const summaryJson = JSON.stringify(result.summary).replace(/<\\//g, '<\\\\/');\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>DeepScan Security Report</title>\n${this.renderStyles()}\n</head>\n<body>\n${this.renderHeaderHtml(result)}\n${this.renderDashboard(result)}\n${this.renderSeverityChart(result)}\n<div class=\"container\">\n ${this.renderFilters(result)}\n <div class=\"table-wrap\">\n <table id=\"findings-table\">\n <thead>\n <tr>\n <th class=\"th-expand\"></th>\n <th class=\"sortable\" data-sort=\"severity\">Severity <span class=\"sort-icon\">⇅</span></th>\n <th class=\"sortable\" data-sort=\"file\">File <span class=\"sort-icon\">⇅</span></th>\n <th>Line</th>\n <th class=\"sortable\" data-sort=\"rule\">Rule <span class=\"sort-icon\">⇅</span></th>\n <th class=\"sortable\" data-sort=\"category\">Category <span class=\"sort-icon\">⇅</span></th>\n <th>Confidence</th>\n <th>Title</th>\n </tr>\n </thead>\n <tbody id=\"findings-body\"></tbody>\n </table>\n <div id=\"no-results\" class=\"no-results\" style=\"display:none;\">\n <span class=\"no-results-icon\">🔍</span>\n <p>No findings match the current filters.</p>\n </div>\n </div>\n</div>\n${this.renderFooter(result)}\n<script>\n// ── Embedded Data ──\nconst FINDINGS = ${findingsJson};\nconst SUMMARY = ${summaryJson};\n${this.renderScript()}\n</script>\n</body>\n</html>`;\n }\n\n // ── HTML Fragments ─────────────────────────────────────────────────────\n\n private renderHeaderHtml(result: ScanResult): string {\n return `\n<header class=\"header\">\n <div class=\"header-inner\">\n <div class=\"logo-group\">\n <div class=\"logo-icon\">\n <svg viewBox=\"0 0 32 32\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect width=\"32\" height=\"32\" rx=\"8\" fill=\"#238636\"/>\n <path d=\"M16 6L26 12V20L16 26L6 20V12L16 6Z\" stroke=\"white\" stroke-width=\"2\" fill=\"none\"/>\n <circle cx=\"16\" cy=\"16\" r=\"4\" fill=\"white\"/>\n </svg>\n </div>\n <div>\n <h1 class=\"logo-text\">DeepScan</h1>\n <p class=\"logo-sub\">Security Report</p>\n </div>\n </div>\n <div class=\"header-meta\">\n <div class=\"meta-item\"><span class=\"meta-label\">Target</span><span class=\"meta-value\">${this.escapeHtml(result.target)}</span></div>\n <div class=\"meta-item\"><span class=\"meta-label\">Scanned</span><span class=\"meta-value\">${this.escapeHtml(result.summary.timestamp)}</span></div>\n <div class=\"meta-item\"><span class=\"meta-label\">Duration</span><span class=\"meta-value\">${this.formatDuration(result.summary.scanDuration)}</span></div>\n </div>\n </div>\n</header>`;\n }\n\n private renderDashboard(result: ScanResult): string {\n const s = result.summary;\n const severities: Severity[] = ['critical', 'high', 'medium', 'low'];\n\n const cards = severities\n .map(\n (sev) => `\n <div class=\"card card-${sev}\">\n <div class=\"card-count\">${s.bySeverity[sev]}</div>\n <div class=\"card-label\">${sev.charAt(0).toUpperCase() + sev.slice(1)}</div>\n <div class=\"card-badge\" style=\"background:${SEVERITY_COLORS[sev]}\">${sev.toUpperCase()}</div>\n </div>`,\n )\n .join('');\n\n return `\n<section class=\"dashboard container\">\n <div class=\"summary-cards\">\n <div class=\"card card-total\">\n <div class=\"card-count\">${s.totalFindings}</div>\n <div class=\"card-label\">Total Findings</div>\n <div class=\"card-sub\">${s.filesScanned} files scanned · ${s.filesWithFindings} with findings</div>\n </div>\n ${cards}\n </div>\n</section>`;\n }\n\n private renderSeverityChart(result: ScanResult): string {\n const s = result.summary;\n const total = s.totalFindings || 1;\n const severities: Severity[] = ['critical', 'high', 'medium', 'low'];\n\n const segments = severities\n .map((sev) => {\n const pct = ((s.bySeverity[sev] / total) * 100).toFixed(1);\n return Number(pct) > 0\n ? `<div class=\"chart-seg\" style=\"width:${pct}%;background:${SEVERITY_COLORS[sev]}\" title=\"${sev}: ${s.bySeverity[sev]} (${pct}%)\"></div>`\n : '';\n })\n .join('');\n\n const legend = severities\n .map(\n (sev) =>\n `<span class=\"legend-item\"><span class=\"legend-dot\" style=\"background:${SEVERITY_COLORS[sev]}\"></span>${sev} (${s.bySeverity[sev]})</span>`,\n )\n .join('');\n\n return `\n<section class=\"chart-section container\">\n <h2 class=\"section-title\">Severity Distribution</h2>\n <div class=\"chart-bar\">${segments}</div>\n <div class=\"chart-legend\">${legend}</div>\n</section>`;\n }\n\n private renderFilters(result: ScanResult): string {\n // Collect unique scanners and categories\n const scanners = [...new Set(result.findings.map((f) => f.scanner))].sort();\n const categories = [...new Set(result.findings.map((f) => f.category))].sort();\n\n const scannerOptions = scanners\n .map((s) => `<option value=\"${this.escapeHtml(s)}\">${this.escapeHtml(s)}</option>`)\n .join('');\n const categoryOptions = categories\n .map((c) => `<option value=\"${this.escapeHtml(c)}\">${this.escapeHtml(c)}</option>`)\n .join('');\n\n return `\n <div class=\"filters\">\n <div class=\"search-box\">\n <input type=\"text\" id=\"search-input\" placeholder=\"Search findings…\" autocomplete=\"off\" />\n </div>\n <div class=\"filter-group\">\n <select id=\"filter-severity\">\n <option value=\"\">All Severities</option>\n <option value=\"critical\">Critical</option>\n <option value=\"high\">High</option>\n <option value=\"medium\">Medium</option>\n <option value=\"low\">Low</option>\n </select>\n <select id=\"filter-scanner\">\n <option value=\"\">All Scanners</option>\n ${scannerOptions}\n </select>\n <select id=\"filter-category\">\n <option value=\"\">All Categories</option>\n ${categoryOptions}\n </select>\n <button id=\"btn-reset\" class=\"btn-reset\" title=\"Reset filters\">✕ Reset</button>\n </div>\n </div>`;\n }\n\n private renderFooter(result: ScanResult): string {\n return `\n<footer class=\"footer\">\n <div class=\"footer-inner\">\n <span>${this.escapeHtml(result.tool.name)} v${this.escapeHtml(result.tool.version)}</span>\n <span>Report generated ${new Date().toISOString()}</span>\n </div>\n</footer>`;\n }\n\n // ── CSS ────────────────────────────────────────────────────────────────\n\n private renderStyles(): string {\n return `<style>\n/* ── Reset & Base ─────────────────────────────────────────────────── */\n*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}\nhtml{font-size:14px;-webkit-font-smoothing:antialiased}\nbody{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,sans-serif;\n background:#f6f8fa;color:#24292f;line-height:1.6;min-height:100vh}\na{color:#0969da;text-decoration:none}\na:hover{text-decoration:underline}\n\n/* ── Container ────────────────────────────────────────────────────── */\n.container{max-width:1280px;margin:0 auto;padding:0 24px}\n\n/* ── Header ───────────────────────────────────────────────────────── */\n.header{background:#ffffff;border-bottom:1px solid #d0d7de;padding:20px 0;box-shadow: 0 1px 3px rgba(0,0,0,0.05)}\n.header-inner{max-width:1280px;margin:0 auto;padding:0 24px;display:flex;\n align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px}\n.logo-group{display:flex;align-items:center;gap:12px}\n.logo-icon svg{width:40px;height:40px}\n.logo-text{font-size:1.5rem;font-weight:700;color:#24292f;line-height:1.2}\n.logo-sub{font-size:.85rem;color:#57606a}\n.header-meta{display:flex;gap:24px;flex-wrap:wrap}\n.meta-item{display:flex;flex-direction:column}\n.meta-label{font-size:.7rem;text-transform:uppercase;color:#57606a;letter-spacing:.05em}\n.meta-value{color:#24292f;font-weight:500;font-size:.9rem}\n\n/* ── Dashboard Cards ──────────────────────────────────────────────── */\n.dashboard{padding-top:24px}\n.summary-cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px}\n.card{background:#ffffff;border:1px solid #d0d7de;border-radius:12px;padding:20px;\n text-align:center;position:relative;overflow:hidden;transition:transform .15s,box-shadow .15s;\n box-shadow: 0 1px 3px rgba(0,0,0,0.05)}\n.card:hover{transform:translateY(-2px);box-shadow:0 8px 24px rgba(140,149,159,.2)}\n.card-total{grid-column:span 1;border-top:3px solid #8c959f}\n.card-count{font-size:2.4rem;font-weight:700;color:#24292f}\n.card-label{font-size:.9rem;color:#57606a;margin-top:2px}\n.card-sub{font-size:.75rem;color:#57606a;margin-top:6px}\n.card-badge{display:inline-block;margin-top:8px;padding:2px 10px;border-radius:20px;\n font-size:.65rem;font-weight:700;color:#fff;letter-spacing:.05em}\n.card-critical{border-top:3px solid ${SEVERITY_COLORS.critical}}\n.card-high{border-top:3px solid ${SEVERITY_COLORS.high}}\n.card-medium{border-top:3px solid ${SEVERITY_COLORS.medium}}\n.card-low{border-top:3px solid ${SEVERITY_COLORS.low}}\n\n/* ── Chart ─────────────────────────────────────────────────────────── */\n.chart-section{padding:28px 24px}\n.section-title{font-size:1rem;font-weight:600;color:#24292f;margin-bottom:12px}\n.chart-bar{display:flex;height:28px;border-radius:6px;overflow:hidden;background:#eaeef2}\n.chart-seg{transition:width .4s ease}\n.chart-legend{display:flex;gap:16px;margin-top:10px;flex-wrap:wrap}\n.legend-item{display:flex;align-items:center;gap:5px;font-size:.8rem;color:#57606a}\n.legend-dot{width:10px;height:10px;border-radius:50%;display:inline-block}\n\n/* ── Filters ──────────────────────────────────────────────────────── */\n.filters{display:flex;flex-wrap:wrap;gap:12px;padding:20px 0;align-items:center}\n.search-box{flex:1;min-width:220px}\n.search-box input{width:100%;padding:8px 14px;border-radius:8px;border:1px solid #d0d7de;\n background:#ffffff;color:#24292f;font-size:.9rem;outline:none;transition:border-color .2s, box-shadow .2s}\n.search-box input:focus{border-color:#0969da;box-shadow: 0 0 0 3px rgba(9,105,218,0.15)}\n.filter-group{display:flex;gap:8px;flex-wrap:wrap;align-items:center}\n.filter-group select{padding:8px 12px;border-radius:8px;border:1px solid #d0d7de;\n background:#ffffff;color:#24292f;font-size:.85rem;cursor:pointer;outline:none;transition:border-color .2s}\n.filter-group select:focus{border-color:#0969da}\n.btn-reset{padding:8px 14px;border-radius:8px;border:1px solid #d0d7de;background:#ffffff;\n color:#cf222e;font-size:.85rem;cursor:pointer;transition:background .15s, border-color .15s}\n.btn-reset:hover{background:#f6f8fa}\n\n/* ── Table ─────────────────────────────────────────────────────────── */\n.table-wrap{overflow-x:auto;border:1px solid #d0d7de;border-radius:12px;background:#ffffff;margin-bottom:32px;box-shadow: 0 1px 3px rgba(0,0,0,0.02)}\ntable{width:100%;border-collapse:collapse}\nthead th{background:#f6f8fa;color:#57606a;font-weight:600;font-size:.8rem;\n text-transform:uppercase;letter-spacing:.04em;padding:12px 14px;text-align:left;\n position:sticky;top:0;border-bottom:1px solid #d0d7de;white-space:nowrap;user-select:none}\nth.sortable{cursor:pointer}\nth.sortable:hover{color:#24292f}\n.sort-icon{font-size:.7rem;opacity:.5}\nth.sort-active .sort-icon{opacity:1;color:#0969da}\ntbody tr{border-bottom:1px solid #eaeef2;transition:background .1s}\ntbody tr.finding-row{cursor:pointer}\ntbody tr.finding-row:hover{background:#f6f8fa}\ntbody td{padding:10px 14px;font-size:.88rem;vertical-align:top;color:#24292f}\n.th-expand{width:32px}\n\n/* ── Severity badges ──────────────────────────────────────────────── */\n.badge{display:inline-block;padding:2px 10px;border-radius:20px;font-size:.75rem;\n font-weight:700;color:#fff;letter-spacing:.03em;text-transform:uppercase}\n.badge-critical{background:${SEVERITY_COLORS.critical}}\n.badge-high{background:${SEVERITY_COLORS.high}}\n.badge-medium{background:${SEVERITY_COLORS.medium}}\n.badge-low{background:${SEVERITY_COLORS.low}}\n.confidence-badge{font-size:.75rem;color:#57606a;border:1px solid #d0d7de;\n padding:1px 8px;border-radius:12px;background:#f6f8fa}\n\n/* ── Expand toggle ─────────────────────────────────────────────────── */\n.expand-btn{width:24px;height:24px;border:none;background:#eaeef2;color:#57606a;\n border-radius:6px;cursor:pointer;font-size:.8rem;display:flex;align-items:center;\n justify-content:center;transition:transform .2s,background .15s}\n.expand-btn:hover{background:#d0d7de}\n.expand-btn.open{transform:rotate(90deg);color:#0969da;background:#ddf4ff}\n\n/* ── Detail row ────────────────────────────────────────────────────── */\n.detail-row td{padding:0 !important;border-bottom:1px solid #eaeef2}\n.detail-content{padding:16px 24px;background:#fafbfc;display:none;animation:fadeIn .2s ease}\n.detail-content.open{display:block}\n.detail-section{margin-bottom:14px}\n.detail-section:last-child{margin-bottom:0}\n.detail-section h4{font-size:.8rem;color:#0969da;text-transform:uppercase;\n letter-spacing:.05em;margin-bottom:6px}\n.snippet-block{background:#f6f8fa;border:1px solid #d0d7de;border-radius:8px;\n padding:8px 0;overflow-x:auto;font-family:'SFMono-Regular',Consolas,'Liberation Mono',\n Menlo,monospace;font-size:.82rem;line-height:1.6;color:#24292f}\n.snippet-line{display:flex;padding:2px 16px}\n.snippet-line:hover{background:#eaeef2}\n.target-line{background:#fff8c5;border-left:3px solid #bf8700;padding-left:13px}\n.target-line:hover{background:#fff8c5}\n.line-number{width:36px;color:#8c959f;user-select:none;text-align:right;padding-right:12px;display:inline-block}\n.line-content{white-space:pre;display:inline-block}\n.fix-block{background:#dafbe1;border:1px solid #2da44e;border-radius:8px;padding:12px 16px;\n color:#1a7f37;font-size:.85rem;font-weight:500}\n.tags-list{display:flex;gap:6px;flex-wrap:wrap}\n.tag{background:#eaeef2;color:#57606a;padding:2px 8px;border-radius:12px;font-size:.75rem}\n.tag-cwe{color:#953800;border:1px solid #ffe1cc;background:#fff8f5}\n.tag-owasp{color:#8250df;border:1px solid #f5f0ff;background:#faf7ff}\n.tag-link{cursor:pointer;transition:background-color .15s,color .15s,border-color .15s}\n.tag-link:hover{background:#eaeef2;color:#0969da;text-decoration:none;border-color:#0969da66}\n.tag-link.tag-cwe:hover{background:#ffe1cc;color:#953800;border-color:#95380066}\n\n/* ── Taint flow ────────────────────────────────────────────────────── */\n.taint-flow{display:flex;flex-direction:column;gap:4px}\n.taint-step{display:flex;align-items:center;gap:8px;padding:4px 8px;border-radius:6px;\n background:#f6f8fa;border:1px solid #d0d7de;font-size:.82rem}\n.taint-kind{padding:1px 6px;border-radius:4px;font-size:.7rem;font-weight:700;text-transform:uppercase}\n.taint-source{background:#ffebe9;color:#cf222e}\n.taint-sink{background:#ffebe9;color:#cf222e}\n.taint-propagator{background:#fff8c5;color:#bf8700}\n.taint-sanitizer{background:#dafbe1;color:#1a7f37}\n.taint-label{color:#24292f}\n.taint-loc{color:#57606a;font-size:.75rem;margin-left:auto}\n\n/* ── No results ────────────────────────────────────────────────────── */\n.no-results{text-align:center;padding:48px 24px;color:#57606a}\n.no-results-icon{font-size:2.5rem}\n\n/* ── Footer ────────────────────────────────────────────────────────── */\n.footer{border-top:1px solid #d0d7de;padding:16px 0;margin-top:16px}\n.footer-inner{max-width:1280px;margin:0 auto;padding:0 24px;display:flex;\n justify-content:space-between;font-size:.8rem;color:#57606a}\n\n/* ── Animation ─────────────────────────────────────────────────────── */\n@keyframes fadeIn{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none}}\n\n/* ── Responsive ────────────────────────────────────────────────────── */\n@media(max-width:768px){\n .header-inner{flex-direction:column;align-items:flex-start}\n .summary-cards{grid-template-columns:repeat(2,1fr)}\n .filters{flex-direction:column}\n .filter-group{width:100%;justify-content:stretch}\n .filter-group select,.search-box input{width:100%}\n .footer-inner{flex-direction:column;gap:4px}\n}\n</style>`;\n }\n\n // ── JavaScript ─────────────────────────────────────────────────────────\n\n private renderScript(): string {\n return `\n// ── Severity ordering ──\nconst SEV_ORDER = { critical: 0, high: 1, medium: 2, low: 3 };\n\n// ── State ──\nlet currentSort = { key: 'severity', dir: 'asc' };\nlet filteredFindings = [...FINDINGS];\n\n// ── DOM references ──\nconst tbody = document.getElementById('findings-body');\nconst noResults = document.getElementById('no-results');\nconst searchInput = document.getElementById('search-input');\nconst filterSeverity = document.getElementById('filter-severity');\nconst filterScanner = document.getElementById('filter-scanner');\nconst filterCategory = document.getElementById('filter-category');\nconst btnReset = document.getElementById('btn-reset');\n\n// ── Render ──\nfunction renderTable() {\n tbody.innerHTML = '';\n if (filteredFindings.length === 0) {\n noResults.style.display = 'block';\n return;\n }\n noResults.style.display = 'none';\n filteredFindings.forEach((f, idx) => {\n // Main row\n const tr = document.createElement('tr');\n tr.className = 'finding-row';\n tr.innerHTML = \\`\n <td><button class=\"expand-btn\" data-idx=\"\\${idx}\">▸</button></td>\n <td><span class=\"badge badge-\\${f.severity}\">\\${f.severity}</span></td>\n <td title=\"\\${esc(f.file)}\">\\${truncPath(f.file)}</td>\n <td>\\${f.line}</td>\n <td><code>\\${esc(f.ruleId)}</code></td>\n <td>\\${esc(f.category)}</td>\n <td><span class=\"confidence-badge\">\\${f.confidence}</span></td>\n <td>\\${esc(f.title)}</td>\n \\`;\n tbody.appendChild(tr);\n\n // Detail row\n const detailTr = document.createElement('tr');\n detailTr.className = 'detail-row';\n detailTr.innerHTML = '<td colspan=\"8\"><div class=\"detail-content\" id=\"detail-' + idx + '\">' + buildDetail(f) + '</div></td>';\n tbody.appendChild(detailTr);\n });\n\n // Bind finding-row click handler to expand rows\n document.querySelectorAll('.finding-row').forEach(row => {\n row.addEventListener('click', (e) => {\n // If the click target is a link or another interactive element, do not toggle expand state\n if (e.target.closest('a') || e.target.closest('button:not(.expand-btn)')) {\n return;\n }\n const btn = row.querySelector('.expand-btn');\n const idx = btn.getAttribute('data-idx');\n const detail = document.getElementById('detail-' + idx);\n const isOpen = detail.classList.contains('open');\n detail.classList.toggle('open');\n btn.classList.toggle('open');\n btn.textContent = isOpen ? '▸' : '▾';\n });\n });\n}\n\nfunction buildDetail(f) {\n let html = '';\n // Message\n html += '<div class=\"detail-section\"><h4>Description</h4><p>' + esc(f.message) + '</p></div>';\n // Snippet\n if (f.snippet) {\n const lines = f.snippet.split(/\\\\r?\\\\n/);\n let startLine = f.snippetStartLine ?? Math.max(1, f.line - 3);\n let snippetHtml = '<div class=\"snippet-block\">';\n lines.forEach((line, idx) => {\n const currentLineNum = startLine + idx;\n const isTarget = currentLineNum >= f.line && currentLineNum <= (f.endLine || f.line);\n const lineClass = isTarget ? 'snippet-line target-line' : 'snippet-line';\n snippetHtml += '<div class=\"' + lineClass + '\">'\n + '<span class=\"line-number\">' + currentLineNum + '</span>'\n + '<span class=\"line-content\">' + esc(line) + '</span>'\n + '</div>';\n });\n snippetHtml += '</div>';\n html += '<div class=\"detail-section\"><h4>Code Snippet</h4>' + snippetHtml + '</div>';\n }\n // Fix\n if (f.fix) {\n html += '<div class=\"detail-section\"><h4>Suggested Fix</h4><div class=\"fix-block\">' + esc(f.fix) + '</div></div>';\n }\n // Taint flow\n if (f.taintFlow && f.taintFlow.length > 0) {\n html += '<div class=\"detail-section\"><h4>Taint Flow</h4><div class=\"taint-flow\">';\n f.taintFlow.forEach(step => {\n html += '<div class=\"taint-step\">'\n + '<span class=\"taint-kind taint-' + step.kind + '\">' + step.kind + '</span>'\n + '<span class=\"taint-label\">' + esc(step.label) + '</span>'\n + '<span class=\"taint-loc\">' + esc(step.file) + ':' + step.line + '</span>'\n + '</div>';\n });\n html += '</div></div>';\n }\n // Tags\n if ((f.cwe && f.cwe.length) || (f.owasp && f.owasp.length) || (f.tags && f.tags.length) || (f.references && f.references.length)) {\n html += '<div class=\"detail-section\"><h4>References</h4><div class=\"tags-list\">';\n (f.cwe || []).forEach(c => {\n const cStr = String(c);\n const cleanCwe = cStr.startsWith('CWE-') ? cStr : 'CWE-' + cStr;\n const cweNum = cStr.replace('CWE-', '');\n html += '<a href=\"https://cwe.mitre.org/data/definitions/' + cweNum + '.html\" target=\"_blank\" class=\"tag tag-cwe tag-link\">' + esc(cleanCwe) + ' ↗</a>';\n });\n (f.owasp || []).forEach(o => { html += '<span class=\"tag tag-owasp\">' + esc(o) + '</span>'; });\n (f.tags || []).forEach(t => { html += '<span class=\"tag\">' + esc(t) + '</span>'; });\n (f.references || []).forEach(r => {\n if (r.startsWith('http://') || r.startsWith('https://')) {\n let label = r;\n if (r.length > 50) {\n try {\n const url = new URL(r);\n label = url.hostname + (url.pathname.length > 20 ? url.pathname.slice(0, 20) + '…' : url.pathname);\n } catch (e) {\n label = r.substring(0, 47) + '…';\n }\n }\n html += '<a href=\"' + esc(r) + '\" target=\"_blank\" class=\"tag tag-link\">' + esc(label) + ' ↗</a>';\n } else {\n html += '<span class=\"tag\">' + esc(r) + '</span>';\n }\n });\n html += '</div></div>';\n }\n return html;\n}\n\n// ── Sorting ──\ndocument.querySelectorAll('th.sortable').forEach(th => {\n th.addEventListener('click', () => {\n const key = th.getAttribute('data-sort');\n if (currentSort.key === key) {\n currentSort.dir = currentSort.dir === 'asc' ? 'desc' : 'asc';\n } else {\n currentSort = { key, dir: 'asc' };\n }\n document.querySelectorAll('th.sortable').forEach(h => h.classList.remove('sort-active'));\n th.classList.add('sort-active');\n applySort();\n renderTable();\n });\n});\n\nfunction applySort() {\n const { key, dir } = currentSort;\n const mul = dir === 'asc' ? 1 : -1;\n filteredFindings.sort((a, b) => {\n let va, vb;\n if (key === 'severity') {\n va = SEV_ORDER[a.severity] ?? 4;\n vb = SEV_ORDER[b.severity] ?? 4;\n } else if (key === 'file') {\n va = a.file.toLowerCase();\n vb = b.file.toLowerCase();\n } else if (key === 'rule') {\n va = a.ruleId.toLowerCase();\n vb = b.ruleId.toLowerCase();\n } else if (key === 'category') {\n va = a.category.toLowerCase();\n vb = b.category.toLowerCase();\n } else {\n va = a[key]; vb = b[key];\n }\n if (va < vb) return -1 * mul;\n if (va > vb) return 1 * mul;\n return 0;\n });\n}\n\n// ── Filtering ──\nfunction applyFilters() {\n const search = searchInput.value.toLowerCase().trim();\n const sev = filterSeverity.value;\n const scn = filterScanner.value;\n const cat = filterCategory.value;\n\n filteredFindings = FINDINGS.filter(f => {\n if (sev && f.severity !== sev) return false;\n if (scn && f.scanner !== scn) return false;\n if (cat && f.category !== cat) return false;\n if (search) {\n const haystack = [f.title, f.message, f.ruleId, f.file, f.category, f.severity]\n .join(' ').toLowerCase();\n if (!haystack.includes(search)) return false;\n }\n return true;\n });\n applySort();\n renderTable();\n}\n\nsearchInput.addEventListener('input', applyFilters);\nfilterSeverity.addEventListener('change', applyFilters);\nfilterScanner.addEventListener('change', applyFilters);\nfilterCategory.addEventListener('change', applyFilters);\nbtnReset.addEventListener('click', () => {\n searchInput.value = '';\n filterSeverity.value = '';\n filterScanner.value = '';\n filterCategory.value = '';\n applyFilters();\n});\n\n// ── Utilities ──\nfunction esc(s) { if (!s) return ''; const d = document.createElement('div'); d.textContent = String(s); return d.innerHTML; }\nfunction escCode(s) { return esc(s).replace(/\\\\n/g, '\\\\n'); }\nfunction truncPath(p) {\n if (!p) return '';\n const parts = p.replace(/\\\\\\\\\\\\\\\\/g, '/').split('/');\n if (parts.length <= 3) return esc(p);\n return esc('…/' + parts.slice(-3).join('/'));\n}\n\n// ── Initial render ──\napplySort();\nrenderTable();\n`;\n }\n\n // ── Data serialisation ────────────────────────────────────────────────\n\n /**\n * Flatten a Finding into a plain object suitable for embedding in the HTML\n * page's JavaScript. Keeps only the fields the front-end actually uses.\n */\n private serializeFinding(f: Finding): Record<string, unknown> {\n return {\n id: f.id,\n ruleId: f.ruleId,\n scanner: f.scanner,\n severity: f.severity,\n confidence: f.confidence,\n category: f.category,\n title: f.title,\n message: f.message,\n file: f.location.file,\n line: f.location.startLine,\n endLine: f.location.endLine,\n snippetStartLine: f.location.snippetStartLine ?? Math.max(1, f.location.startLine - 3),\n snippet: f.location.snippet || '',\n fix: f.fix?.description ?? null,\n cwe: f.cwe ?? [],\n owasp: f.owasp ?? [],\n tags: f.metadata.tags ?? [],\n references: f.references ?? f.fix?.references ?? [],\n taintFlow: f.taintFlow\n ? f.taintFlow.map((step) => ({\n kind: step.kind,\n label: step.label,\n file: step.location.file,\n line: step.location.startLine,\n }))\n : [],\n };\n }\n\n // ── HTML helpers ───────────────────────────────────────────────────────\n\n private escapeHtml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#x27;');\n }\n}\n","// ─── Reporter Module Index ──────────────────────────────────────────────────\n// Exports all reporters and provides a factory function.\n\nimport type { IReporter } from '../types/scanner.js';\nimport type { OutputFormat } from '../types/config.js';\n\nimport { ConsoleReporter } from './console-reporter.js';\nimport { JsonReporter } from './json-reporter.js';\nimport { CsvReporter } from './csv-reporter.js';\nimport { SarifReporter } from './sarif-reporter.js';\nimport { HtmlReporter } from './html-reporter.js';\n\n// ── Re-exports ───────────────────────────────────────────────────────────\n\nexport { BaseReporter } from './base-reporter.js';\nexport { ConsoleReporter } from './console-reporter.js';\nexport { JsonReporter } from './json-reporter.js';\nexport { CsvReporter } from './csv-reporter.js';\nexport { SarifReporter } from './sarif-reporter.js';\nexport { HtmlReporter } from './html-reporter.js';\n\n// ── Factory ──────────────────────────────────────────────────────────────\n\n/**\n * Instantiate the appropriate reporter for the given output format.\n *\n * @param format - One of the supported `OutputFormat` values.\n * @returns A ready-to-use `IReporter` instance.\n * @throws If an unsupported format is provided.\n *\n * @example\n * ```ts\n * const reporter = getReporter('html');\n * const html = await reporter.generate(scanResult);\n * ```\n */\nexport function getReporter(format: OutputFormat): IReporter {\n switch (format) {\n case 'console':\n return new ConsoleReporter();\n case 'json':\n return new JsonReporter();\n case 'csv':\n return new CsvReporter();\n case 'sarif':\n return new SarifReporter();\n case 'html':\n return new HtmlReporter();\n default: {\n // Exhaustiveness check – TypeScript will flag if a new OutputFormat is\n // added but not handled here.\n const _exhaustive: never = format;\n throw new Error(`Unsupported output format: ${String(_exhaustive)}`);\n }\n }\n}\n","// ─── Base Scanner ──────────────────────────────────────────────────────────\n// Lớp cơ sở trừu tượng cho tất cả scanner engines\n// Abstract base class implementing IScanner with common utilities\n\nimport { createHash } from 'node:crypto';\nimport type { Finding, Severity, Confidence, ScannerType, SourceLocation, FixSuggestion } from '../types/finding.js';\nimport type { IScanner, ScanFileContext } from '../types/scanner.js';\nimport type { DeepScanConfig } from '../types/config.js';\nimport type { Rule } from '../types/rule.js';\n\n// ─── Helper Types ──────────────────────────────────────────────────────────\n\n/** Options for creating a finding */\nexport interface CreateFindingOptions {\n ruleId: string;\n scanner: ScannerType;\n severity: Severity;\n confidence: Confidence;\n category: string;\n subcategory?: string;\n title: string;\n message: string;\n filePath: string;\n lineNumber: number;\n column?: number;\n endLine?: number;\n endColumn?: number;\n snippet: string;\n snippetStartLine?: number;\n cwe?: string[];\n owasp?: string[];\n fix?: FixSuggestion;\n references?: string[];\n tags?: string[];\n}\n\n// ─── Utility Functions ─────────────────────────────────────────────────────\n\n/**\n * Generate a stable fingerprint for a finding.\n * Uses ruleId + filePath + line content hash for deduplication across scans.\n * Tạo fingerprint ổn định cho finding để nhận diện qua các lần quét\n */\nexport function generateFingerprint(ruleId: string, filePath: string, snippet: string): string {\n const input = `${ruleId}::${filePath}::${snippet.trim()}`;\n return createHash('sha256').update(input).digest('hex').substring(0, 16);\n}\n\n/**\n * Extract a code snippet around a given line number or range.\n * Trích xuất đoạn code xung quanh dòng hoặc đoạn dòng được chỉ định\n * @param source - Full source code\n * @param startLine - 1-indexed start line number\n * @param endLine - 1-indexed end line number (defaults to startLine)\n * @param contextLines - Number of lines above and below to include (default: 3)\n */\nexport function extractSnippet(\n source: string,\n startLine: number,\n endLine: number = startLine,\n contextLines: number = 3,\n): string {\n const lines = source.split('\\n');\n const start = Math.max(0, startLine - 1 - contextLines);\n const end = Math.min(lines.length, endLine + contextLines);\n return lines.slice(start, end).join('\\n');\n}\n\n/**\n * Create a fully-formed Finding object from options.\n * Tạo đối tượng Finding hoàn chỉnh từ các tùy chọn\n */\nexport function createFinding(options: CreateFindingOptions): Finding {\n const fingerprint = generateFingerprint(options.ruleId, options.filePath, options.snippet);\n\n const location: SourceLocation = {\n file: options.filePath,\n startLine: options.lineNumber,\n startColumn: options.column ?? 1,\n endLine: options.endLine ?? options.lineNumber,\n endColumn: options.endColumn ?? (options.column ?? 1),\n snippet: options.snippet,\n snippetStartLine: options.snippetStartLine ?? Math.max(1, options.lineNumber - 3),\n };\n\n return {\n id: `${options.scanner}-${fingerprint}`,\n ruleId: options.ruleId,\n scanner: options.scanner,\n severity: options.severity,\n confidence: options.confidence,\n category: options.category,\n subcategory: options.subcategory,\n title: options.title,\n message: options.message,\n location,\n cwe: options.cwe,\n owasp: options.owasp,\n fix: options.fix,\n references: options.references ?? options.fix?.references ?? [],\n metadata: {\n fingerprint,\n firstSeen: new Date().toISOString(),\n tags: options.tags ?? [],\n },\n };\n}\n\n/**\n * Match a regex pattern against source code and return all matches with line info.\n * Khớp mẫu regex với mã nguồn và trả về tất cả kết quả kèm thông tin dòng\n */\nexport function matchPattern(\n source: string,\n pattern: RegExp,\n): Array<{ line: number; column: number; match: string; lineContent: string }> {\n const results: Array<{ line: number; column: number; match: string; lineContent: string }> = [];\n const lines = source.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const lineContent = lines[i];\n // Reset lastIndex for global patterns\n const regex = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g');\n let m: RegExpExecArray | null;\n while ((m = regex.exec(lineContent)) !== null) {\n results.push({\n line: i + 1, // 1-indexed\n column: m.index + 1,\n match: m[0],\n lineContent,\n });\n // Prevent infinite loop on zero-width matches\n if (m.index === regex.lastIndex) regex.lastIndex++;\n }\n }\n\n return results;\n}\n\n/**\n * Check if a line is inside a comment or string literal (basic heuristic).\n * Kiểm tra xem dòng có nằm trong comment hoặc chuỗi ký tự không\n */\nexport function isInCommentOrString(line: string, column: number): boolean {\n const trimmed = line.trimStart();\n // Single-line comment check\n if (trimmed.startsWith('//') || trimmed.startsWith('#') || trimmed.startsWith('*') || trimmed.startsWith('/*')) {\n return true;\n }\n return false;\n}\n\n/**\n * Check if a regex match falls inside a pattern/rule definition context,\n * indicating a likely false positive when scanning static analysis tool\n * source code or similar data-definition files.\n *\n * Detects:\n * 1. Match inside a regex literal: /somePattern/flags\n * 2. Line is a property in a pattern/rule definition object\n * (e.g., `regex: /.../, pattern: '...', message: '...'`)\n * 3. Line defines a taint sink/source pattern string\n * (e.g., `{ pattern: 'eval($TAINTED)', ... }`)\n * 4. Match inside a string literal that is being assigned to a data property\n */\nexport function isPatternDefinitionContext(lineContent: string, column: number): boolean {\n const trimmed = lineContent.trimStart();\n\n // 1. Line is a property in a pattern definition object\n // (regex:, pattern:, message:, description:)\n if (/^\\s*(?:regex|pattern|message|description)\\s*[:=]\\s/.test(lineContent)) {\n return true;\n }\n\n // 2. Check if match is inside a regex literal on this line\n // Look for the pattern: / ... <match> ... /flags\n // We scan for regex literal boundaries (unescaped `/` not preceded by `\\`)\n const regexLiteralRanges = findRegexLiteralRanges(lineContent);\n const colIdx = column - 1; // Convert to 0-indexed\n for (const [start, end] of regexLiteralRanges) {\n if (colIdx >= start && colIdx <= end) {\n return true;\n }\n }\n\n // 3. Taint sink/source definition strings\n // e.g., { pattern: 'eval($TAINTED)', type: 'code_injection', description: '...' }\n if (/\\bpattern\\s*:\\s*['\"]/.test(trimmed) && /\\$TAINTED|\\$BUF|\\$X/.test(trimmed)) {\n return true;\n }\n\n // 4. Line is inside a taint sink/source array entry\n // e.g., { pattern: 'system($TAINTED)', type: 'command_injection', ... }\n if (/\\btype\\s*:\\s*'(?:code_injection|command_injection|sql_injection|xss|path_traversal|buffer_overflow|format_string|file_inclusion|deserialization|network)'/.test(trimmed)) {\n return true;\n }\n\n // 5. Line contains a string that defines a detection pattern with meta-references\n // e.g., cwe: ['CWE-...'], or severity: '...' as part of rule definition objects\n if (/\\bcwe\\s*:\\s*\\[/.test(trimmed) && /\\bseverity\\s*:\\s*['\"]/.test(lineContent)) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Find ranges (start, end) of regex literals in a line of JavaScript/TypeScript code.\n * Returns an array of [startIndex, endIndex] pairs (0-indexed, inclusive).\n * Handles escaped characters inside regex literals.\n */\nfunction findRegexLiteralRanges(line: string): Array<[number, number]> {\n const ranges: Array<[number, number]> = [];\n const len = line.length;\n let i = 0;\n\n while (i < len) {\n const ch = line[i];\n\n // Skip string literals (single, double, backtick)\n if (ch === \"'\" || ch === '\"' || ch === '`') {\n i = skipStringLiteral(line, i);\n continue;\n }\n\n // Skip single-line comments\n if (ch === '/' && i + 1 < len && line[i + 1] === '/') {\n break; // Rest of line is a comment\n }\n\n // Detect regex literal start\n // A `/` is a regex start if preceded by certain tokens (heuristic)\n if (ch === '/' && i + 1 < len && line[i + 1] !== '/' && line[i + 1] !== '*') {\n if (isRegexStart(line, i)) {\n const start = i;\n i++; // skip opening /\n // Find closing /\n while (i < len) {\n if (line[i] === '\\\\' && i + 1 < len) {\n i += 2; // skip escaped character\n continue;\n }\n if (line[i] === '/') {\n // Skip flags after closing /\n const end = i;\n i++;\n while (i < len && /[gimsuy]/.test(line[i])) i++;\n ranges.push([start, end]);\n break;\n }\n i++;\n }\n continue;\n }\n }\n\n i++;\n }\n\n return ranges;\n}\n\n/**\n * Heuristic: check if a `/` at position `pos` in `line` is the start of a regex literal.\n * A `/` starts a regex if the preceding non-whitespace token is one of:\n * = ( [ ! & | ? : ; , { } ~ ^ % + - * return typeof void delete case in instanceof\n * or the line starts with `/` (beginning of statement).\n */\nfunction isRegexStart(line: string, pos: number): boolean {\n if (pos === 0) return true;\n\n // Look backwards for the previous non-whitespace character\n let j = pos - 1;\n while (j >= 0 && (line[j] === ' ' || line[j] === '\\t')) j--;\n if (j < 0) return true;\n\n const prevChar = line[j];\n // These characters can precede a regex literal\n if ('=([!&|?:;,{}~^%+-*<>'.includes(prevChar)) return true;\n\n // Check for keyword predecessors (return, typeof, etc.)\n const before = line.substring(0, j + 1).trimEnd();\n if (/(?:return|typeof|void|delete|case|in|instanceof|new|throw|of)\\s*$/.test(before)) return true;\n\n return false;\n}\n\n/**\n * Skip a string literal starting at position `pos` in `line`.\n * Returns the index after the closing quote.\n */\nfunction skipStringLiteral(line: string, pos: number): number {\n const quote = line[pos];\n let i = pos + 1;\n while (i < line.length) {\n if (line[i] === '\\\\' && i + 1 < line.length) {\n i += 2; // skip escaped character\n continue;\n }\n if (line[i] === quote) {\n return i + 1;\n }\n i++;\n }\n return i;\n}\n\n/**\n * Check if a match at (line, column) is in a \"safe\" AST context:\n * string literal, comment, import statement, or type annotation.\n * Uses tree-sitter AST if available, otherwise returns false (falls back to regex heuristics).\n * \n * @param tree - Tree from web-tree-sitter (or null)\n * @param line - 1-indexed line number\n * @param column - 1-indexed column number\n */\nexport function isInSafeASTContext(\n tree: import('web-tree-sitter').Tree | null,\n line: number,\n column: number,\n): boolean {\n if (!tree) return false;\n\n try {\n // Get the AST node at the match position (tree-sitter uses 0-indexed)\n const node = tree.rootNode.descendantForPosition({ row: line - 1, column: column - 1 });\n if (!node) return false;\n\n // Walk up ancestors to check context\n let current: import('web-tree-sitter').Node | null = node;\n while (current) {\n const type = current.type;\n\n // Comments\n if (type === 'comment' || type === 'line_comment' || type === 'block_comment') return true;\n\n // Bare string statements (docstrings and directives)\n if (\n (type === 'string' || type === 'string_literal' ||\n type === 'string_content' || type === 'interpreted_string_literal') &&\n (current.parent?.type === 'expression_statement' || current.parent?.parent?.type === 'expression_statement')\n ) return true;\n\n // Template strings are only safe if they have no interpolation\n if (type === 'template_string') {\n let hasInterpolation = false;\n for (let i = 0; i < current.childCount; i++) {\n if (current.child(i)?.type === 'template_substitution') {\n hasInterpolation = true;\n break;\n }\n }\n if (!hasInterpolation) return true;\n }\n\n // Import/require statements\n if (\n type === 'import_statement' || type === 'import_declaration' ||\n type === 'import_from_statement'\n ) return true;\n\n // Type annotations (TypeScript)\n if (\n type === 'type_annotation' || type === 'type_alias_declaration' ||\n type === 'interface_declaration'\n ) return true;\n\n current = current.parent;\n }\n } catch {\n // Tree-sitter errors — fall back gracefully\n }\n return false;\n}\n\n// ─── Abstract Base Scanner ─────────────────────────────────────────────────\n\n/**\n * Abstract base class that implements IScanner.\n * Provides common rule matching, fingerprinting, and snippet extraction.\n * Lớp cơ sở trừu tượng cung cấp các tiện ích chung cho scanner\n */\nexport abstract class BaseScanner implements IScanner {\n abstract name: string;\n abstract type: 'security' | 'quality' | 'cve';\n\n protected config: DeepScanConfig | null = null;\n\n async initialize(config: DeepScanConfig): Promise<void> {\n this.config = config;\n }\n\n abstract scanFile(context: ScanFileContext): Promise<Finding[]>;\n\n async destroy(): Promise<void> {\n this.config = null;\n }\n\n /**\n * Match all rule patterns against source code and return findings.\n * Khớp tất cả rule patterns với mã nguồn và trả về findings\n */\n protected matchRulePatterns(context: ScanFileContext, rules: Rule[]): Finding[] {\n const findings: Finding[] = [];\n\n for (const rule of rules) {\n if (rule.enabled === false) continue;\n\n // Check if rule applies to this language\n if (rule.languages.length > 0 && !rule.languages.includes(context.language) && !rule.languages.includes('*')) {\n continue;\n }\n\n for (const rulePattern of rule.patterns) {\n // Use regex pattern if available\n const regexStr = rulePattern.regex ?? rulePattern.pattern;\n if (!regexStr) continue;\n\n try {\n const flags = rulePattern.regexFlags ?? 'gi';\n const regex = new RegExp(regexStr, flags);\n const matches = matchPattern(context.content, regex);\n\n for (const match of matches) {\n // Skip matches inside comments\n if (isInCommentOrString(match.lineContent, match.column)) continue;\n\n // Skip matches inside pattern/rule definition contexts (regex literals, data objects)\n if (isPatternDefinitionContext(match.lineContent, match.column)) continue;\n\n // AST-based context check: skip matches in string literals, comments, imports, type annotations\n if (context.tree && isInSafeASTContext(context.tree, match.line, match.column)) continue;\n\n // Skip secrets rules matching environment variables or template strings\n if (\n rule.category === 'secrets' ||\n rule.id === 'security/hardcoded-secret' ||\n rule.id.includes('secret') ||\n rule.id.includes('password')\n ) {\n // Skip password/secret rules in test files (dummy credentials are expected)\n // But NOT API key/token rules — those are real leaks even in tests\n const isPasswordRule = rule.id.includes('password') || rule.id.includes('secret') || rule.id === 'security/hardcoded-secret';\n if (isPasswordRule) {\n const TEST_PATH = /(?:^|[\\\\/])(?:tests?|__tests__|spec|__spec__|fixtures?|mocks?|__mocks__|e2e|integration)[\\\\/]/i;\n const TEST_FILE = /\\.(?:test|spec|mock|fixture)\\./i;\n if (TEST_PATH.test(context.filePath) || TEST_FILE.test(context.filePath)) {\n continue;\n }\n }\n const line = match.lineContent;\n const val = match.match;\n // Skip lines that reference environment variables\n if (\n /process\\.env\\b|os\\.environ|os\\.getenv|System\\.getenv|System\\.getProperty|ENV\\[|getenv\\s*\\(/i.test(line)\n ) {\n continue;\n }\n // Skip template/bracket placeholders or dynamic interpolation (e.g. {DB_PASSWORD}, $DB_PASSWORD, ${DB_PASSWORD})\n if (\n /\\{\\s*(?:DB_|db_|PASSWORD|PASS|USER|user|HOST|host|PORT|port|NAME|name|SECRET|TOKEN|KEY|API)/.test(line) ||\n /\\{\\s*[a-zA-Z_][a-zA-Z0-9_]*\\s*\\}/.test(line) || // generic {variable}\n /\\$[a-zA-Z_][a-zA-Z0-9_]*/.test(line) || // generic $variable\n /\\$\\{[a-zA-Z_][a-zA-Z0-9_]*\\}/.test(line) // generic ${variable}\n ) {\n continue;\n }\n // Skip example/placeholder values (excluding high-fidelity test keys like AWS keys containing EXAMPLE)\n if (\n !/^(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}$/i.test(val) &&\n /(?:example|placeholder|your[_-]|changeme|xxxx|TODO|FIXME)/i.test(val)\n ) {\n continue;\n }\n }\n\n // Skip static assignments to innerHTML in rule-based matchers to avoid false positives\n if (rule.id === 'security/xss-innerhtml' || rule.id === 'insecure-innerhtml') {\n const line = match.lineContent;\n if (line.includes('escapeHtml') || line.includes('escapeHTML') || line.includes('DOMPurify') || line.includes('sanitizeHtml')) {\n continue;\n }\n const innerHtmlMatch = line.match(/\\.(?:inner|outer)HTML\\s*\\+?=\\s*(.*)/i);\n if (innerHtmlMatch) {\n let rhs = innerHtmlMatch[1].trim();\n if (rhs.endsWith(';')) {\n rhs = rhs.slice(0, -1).trim();\n }\n const singleQuoted = /^'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'$/;\n const doubleQuoted = /^\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"$/;\n const backtickQuoted = /^`[^`\\\\]*(?:\\\\.[^`\\\\]*)*`$/;\n const isStaticString = \n singleQuoted.test(rhs) || \n doubleQuoted.test(rhs) || \n (backtickQuoted.test(rhs) && !rhs.includes('${'));\n if (isStaticString) {\n continue;\n }\n }\n\n // Skip innerHTML in report/template generator files\n if (\n context.filePath.includes('reporter') ||\n context.filePath.includes('template') ||\n context.filePath.includes('report-generator')\n ) {\n continue;\n }\n\n // Skip innerHTML where a custom escaping function is used\n if (innerHtmlMatch && /\\besc\\s*\\(/.test(line)) {\n continue;\n }\n }\n\n // Skip Math.random() in non-cryptographic/non-security contexts\n if (rule.id === 'SEC-CRYPTO-003' || rule.id === 'security/weak-crypto') {\n const trimmed = match.lineContent.trim();\n const isSafeContext = \n trimmed.includes('id:') ||\n trimmed.includes('id =') ||\n trimmed.includes('key:') ||\n trimmed.includes('key =') ||\n trimmed.includes('reactKey') ||\n trimmed.includes('index') ||\n trimmed.includes('assert') ||\n trimmed.includes('tc.') ||\n /^(?:const|let|var)\\s+\\w*(?:id|key|uuid|idx|index)\\w*\\s*=/i.test(trimmed);\n if (isSafeContext) {\n continue;\n }\n }\n\n // Skip relative imports/requires/includes for path traversal rules to avoid false positives\n if (rule.id === 'security/path-traversal') {\n const line = match.lineContent.trim();\n const isConfigFile = \n context.filePath.endsWith('.config.js') || \n context.filePath.endsWith('.config.ts') || \n context.filePath.includes('vite.config') || \n context.filePath.includes('webpack.') || \n context.filePath.includes('tailwind.');\n\n if (\n line.startsWith('import ') ||\n line.startsWith('import(') ||\n line.startsWith('export ') ||\n line.startsWith('from ') ||\n line.includes('require(') ||\n line.includes('require ') ||\n line.includes('require_once ') ||\n line.includes('include ') ||\n line.includes('include_once ') ||\n isConfigFile\n ) {\n continue;\n }\n\n // Skip static path constants starting points\n if (\n line.includes('__DIR__') ||\n line.includes('__dirname') ||\n line.includes('__filename') ||\n line.includes('__FILE__') ||\n line.includes('import.meta.url')\n ) {\n if (!/(?:req|request|params|query|body|args|input|user|GET|POST|REQUEST)\\b/i.test(line)) {\n continue;\n }\n }\n }\n\n // Skip XXE warnings if the XML parser is safely configured in the file\n if (rule.id === 'security/xxe' || rule.id === 'SEC-XXE-001') {\n if (\n context.content.includes('disallow-doctype-decl') ||\n (context.content.includes('external-general-entities') && context.content.includes('external-parameter-entities')) ||\n context.content.includes('SUPPORT_DTD') ||\n context.content.includes('IS_SUPPORTING_EXTERNAL_ENTITIES')\n ) {\n continue;\n }\n }\n\n // Skip SSRF warnings if the URL is validated in the file\n if (rule.id === 'security/ssrf' || rule.id === 'SEC-SRF-001' || rule.id === 'SEC-SRF-002') {\n if (\n context.content.includes('startsWith') ||\n context.content.includes('validate') ||\n context.content.includes('whitelist') ||\n context.content.includes('trusted')\n ) {\n continue;\n }\n }\n\n const snippet = extractSnippet(context.content, match.line);\n findings.push(\n createFinding({\n ruleId: rule.id,\n scanner: this.type,\n severity: rule.severity,\n confidence: rule.confidence,\n category: rule.category,\n subcategory: rule.subcategory,\n title: rule.name,\n message: rulePattern.message ?? rule.description,\n filePath: context.filePath,\n lineNumber: match.line,\n column: match.column,\n snippet,\n cwe: rule.cwe,\n owasp: rule.owasp,\n fix: rule.fix ? { description: rule.fix.description, suggestion: rule.fix.replacement, references: rule.references ?? [] } : undefined,\n references: rule.references,\n tags: rule.tags,\n }),\n );\n }\n } catch {\n // Invalid regex pattern – skip silently\n }\n }\n }\n\n return findings;\n }\n}\n","import { consola } from 'consola';\nimport type { TaintFlowStep, SourceLocation } from '../types/finding.js';\nimport type { TaintSource, TaintSink, Sanitizer } from '../types/scanner.js';\nimport { getLanguageConfig } from '../languages/registry.js';\nimport type { Tree, Node } from 'web-tree-sitter';\n\n/**\n * Taint Tracker - Data flow analysis\n *\n * Tracks tainted (untrusted) data from sources to sinks.\n * Uses AST traversal when tree-sitter is available for high accuracy,\n * falls back to regex-based heuristics if no AST.\n */\n\nexport interface TaintResult {\n hasTaintedSink: boolean;\n sourceType: string;\n sinkType: string;\n flow: TaintFlowStep[];\n}\n\ninterface TaintedValue {\n id: string;\n sourceType: string;\n originLocation: SourceLocation;\n currentVariable: string;\n propagationPath: TaintFlowStep[];\n sanitized: Set<string>;\n}\n\n/**\n * Analyze a file for taint flow issues\n */\nexport function analyzeTaintFlow(\n content: string,\n filePath: string,\n language: string,\n tree?: Tree | null\n): TaintResult[] {\n const langConfig = getLanguageConfig(language);\n if (!langConfig) return [];\n\n if (tree) {\n return analyzeTaintFlowAST(tree, content, filePath, langConfig.taintSources, langConfig.taintSinks, langConfig.sanitizers);\n } else {\n // Fallback to old regex-based tracker\n return analyzeTaintFlowRegex(content, filePath, langConfig.taintSources, langConfig.taintSinks, langConfig.sanitizers);\n }\n}\n\n// ─── AST-Based Tracker ───────────────────────────────────────────────────────\n\nfunction analyzeTaintFlowAST(\n tree: Tree,\n content: string,\n filePath: string,\n sources: TaintSource[],\n sinks: TaintSink[],\n sanitizers: Sanitizer[]\n): TaintResult[] {\n const results: TaintResult[] = [];\n \n // A map of tainted variable names to their tracking data within the current file\n const taintedVars = new Map<string, TaintedValue>();\n\n // A helper to create a SourceLocation from a SyntaxNode\n const getLocation = (node: Node): SourceLocation => ({\n file: filePath,\n startLine: node.startPosition.row + 1,\n startColumn: node.startPosition.column,\n endLine: node.endPosition.row + 1,\n endColumn: node.endPosition.column,\n snippet: node.text.split('\\n')[0],\n });\n\n // Pre-process sink names for quick lookup\n const sinkNames = sinks.map(s => s.pattern.replace(/\\$TAINTED|\\(|\\)/g, '').replace(/[^a-zA-Z0-9_.]/g, ''));\n const sourceNames = sources.map(s => s.pattern.replace(/\\$TAINTED|\\(|\\)/g, '').replace(/[^a-zA-Z0-9_.]/g, ''));\n\n // First pass: Find sources and track assignments (Simulating control flow simply via tree order)\n function traverse(node: Node) {\n // 1. Variable Declarations (var/let/const x = y)\n if (node.type === 'variable_declarator') {\n const idNode = node.childForFieldName('name') || node.children.find(n => n.type === 'identifier');\n const valueNode = node.childForFieldName('value');\n \n if (idNode && valueNode) {\n checkAssignment(idNode, valueNode);\n }\n }\n\n // 2. Assignments (x = y)\n if (node.type === 'assignment_expression') {\n const leftNode = node.childForFieldName('left');\n const rightNode = node.childForFieldName('right');\n \n if (leftNode && rightNode) {\n checkAssignment(leftNode, rightNode);\n }\n }\n\n // 3. Sinks (eval, db.query, etc.)\n if (node.type === 'call_expression') {\n const funcNode = node.childForFieldName('function');\n const argsNode = node.childForFieldName('arguments');\n\n if (funcNode && argsNode) {\n const funcName = funcNode.text;\n \n // Is this function a known sink?\n const matchedSink = sinks.find(s => {\n const sName = s.pattern.replace(/\\$TAINTED|\\(|\\)/g, '').replace(/[^a-zA-Z0-9_.]/g, '');\n return funcName === sName || funcName.endsWith(`.${sName}`);\n });\n\n if (matchedSink) {\n // Check if any argument is tainted\n for (let i = 0; i < argsNode.childCount; i++) {\n const arg = argsNode.child(i);\n if (!arg || arg.type === '(' || arg.type === ')' || arg.type === ',') continue;\n\n const taintedArg = findTaintedVarInExpression(arg, taintedVars);\n if (taintedArg) {\n // Found a vulnerable flow!\n results.push({\n hasTaintedSink: true,\n sourceType: taintedArg.sourceType,\n sinkType: matchedSink.type,\n flow: [\n ...taintedArg.propagationPath,\n {\n location: getLocation(node),\n label: `Sink: ${matchedSink.description} (${matchedSink.type})`,\n kind: 'sink'\n }\n ]\n });\n }\n }\n }\n }\n }\n\n for (let i = 0; i < node.childCount; i++) {\n traverse(node.child(i)!);\n }\n }\n\n function checkAssignment(leftNode: Node, rightNode: Node) {\n const varName = leftNode.text;\n const rightText = rightNode.text;\n\n // Is the right side directly a source? (e.g., req.query)\n const matchedSource = sources.find(s => {\n const sName = s.pattern.replace(/\\$TAINTED|\\(|\\)/g, '').replace(/[^a-zA-Z0-9_.]/g, '');\n return rightText.includes(sName);\n });\n\n if (matchedSource) {\n taintedVars.set(varName, {\n id: `taint_${varName}`,\n sourceType: matchedSource.type,\n originLocation: getLocation(rightNode),\n currentVariable: varName,\n sanitized: new Set(),\n propagationPath: [{\n location: getLocation(rightNode),\n label: `Source: ${matchedSource.description}`,\n kind: 'source'\n }]\n });\n return;\n }\n\n // Is the right side a previously tainted variable? (Propagation)\n const taintedSource = findTaintedVarInExpression(rightNode, taintedVars);\n if (taintedSource) {\n // Check for sanitizers\n const isSanitized = sanitizers.some(s => {\n const sName = s.pattern.replace(/\\$TAINTED|\\(|\\)/g, '').replace(/[^a-zA-Z0-9_.]/g, '');\n return rightText.includes(sName);\n });\n\n if (!isSanitized) {\n // Propagate\n taintedVars.set(varName, {\n ...taintedSource,\n currentVariable: varName,\n propagationPath: [\n ...taintedSource.propagationPath,\n {\n location: getLocation(leftNode),\n label: `Propagated to ${varName}`,\n kind: 'propagator'\n }\n ]\n });\n }\n }\n }\n\n function findTaintedVarInExpression(node: Node, map: Map<string, TaintedValue>): TaintedValue | null {\n if (node.type === 'identifier' && map.has(node.text)) {\n return map.get(node.text)!;\n }\n // Deep check for binary expressions (e.g., \"SELECT * FROM users WHERE id = '\" + req.query.id + \"'\")\n if (node.type === 'binary_expression' || node.type === 'template_string') {\n // Just check if any identifier in this subtree is tainted\n let found: TaintedValue | null = null;\n function walk(n: Node) {\n if (found) return;\n if (n.type === 'identifier' && map.has(n.text)) {\n found = map.get(n.text)!;\n }\n for (let i = 0; i < n.childCount; i++) walk(n.child(i)!);\n }\n walk(node);\n return found;\n }\n return null;\n }\n\n traverse(tree.rootNode);\n return results;\n}\n\n// ─── Regex-Based Tracker (Fallback) ──────────────────────────────────────────\n\nfunction analyzeTaintFlowRegex(\n content: string,\n filePath: string,\n sources: TaintSource[],\n sinks: TaintSink[],\n sanitizers: Sanitizer[]\n): TaintResult[] {\n const results: TaintResult[] = [];\n const lines = content.split('\\n');\n const taintedVars = findTaintSourcesRegex(lines, sources, filePath);\n propagateTaintRegex(lines, taintedVars, filePath);\n \n for (const tainted of taintedVars) {\n const sinkHits = findTaintSinksRegex(lines, tainted, sinks, sanitizers, filePath);\n results.push(...sinkHits);\n }\n return results;\n}\n\nfunction findTaintSourcesRegex(lines: string[], sources: TaintSource[], filePath: string): TaintedValue[] {\n const tainted: TaintedValue[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n if (!line || line.startsWith('//') || line.startsWith('#')) continue;\n \n for (const source of sources) {\n if (line.includes(source.pattern.replace('$TAINTED', '').replace('()', ''))) {\n const assignMatch = line.match(/(?:const|let|var|final|auto)?\\s*(\\w+)\\s*=.*$/);\n const varName = assignMatch ? assignMatch[1] : `__tainted_${i}`;\n tainted.push({\n id: `taint_${i}_${varName}`,\n sourceType: source.type,\n originLocation: { file: filePath, startLine: i + 1, startColumn: 0, endLine: i + 1, endColumn: line.length, snippet: line },\n currentVariable: varName,\n propagationPath: [{ location: { file: filePath, startLine: i + 1, startColumn: 0, endLine: i + 1, endColumn: line.length, snippet: line }, label: `Source: ${source.description}`, kind: 'source' }],\n sanitized: new Set(),\n });\n }\n }\n }\n return tainted;\n}\n\nfunction propagateTaintRegex(lines: string[], taintedVars: TaintedValue[], filePath: string): void {\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n if (!line) continue;\n for (const tainted of taintedVars) {\n if (line.includes(tainted.currentVariable)) {\n const assignMatch = line.match(/(?:const|let|var|final|auto)?\\s*(\\w+)\\s*=.*$/);\n if (assignMatch && assignMatch[1] !== tainted.currentVariable) {\n const newVar = assignMatch[1];\n tainted.propagationPath.push({ location: { file: filePath, startLine: i + 1, startColumn: 0, endLine: i + 1, endColumn: line.length, snippet: line }, label: `Propagated: ${tainted.currentVariable} → ${newVar}`, kind: 'propagator' });\n tainted.currentVariable = newVar;\n }\n }\n }\n }\n}\n\nfunction findTaintSinksRegex(lines: string[], tainted: TaintedValue, sinks: TaintSink[], sanitizers: Sanitizer[], filePath: string): TaintResult[] {\n const results: TaintResult[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n if (!line || line.startsWith('//') || line.startsWith('#')) continue;\n \n // Check sanitizers\n for (const sanitizer of sanitizers) {\n if (line.includes(sanitizer.pattern.replace('$TAINTED', tainted.currentVariable))) {\n for (const c of sanitizer.cleanses) {\n tainted.sanitized.add(c);\n }\n }\n }\n \n // Check sinks\n if (line.includes(tainted.currentVariable)) {\n for (const sink of sinks) {\n if (tainted.sanitized.has(sink.type)) continue;\n const sinkPattern = sink.pattern.replace('$TAINTED', '');\n if (line.includes(sinkPattern)) {\n results.push({\n hasTaintedSink: true,\n sourceType: tainted.sourceType,\n sinkType: sink.type,\n flow: [...tainted.propagationPath, { location: { file: filePath, startLine: i + 1, startColumn: 0, endLine: i + 1, endColumn: line.length, snippet: line }, label: `Sink: ${sink.description}`, kind: 'sink' }],\n });\n }\n }\n }\n }\n return results;\n}\n","// ─── Injection Analyzer ────────────────────────────────────────────────────\n// Detects injection vulnerabilities (SQL, Command, LDAP, SSTI) using regex patterns\n\nimport type { Finding } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport { createFinding, extractSnippet, matchPattern, isInCommentOrString, isPatternDefinitionContext, isInSafeASTContext } from '../../base-scanner.js';\n\n// ─── SQL Injection Detection ───────────────────────────────────────────────\n\n/** Patterns that indicate SQL injection via string concatenation */\nconst SQL_CONCAT_PATTERNS: Array<{ regex: RegExp; message: string }> = [\n {\n // query(\"SELECT * FROM users WHERE id = \" + userId)\n regex: /(?:query|execute|exec|raw|prepare)\\s*\\(\\s*[\"'`](?:SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|UNION|EXEC)\\b[^\"'`]*[\"'`]\\s*\\+/i,\n message: 'SQL query built with string concatenation – vulnerable to SQL injection',\n },\n {\n // \"SELECT * FROM \" + table + \" WHERE id = \" + id\n regex: /[\"'`](?:SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|CREATE)\\s+[\\w\\s*,]+(?:FROM|INTO|SET|TABLE)\\s+[\"'`]\\s*\\+\\s*\\w+/i,\n message: 'SQL query built with string concatenation – use parameterized queries',\n },\n {\n // `SELECT * FROM users WHERE id = ${userId}` (template literal)\n regex: /(?:query|execute|exec|raw)\\s*\\(\\s*`[^`]*(?:SELECT|INSERT|UPDATE|DELETE|DROP)\\b[^`]*\\$\\{[^}]+\\}[^`]*`/i,\n message: 'SQL query with template literal interpolation – vulnerable to SQL injection',\n },\n {\n // query(`...${req.body.id}...`)\n regex: /(?:query|execute|exec|raw)\\s*\\(\\s*`[^`]*\\$\\{\\s*(?:req|request|params|query|body|args|input|user)\\b[^}]*\\}[^`]*`/i,\n message: 'SQL query interpolates user-controlled input directly',\n },\n {\n // f\"SELECT * FROM users WHERE name = '{name}'\" (Python f-string)\n regex: /f[\"'](?:SELECT|INSERT|UPDATE|DELETE|DROP)\\s+[^\"']*\\{[^}]+\\}[^\"']*[\"']/i,\n message: 'Python f-string used in SQL query – vulnerable to SQL injection',\n },\n {\n // \"SELECT ... WHERE id = %s\" % user_id (Python % formatting)\n regex: /[\"'](?:SELECT|INSERT|UPDATE|DELETE|DROP)\\b[^\"']*%s[^\"']*[\"']\\s*%/i,\n message: 'Python %-format used in SQL query – use parameterized queries instead',\n },\n {\n // \"SELECT ... WHERE id = #{id}\" (Ruby interpolation)\n regex: /[\"'](?:SELECT|INSERT|UPDATE|DELETE|DROP)\\b[^\"']*#\\{[^}]+\\}[^\"']*[\"']/i,\n message: 'String interpolation in SQL query – vulnerable to SQL injection',\n },\n {\n // .where(\"name = '\" + params[:name] + \"'\")\n regex: /\\.where\\s*\\(\\s*[\"'][^\"']*[\"']\\s*\\+/i,\n message: 'ORM .where() with string concatenation – use parameterized form',\n },\n];\n\n/** Patterns for SQL injection in various ORMs/frameworks */\nconst SQL_ORM_PATTERNS: Array<{ regex: RegExp; message: string }> = [\n {\n // sequelize.query(\"SELECT ...\" + input)\n regex: /sequelize\\.query\\s*\\(\\s*[\"'`][^\"'`]*[\"'`]\\s*\\+/i,\n message: 'Sequelize raw query with string concatenation',\n },\n {\n // knex.raw(\"SELECT ...\" + input)\n regex: /knex\\.raw\\s*\\(\\s*[\"'`][^\"'`]*[\"'`]\\s*\\+/i,\n message: 'Knex raw query with string concatenation',\n },\n {\n // connection.query(\"...\" + userInput)\n regex: /(?:connection|conn|db|client|pool)\\.query\\s*\\(\\s*[\"'`][^\"'`]*[\"'`]\\s*\\+/i,\n message: 'Database query with string concatenation',\n },\n {\n // cursor.execute(\"...\" + var) (Python)\n regex: /cursor\\.execute\\s*\\(\\s*[\"'][^\"']*[\"']\\s*(?:\\+|%)/i,\n message: 'Cursor execute with string concatenation or format – use parameterized queries',\n },\n {\n // PHP/Laravel DB raw queries with string concatenation using dot (.)\n regex: /(?:DB\\s*::\\s*(?:select|statement|insert|update|delete|raw)|whereRaw|havingRaw|orderByRaw)\\s*\\(\\s*[\"'](?:SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|UNION)\\b[^\"']*[\"']\\s*\\.\\s*\\$\\w+/i,\n message: 'Laravel raw SQL query built with string concatenation – vulnerable to SQL injection',\n },\n];\n\n// ─── Command Injection Detection ───────────────────────────────────────────\n\nconst COMMAND_INJECTION_PATTERNS: Array<{ regex: RegExp; message: string }> = [\n {\n // exec(\"rm -rf \" + userInput)\n regex: /(?:child_process\\s*\\.\\s*)?exec\\s*\\(\\s*(?:[\"'`][^\"'`]*[\"'`]\\s*\\+\\s*\\w+|\\w+\\s*\\+\\s*[\"'`])/i,\n message: 'Command execution with string concatenation – vulnerable to command injection',\n },\n {\n // exec(`command ${userInput}`)\n regex: /(?:child_process\\s*\\.\\s*)?exec\\s*\\(\\s*`[^`]*\\$\\{[^}]+\\}[^`]*`/i,\n message: 'Command execution with template literal interpolation',\n },\n {\n // execSync(userInput)\n regex: /execSync\\s*\\(\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'execSync called with user-controlled input',\n },\n {\n // os.system(user_input) or os.popen(...)\n regex: /os\\.(?:system|popen)\\s*\\(\\s*(?:[\"'][^\"']*[\"']\\s*(?:\\+|%|\\.\\s*format)|f[\"'])/i,\n message: 'os.system/popen with dynamic input – vulnerable to command injection',\n },\n {\n // subprocess.call(cmd, shell=True)\n regex: /subprocess\\.(?:call|run|Popen|check_output)\\s*\\([^)]*shell\\s*=\\s*True/i,\n message: 'subprocess with shell=True – vulnerable to command injection',\n },\n {\n // spawn with user input in arguments \n regex: /spawn\\s*\\(\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'spawn called with user-controlled input',\n },\n {\n // eval(userInput)\n regex: /\\beval\\s*\\(\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'eval() called with user-controlled input – code injection risk',\n },\n {\n // new Function(userInput)\n regex: /new\\s+Function\\s*\\(\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'new Function() with user input – code injection risk',\n },\n {\n // Runtime.getRuntime().exec(input) (Java)\n regex: /Runtime\\s*\\.\\s*getRuntime\\s*\\(\\s*\\)\\s*\\.\\s*exec\\s*\\(\\s*\\w+/i,\n message: 'Runtime.exec with potentially user-controlled argument',\n },\n];\n\n// ─── LDAP Injection Detection ──────────────────────────────────────────────\n\nconst LDAP_INJECTION_PATTERNS: Array<{ regex: RegExp; message: string }> = [\n {\n // \"(uid=\" + username + \")\"\n regex: /[\"']\\s*\\(\\s*(?:uid|cn|sn|mail|memberOf|objectClass)\\s*=\\s*[\"']\\s*\\+\\s*\\w+/i,\n message: 'LDAP filter built with string concatenation – vulnerable to LDAP injection',\n },\n {\n // `(uid=${req.body.username})`\n regex: /`\\s*\\([^`]*(?:uid|cn|sn|mail|memberOf)=[^`]*\\$\\{[^}]+\\}[^`]*\\)`/i,\n message: 'LDAP filter with template literal interpolation',\n },\n {\n // ldap.search(\"...\" + input)\n regex: /ldap\\w*\\.(?:search|bind|modify)\\s*\\(\\s*[\"'`][^\"'`]*[\"'`]\\s*\\+/i,\n message: 'LDAP operation with string concatenation',\n },\n];\n\n// ─── Template Injection (SSTI) Detection ───────────────────────────────────\n\nconst TEMPLATE_INJECTION_PATTERNS: Array<{ regex: RegExp; message: string }> = [\n {\n // render_template_string(user_input)\n regex: /render_template_string\\s*\\(\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'render_template_string with user input – SSTI vulnerability',\n },\n {\n // Template(user_input).render()\n regex: /(?:Template|Jinja2?|Environment)\\s*\\(\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'Template engine initialized with user-controlled input',\n },\n {\n // nunjucks.renderString(userInput)\n regex: /(?:nunjucks|swig|pug|ejs|handlebars|mustache)\\s*\\.(?:render|renderString|compile)\\s*\\(\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'Template engine renders user-controlled input – SSTI risk',\n },\n {\n // res.render with user-controlled template name\n regex: /res\\.render\\s*\\(\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'res.render with user-controlled template name',\n },\n {\n // Jinja2 Environment with user input\n regex: /Environment\\s*\\([^)]*\\)\\s*\\.from_string\\s*\\(\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'Jinja2 Environment.from_string with user input – SSTI',\n },\n];\n\n// ─── Main Analyzer Function ────────────────────────────────────────────────\n\n/**\n * Analyze source code for injection vulnerabilities.\n */\nexport function analyzeInjection(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath } = context;\n\n // Skip empty files or very small files\n if (content.length < 10) return findings;\n\n // Run SQL injection detection\n findings.push(...detectPatterns(context, SQL_CONCAT_PATTERNS, {\n ruleId: 'SEC-INJ-001',\n category: 'injection',\n subcategory: 'sql-injection',\n title: 'SQL Injection',\n severity: 'critical',\n confidence: 'high',\n cwe: ['CWE-89'],\n owasp: ['A03:2021'],\n tags: ['sql', 'injection', 'owasp-top10'],\n fix: {\n description: 'Use parameterized queries or prepared statements instead of string concatenation.',\n references: ['https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html'],\n },\n }));\n\n findings.push(...detectPatterns(context, SQL_ORM_PATTERNS, {\n ruleId: 'SEC-INJ-002',\n category: 'injection',\n subcategory: 'sql-injection',\n title: 'SQL Injection via ORM',\n severity: 'critical',\n confidence: 'medium',\n cwe: ['CWE-89'],\n owasp: ['A03:2021'],\n tags: ['sql', 'injection', 'orm'],\n fix: {\n description: 'Use the ORM\\'s parameterized query methods instead of raw query with concatenation.',\n references: ['https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html'],\n },\n }));\n\n // Run command injection detection\n findings.push(...detectPatterns(context, COMMAND_INJECTION_PATTERNS, {\n ruleId: 'SEC-INJ-003',\n category: 'injection',\n subcategory: 'command-injection',\n title: 'Command Injection',\n severity: 'critical',\n confidence: 'high',\n cwe: ['CWE-78'],\n owasp: ['A03:2021'],\n tags: ['command', 'injection', 'rce'],\n fix: {\n description: 'Use parameterized command execution (e.g., execFile, spawn with array args) and validate/sanitize user input.',\n references: ['https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html'],\n },\n }));\n\n // Run LDAP injection detection\n findings.push(...detectPatterns(context, LDAP_INJECTION_PATTERNS, {\n ruleId: 'SEC-INJ-004',\n category: 'injection',\n subcategory: 'ldap-injection',\n title: 'LDAP Injection',\n severity: 'high',\n confidence: 'medium',\n cwe: ['CWE-90'],\n owasp: ['A03:2021'],\n tags: ['ldap', 'injection'],\n fix: {\n description: 'Escape special LDAP characters in user input or use parameterized LDAP filters.',\n references: ['https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html'],\n },\n }));\n\n // Run template injection detection\n findings.push(...detectPatterns(context, TEMPLATE_INJECTION_PATTERNS, {\n ruleId: 'SEC-INJ-005',\n category: 'injection',\n subcategory: 'template-injection',\n title: 'Server-Side Template Injection (SSTI)',\n severity: 'critical',\n confidence: 'high',\n cwe: ['CWE-1336'],\n owasp: ['A03:2021'],\n tags: ['ssti', 'template', 'injection', 'rce'],\n fix: {\n description: 'Never render user-controlled strings as templates. Use static templates with data binding.',\n references: ['https://portswigger.net/web-security/server-side-template-injection'],\n },\n }));\n\n return findings;\n}\n\n// ─── Internal Helper ───────────────────────────────────────────────────────\n\ninterface PatternMeta {\n ruleId: string;\n category: string;\n subcategory: string;\n title: string;\n severity: 'critical' | 'high' | 'medium' | 'low';\n confidence: 'high' | 'medium' | 'low';\n cwe: string[];\n owasp: string[];\n tags: string[];\n fix: { description: string; references: string[] };\n}\n\nfunction detectPatterns(\n context: ScanFileContext,\n patterns: Array<{ regex: RegExp; message: string }>,\n meta: PatternMeta,\n): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath } = context;\n\n for (const { regex, message } of patterns) {\n const matches = matchPattern(content, regex);\n for (const match of matches) {\n // Skip matches in safe AST contexts (string literals, comments, imports, type annotations)\n if (context.tree && isInSafeASTContext(context.tree, match.line, match.column)) continue;\n\n // Skip matches inside comments or pattern/rule definition contexts\n if (isInCommentOrString(match.lineContent, match.column)) continue;\n if (isPatternDefinitionContext(match.lineContent, match.column)) continue;\n\n const snippet = extractSnippet(content, match.line);\n findings.push(\n createFinding({\n ruleId: meta.ruleId,\n scanner: 'security',\n severity: meta.severity,\n confidence: meta.confidence,\n category: meta.category,\n subcategory: meta.subcategory,\n title: meta.title,\n message,\n filePath,\n lineNumber: match.line,\n column: match.column,\n snippet,\n cwe: meta.cwe,\n owasp: meta.owasp,\n fix: meta.fix,\n tags: meta.tags,\n }),\n );\n }\n }\n\n return findings;\n}\n","// ─── XSS Analyzer ──────────────────────────────────────────────────────────\n// Detects DOM-based, reflected, and stored XSS patterns\n\nimport type { Finding, Severity, Confidence } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport { createFinding, extractSnippet, matchPattern, isPatternDefinitionContext, isInSafeASTContext } from '../../base-scanner.js';\n\n// ─── Pattern Definitions ───────────────────────────────────────────────────\n\ninterface XSSPattern {\n regex: RegExp;\n message: string;\n severity: Severity;\n confidence: Confidence;\n subcategory: string;\n cwe: string[];\n}\n\nconst XSS_PATTERNS: XSSPattern[] = [\n // ── innerHTML assignments ──\n {\n regex: /\\.innerHTML\\s*=\\s*(?!['\"`]\\s*['\"`])\\S/i,\n message: 'Direct innerHTML assignment – may allow XSS if input is not sanitized',\n severity: 'high',\n confidence: 'high',\n subcategory: 'dom-xss',\n cwe: ['CWE-79'],\n },\n {\n regex: /\\.innerHTML\\s*=\\s*(?:req|request|params|query|body|args|input|user|data)\\b/i,\n message: 'innerHTML set to user-controlled value – high risk XSS',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'dom-xss',\n cwe: ['CWE-79'],\n },\n {\n regex: /\\.innerHTML\\s*\\+=\\s*\\S/i,\n message: 'innerHTML concatenation – may allow XSS if input is not sanitized',\n severity: 'high',\n confidence: 'high',\n subcategory: 'dom-xss',\n cwe: ['CWE-79'],\n },\n {\n regex: /\\.outerHTML\\s*=\\s*(?!['\"`]\\s*['\"`])\\S/i,\n message: 'Direct outerHTML assignment – may allow XSS',\n severity: 'high',\n confidence: 'high',\n subcategory: 'dom-xss',\n cwe: ['CWE-79'],\n },\n\n // ── document.write ──\n {\n regex: /document\\.write(?:ln)?\\s*\\(/i,\n message: 'document.write() usage – can introduce XSS vulnerabilities',\n severity: 'high',\n confidence: 'high',\n subcategory: 'dom-xss',\n cwe: ['CWE-79'],\n },\n\n // ── dangerouslySetInnerHTML (React) ──\n {\n regex: /dangerouslySetInnerHTML\\s*=\\s*\\{/i,\n message: 'dangerouslySetInnerHTML in React component – ensure input is sanitized',\n severity: 'medium',\n confidence: 'high',\n subcategory: 'react-xss',\n cwe: ['CWE-79'],\n },\n {\n regex: /dangerouslySetInnerHTML\\s*=\\s*\\{\\s*\\{\\s*__html\\s*:\\s*(?:req|request|params|query|body|args|input|user|data|props)\\b/i,\n message: 'dangerouslySetInnerHTML with user-controlled data – XSS risk',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'react-xss',\n cwe: ['CWE-79'],\n },\n\n // ── Unescaped output in templates ──\n {\n // Jinja2 / Twig: {{ variable | safe }} or {% autoescape false %}\n regex: /\\{\\{[^}]*\\|\\s*safe\\s*\\}\\}/i,\n message: 'Template output marked as safe/unescaped – XSS risk if user-controlled',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'template-xss',\n cwe: ['CWE-79'],\n },\n {\n // EJS: <%- variable %> (unescaped output)\n regex: /<%[-=]\\s*(?:req|request|params|query|body|args|input|user|data)\\b[^%]*%>/i,\n message: 'Unescaped EJS output with user-controlled data',\n severity: 'high',\n confidence: 'high',\n subcategory: 'template-xss',\n cwe: ['CWE-79'],\n },\n {\n // {!! $variable !!} (Laravel Blade unescaped)\n regex: /\\{!!\\s*\\$\\w+\\s*!!\\}/i,\n message: 'Unescaped Blade output ({!! !!}) – XSS risk if user-controlled',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'template-xss',\n cwe: ['CWE-79'],\n },\n {\n // Handlebars triple-stash {{{ variable }}}\n regex: /\\{\\{\\{\\s*\\w+[^}]*\\}\\}\\}/i,\n message: 'Handlebars triple-stash ({{{ }}}) outputs unescaped HTML – XSS risk',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'template-xss',\n cwe: ['CWE-79'],\n },\n {\n // {% autoescape false %}\n regex: /\\{%\\s*autoescape\\s+(?:false|off)\\s*%\\}/i,\n message: 'Template autoescaping disabled – all output is vulnerable to XSS',\n severity: 'high',\n confidence: 'high',\n subcategory: 'template-xss',\n cwe: ['CWE-79'],\n },\n\n // ── DOM-based XSS patterns ──\n {\n // location.hash / location.search used in DOM operations\n regex: /(?:location\\.(?:hash|search|href)|document\\.(?:URL|referrer|documentURI))\\s*(?:;|\\))/i,\n message: 'DOM source (location/document) accessed – check for XSS if used in DOM sinks',\n severity: 'low',\n confidence: 'low',\n subcategory: 'dom-xss',\n cwe: ['CWE-79'],\n },\n {\n // element.insertAdjacentHTML\n regex: /\\.insertAdjacentHTML\\s*\\(\\s*['\"][^'\"]*['\"]\\s*,\\s*(?!['\"`]\\s*['\"`])\\S/i,\n message: 'insertAdjacentHTML with dynamic content – possible XSS',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'dom-xss',\n cwe: ['CWE-79'],\n },\n {\n // jQuery html() with dynamic content\n regex: /\\$\\s*\\([^)]*\\)\\s*\\.html\\s*\\(\\s*(?!['\"`]\\s*['\"`]|['\"`]<)(?:\\w|\\$)/i,\n message: 'jQuery .html() with dynamic content – XSS risk',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'dom-xss',\n cwe: ['CWE-79'],\n },\n {\n // jQuery append/prepend/after/before with user data\n regex: /\\$\\s*\\([^)]*\\)\\s*\\.(?:append|prepend|after|before)\\s*\\(\\s*(?:req|request|params|query|body|args|input|user|data)\\b/i,\n message: 'jQuery DOM insertion with user-controlled data – XSS risk',\n severity: 'high',\n confidence: 'high',\n subcategory: 'dom-xss',\n cwe: ['CWE-79'],\n },\n\n // ── Response header injection / reflected ──\n {\n // res.send(req.query.xxx) or res.send(req.body.xxx)\n regex: /res\\.(?:send|write|end)\\s*\\(\\s*(?:req|request)\\s*\\.\\s*(?:query|body|params)\\b/i,\n message: 'User input sent directly in HTTP response – reflected XSS risk',\n severity: 'high',\n confidence: 'high',\n subcategory: 'reflected-xss',\n cwe: ['CWE-79'],\n },\n {\n // Response.Write(Request.QueryString)\n regex: /Response\\.Write\\s*\\(\\s*Request\\.(?:QueryString|Form|Params)/i,\n message: 'ASP.NET Response.Write with request data – reflected XSS',\n severity: 'high',\n confidence: 'high',\n subcategory: 'reflected-xss',\n cwe: ['CWE-79'],\n },\n {\n // res.send/write with template literal containing HTML and interpolation\n regex: /res\\.(?:send|write|end)\\s*\\(\\s*`[^`]*<[a-zA-Z]+[^>]*>[^`]*\\$\\{[^}]+\\}[^`]*`\\s*\\)/i,\n message: 'Dynamic HTML template literal sent directly in HTTP response – reflected XSS risk',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'reflected-xss',\n cwe: ['CWE-79'],\n },\n {\n // res.send/write with string concatenation containing HTML\n regex: /res\\.(?:send|write|end)\\s*\\(\\s*(?:['\"][^'\"]*<[a-zA-Z]+[^>]*>[^'\"]*['\"]\\s*\\+\\s*[^)]+|[^,)]+\\s*\\+\\s*['\"][^'\"]*<[a-zA-Z]+[^>]*>[^'\"]*['\"])/i,\n message: 'HTML string concatenation sent directly in HTTP response – reflected XSS risk',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'reflected-xss',\n cwe: ['CWE-79'],\n },\n {\n // Flask/Python HTML response return with string formatting %\n regex: /return\\s+['\"][^'\"]*<[a-zA-Z]+[^>]*>[^'\"]*['\"]\\s*%\\s*[^;]+/i,\n message: 'Python string formatting with % used to return HTML response – reflected XSS risk',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'reflected-xss',\n cwe: ['CWE-79'],\n },\n {\n // Flask/Python HTML response return with f-strings\n regex: /return\\s+f['\"][^'\"]*<[a-zA-Z]+[^>]*>[^'\"]*\\{[^}]+\\}[^'\"]*['\"]/i,\n message: 'Python f-string used to return HTML response – reflected XSS risk',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'reflected-xss',\n cwe: ['CWE-79'],\n },\n {\n // Flask/Python HTML response return with .format()\n regex: /return\\s+['\"][^'\"]*<[a-zA-Z]+[^>]*>[^'\"]*['\"]\\.format\\s*\\(/i,\n message: 'Python .format() used to return HTML response – reflected XSS risk',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'reflected-xss',\n cwe: ['CWE-79'],\n },\n {\n // Django mark_safe XSS on non-literals\n regex: /mark_safe\\s*\\(\\s*(?!(?:['\"`][^'\"`]*['\"`])\\s*\\))\\S/i,\n message: 'mark_safe called with dynamic content or variable – reflected XSS risk',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'reflected-xss',\n cwe: ['CWE-79'],\n },\n];\n\n// ─── Main Analyzer Function ────────────────────────────────────────────────\n\n/**\n * Analyze source code for Cross-Site Scripting (XSS) vulnerabilities.\n */\nexport function analyzeXSS(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath } = context;\n\n if (content.length < 10) return findings;\n\n for (const pattern of XSS_PATTERNS) {\n const matches = matchPattern(content, pattern.regex);\n for (const match of matches) {\n // Skip matches in safe AST contexts (string literals, comments, imports, type annotations)\n if (context.tree && isInSafeASTContext(context.tree, match.line, match.column)) continue;\n\n // Skip matches that appear in comments\n const trimmed = match.lineContent.trimStart();\n if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('#') || trimmed.startsWith('/*')) {\n continue;\n }\n\n // Skip matches inside pattern/rule definition contexts\n if (isPatternDefinitionContext(match.lineContent, match.column)) continue;\n\n // Skip if the line contains a known sanitization/escaping function to avoid false positives\n if (trimmed.includes('escapeHtml') || trimmed.includes('escapeHTML') || trimmed.includes('DOMPurify') || trimmed.includes('sanitizeHtml')) {\n continue;\n }\n\n // Skip static assignments to innerHTML / outerHTML to avoid false positives\n if (pattern.subcategory === 'dom-xss' && (pattern.regex.source.includes('innerHTML') || pattern.regex.source.includes('outerHTML'))) {\n const innerHtmlMatch = match.lineContent.match(/\\.(?:inner|outer)HTML\\s*\\+?=\\s*(.*)/i);\n if (innerHtmlMatch) {\n let rhs = innerHtmlMatch[1].trim();\n if (rhs.endsWith(';')) {\n rhs = rhs.slice(0, -1).trim();\n }\n const singleQuoted = /^'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'$/;\n const doubleQuoted = /^\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"$/;\n const backtickQuoted = /^`[^`\\\\]*(?:\\\\.[^`\\\\]*)*`$/;\n const isStaticString = \n singleQuoted.test(rhs) || \n doubleQuoted.test(rhs) || \n (backtickQuoted.test(rhs) && !rhs.includes('${'));\n if (isStaticString) {\n continue;\n }\n }\n\n // Skip innerHTML in report/template generator files – these generate HTML output\n // for file-based reports, not user-facing DOM manipulation\n if (\n filePath.includes('reporter') ||\n filePath.includes('template') ||\n filePath.includes('report-generator')\n ) {\n continue;\n }\n\n // Skip innerHTML where a custom escaping function (esc(), escapeHtml()) is applied to interpolated values\n if (innerHtmlMatch && /\\besc\\s*\\(/.test(match.lineContent)) {\n continue;\n }\n }\n\n // Skip low severity DOM source warnings on safe/common usages\n if (pattern.subcategory === 'dom-xss' && pattern.severity === 'low') {\n const hasSafeWords = \n trimmed.includes('URLSearchParams') ||\n trimmed.includes('writeText') ||\n trimmed.includes('clipboard') ||\n trimmed.includes('console.') ||\n trimmed.includes('sessionStorage') ||\n trimmed.includes('localStorage') ||\n trimmed.includes('siteUrl') ||\n trimmed.includes('siteImage') ||\n trimmed.includes('siteDescription') ||\n trimmed.includes('siteTitle') ||\n trimmed.includes('encodeURIComponent') ||\n trimmed.includes('decodeURIComponent') ||\n trimmed.includes('location.href =') ||\n trimmed.includes('location.href=') ||\n trimmed.includes('location.replace') ||\n trimmed.includes('location.assign') ||\n trimmed.includes('return ') ||\n trimmed.includes('window.location.href =') ||\n trimmed.includes('window.location.href=') ||\n trimmed.endsWith(']);') ||\n trimmed.endsWith('],') ||\n /^(?:const|let|var)\\s+\\w+\\s*=\\s*(?:url\\s*\\|\\|\\s*)?window\\.location\\.(?:href|origin)/.test(trimmed);\n\n if (hasSafeWords) {\n continue;\n }\n }\n\n const snippet = extractSnippet(content, match.line);\n findings.push(\n createFinding({\n ruleId: 'SEC-XSS-001',\n scanner: 'security',\n severity: pattern.severity,\n confidence: pattern.confidence,\n category: 'xss',\n subcategory: pattern.subcategory,\n title: 'Cross-Site Scripting (XSS)',\n message: pattern.message,\n filePath,\n lineNumber: match.line,\n column: match.column,\n snippet,\n cwe: pattern.cwe,\n owasp: ['A03:2021'],\n fix: {\n description: 'Sanitize and escape all user input before rendering in HTML. Use context-aware encoding.',\n references: [\n 'https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html',\n 'https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html',\n ],\n },\n tags: ['xss', 'owasp-top10'],\n }),\n );\n }\n }\n\n return findings;\n}\n","// ─── Secrets Analyzer ──────────────────────────────────────────────────────\n// Detects hardcoded secrets: passwords, API keys, private keys, high-entropy strings\n\nimport type { Finding, Severity, Confidence } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport { createFinding, extractSnippet, matchPattern } from '../../base-scanner.js';\n\n// ─── Pattern Definitions ───────────────────────────────────────────────────\n\ninterface SecretPattern {\n id: string;\n regex: RegExp;\n message: string;\n severity: Severity;\n confidence: Confidence;\n subcategory: string;\n service?: string;\n}\n\n// ── Hardcoded password patterns ──\nconst PASSWORD_PATTERNS: SecretPattern[] = [\n {\n id: 'SEC-SEC-001',\n regex: /(?:password|passwd|pwd|pass|secret|credential)\\s*[:=]\\s*[\"'][^\"']{4,}[\"']/i,\n message: 'Hardcoded password or secret detected in source code',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'hardcoded-password',\n },\n {\n id: 'SEC-SEC-001',\n regex: /(?:password|passwd|pwd|pass)\\s*=\\s*[\"'][^\"']{4,}[\"']/i,\n message: 'Hardcoded password assignment detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'hardcoded-password',\n },\n {\n id: 'SEC-SEC-001',\n regex: /(?:db_password|database_password|DB_PASS|mysql_pwd|pg_password)\\s*[:=]\\s*[\"'][^\"']{4,}[\"']/i,\n message: 'Hardcoded database password detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'hardcoded-password',\n },\n {\n id: 'SEC-SEC-002',\n regex: /(?:admin_password|root_password|master_password|default_password)\\s*[:=]\\s*[\"'][^\"']+[\"']/i,\n message: 'Hardcoded admin/root password detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'hardcoded-password',\n },\n];\n\n// ── API key and token patterns for 20+ services ──\nconst API_KEY_PATTERNS: SecretPattern[] = [\n // AWS\n {\n id: 'SEC-SEC-010',\n regex: /(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}/,\n message: 'AWS Access Key ID detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'AWS',\n },\n {\n id: 'SEC-SEC-010',\n regex: /(?:aws_secret_access_key|aws_secret_key)\\s*[:=]\\s*[\"'][A-Za-z0-9/+=]{40}[\"']/i,\n message: 'AWS Secret Access Key detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'AWS',\n },\n // GitHub\n {\n id: 'SEC-SEC-011',\n regex: /(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,}/,\n message: 'GitHub personal access token detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'GitHub',\n },\n {\n id: 'SEC-SEC-011',\n regex: /github_token\\s*[:=]\\s*[\"'][^\"']{20,}[\"']/i,\n message: 'GitHub token detected in source code',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'GitHub',\n },\n // Slack\n {\n id: 'SEC-SEC-012',\n regex: /xox[bpors]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*/,\n message: 'Slack token detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Slack',\n },\n {\n id: 'SEC-SEC-012',\n regex: /https:\\/\\/hooks\\.slack\\.com\\/services\\/T[A-Z0-9]{8,}\\/B[A-Z0-9]{8,}\\/[A-Za-z0-9]{24}/,\n message: 'Slack webhook URL detected',\n severity: 'high',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Slack',\n },\n // Stripe\n {\n id: 'SEC-SEC-013',\n regex: /sk_live_[0-9a-zA-Z]{24,}/,\n message: 'Stripe live secret key detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Stripe',\n },\n {\n id: 'SEC-SEC-013',\n regex: /rk_live_[0-9a-zA-Z]{24,}/,\n message: 'Stripe live restricted key detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Stripe',\n },\n // Google\n {\n id: 'SEC-SEC-014',\n regex: /AIza[0-9A-Za-z\\-_]{35}/,\n message: 'Google API key detected',\n severity: 'high',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Google',\n },\n {\n id: 'SEC-SEC-014',\n regex: /[0-9]+-[0-9A-Za-z_]{32}\\.apps\\.googleusercontent\\.com/,\n message: 'Google OAuth client ID detected',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'api-key',\n service: 'Google',\n },\n // Heroku\n {\n id: 'SEC-SEC-015',\n regex: /(?:heroku_api_key|HEROKU_API_KEY)\\s*[:=]\\s*[\"'][0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}[\"']/i,\n message: 'Heroku API key detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Heroku',\n },\n // Twilio\n {\n id: 'SEC-SEC-016',\n regex: /SK[0-9a-fA-F]{32}/,\n message: 'Twilio API key detected',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'api-key',\n service: 'Twilio',\n },\n // Mailgun\n {\n id: 'SEC-SEC-017',\n regex: /key-[0-9a-zA-Z]{32}/,\n message: 'Mailgun API key detected',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'api-key',\n service: 'Mailgun',\n },\n // SendGrid\n {\n id: 'SEC-SEC-018',\n regex: /SG\\.[0-9A-Za-z\\-_]{22}\\.[0-9A-Za-z\\-_]{43}/,\n message: 'SendGrid API key detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'SendGrid',\n },\n // Square\n {\n id: 'SEC-SEC-019',\n regex: /sq0atp-[0-9A-Za-z\\-_]{22}/,\n message: 'Square access token detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Square',\n },\n // PayPal\n {\n id: 'SEC-SEC-020',\n regex: /access_token\\$production\\$[0-9a-z]{16}\\$[0-9a-f]{32}/,\n message: 'PayPal/Braintree production access token detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'PayPal',\n },\n // Discord\n {\n id: 'SEC-SEC-021',\n regex: /(?:discord_token|DISCORD_TOKEN|discord_bot_token)\\s*[:=]\\s*[\"'][A-Za-z0-9._-]{50,}[\"']/i,\n message: 'Discord bot token detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Discord',\n },\n // NPM\n {\n id: 'SEC-SEC-022',\n regex: /npm_[A-Za-z0-9]{36}/,\n message: 'NPM access token detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'NPM',\n },\n // Databricks\n {\n id: 'SEC-SEC-023',\n regex: /dapi[0-9a-f]{32}/,\n message: 'Databricks API token detected',\n severity: 'high',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Databricks',\n },\n // Firebase\n {\n id: 'SEC-SEC-024',\n regex: /(?:firebase_api_key|FIREBASE_KEY)\\s*[:=]\\s*[\"'][A-Za-z0-9_-]{20,}[\"']/i,\n message: 'Firebase API key detected',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'api-key',\n service: 'Firebase',\n },\n // Azure\n {\n id: 'SEC-SEC-025',\n regex: /(?:azure_storage_key|AZURE_STORAGE_KEY|azure_api_key)\\s*[:=]\\s*[\"'][A-Za-z0-9+/=]{40,}[\"']/i,\n message: 'Azure storage or API key detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Azure',\n },\n // DigitalOcean\n {\n id: 'SEC-SEC-026',\n regex: /dop_v1_[0-9a-f]{64}/,\n message: 'DigitalOcean personal access token detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'DigitalOcean',\n },\n // Shopify\n {\n id: 'SEC-SEC-027',\n regex: /shpat_[0-9a-fA-F]{32}/,\n message: 'Shopify access token detected',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'api-key',\n service: 'Shopify',\n },\n // Generic API key / secret patterns\n {\n id: 'SEC-SEC-030',\n regex: /(?:api_key|apikey|api_secret|API_KEY|API_SECRET)\\s*[:=]\\s*[\"'][A-Za-z0-9_\\-./+=]{16,}[\"']/i,\n message: 'Generic API key/secret detected in source code',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'api-key',\n },\n {\n id: 'SEC-SEC-030',\n regex: /(?:access_token|auth_token|bearer_token|client_secret)\\s*[:=]\\s*[\"'][A-Za-z0-9_\\-./+=]{16,}[\"']/i,\n message: 'Access/auth token or client secret detected',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'api-key',\n },\n];\n\n// ── Private key patterns ──\nconst PRIVATE_KEY_PATTERNS: SecretPattern[] = [\n {\n id: 'SEC-SEC-040',\n regex: /-----BEGIN\\s+(?:RSA\\s+)?PRIVATE\\s+KEY-----/,\n message: 'RSA private key detected in source code',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'private-key',\n },\n {\n id: 'SEC-SEC-040',\n regex: /-----BEGIN\\s+EC\\s+PRIVATE\\s+KEY-----/,\n message: 'EC private key detected in source code',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'private-key',\n },\n {\n id: 'SEC-SEC-040',\n regex: /-----BEGIN\\s+DSA\\s+PRIVATE\\s+KEY-----/,\n message: 'DSA private key detected in source code',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'private-key',\n },\n {\n id: 'SEC-SEC-040',\n regex: /-----BEGIN\\s+OPENSSH\\s+PRIVATE\\s+KEY-----/,\n message: 'OpenSSH private key detected in source code',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'private-key',\n },\n {\n id: 'SEC-SEC-040',\n regex: /-----BEGIN\\s+PGP\\s+PRIVATE\\s+KEY\\s+BLOCK-----/,\n message: 'PGP private key detected in source code',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'private-key',\n },\n {\n id: 'SEC-SEC-041',\n regex: /-----BEGIN\\s+CERTIFICATE-----/,\n message: 'Certificate detected in source code – verify this is intentional',\n severity: 'medium',\n confidence: 'low',\n subcategory: 'private-key',\n },\n];\n\n// ─── Shannon Entropy Calculator ────────────────────────────────────────────\n\n/**\n * Calculate Shannon entropy of a string.\n * High entropy indicates potentially random/secret data.\n */\nfunction shannonEntropy(str: string): number {\n if (str.length === 0) return 0;\n\n const freq: Map<string, number> = new Map();\n for (const ch of str) {\n freq.set(ch, (freq.get(ch) ?? 0) + 1);\n }\n\n let entropy = 0;\n const len = str.length;\n for (const count of freq.values()) {\n const p = count / len;\n if (p > 0) {\n entropy -= p * Math.log2(p);\n }\n }\n return entropy;\n}\n\n// ── Allowed file extensions for entropy scanning ──\nconst SKIP_ENTROPY_EXTENSIONS = new Set([\n '.min.js', '.min.css', '.map', '.lock', '.svg', '.png', '.jpg', '.gif',\n '.woff', '.woff2', '.ttf', '.eot', '.ico', '.pdf',\n]);\n\n// ── Common false positives for entropy detection ──\nconst ENTROPY_FALSE_POSITIVES = new Set([\n 'undefined', 'null', 'true', 'false', 'localhost',\n 'example.com', 'test', 'development', 'production', 'staging',\n 'placeholder', 'changeme', 'your_key_here', 'TODO', 'FIXME',\n 'xxxx', 'yyyy', 'zzzz', 'aaaa', 'bbbb',\n 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n '0123456789', '1234567890',\n]);\n\n// ── Test file/directory detection ──\nconst TEST_PATH_PATTERN = /(?:^|[\\\\/])(?:tests?|__tests__|spec|__spec__|fixtures?|mocks?|__mocks__|e2e|integration|cypress|playwright)[\\\\/]/i;\nconst TEST_FILE_PATTERN = /\\.(?:test|spec|mock|fixture|e2e|cy)\\./i;\nconst TEST_FILE_NAMES = /(?:^|[\\\\/])(?:conftest\\.py|test_helper\\.rb|setup_test\\.go|jest\\.setup\\.|vitest\\.setup\\.)$/i;\n\nfunction isTestFile(filePath: string): boolean {\n return TEST_PATH_PATTERN.test(filePath) || TEST_FILE_PATTERN.test(filePath) || TEST_FILE_NAMES.test(filePath);\n}\n\n// ── ORM/Schema/Model definition detection ──\nconst SCHEMA_DEFINITION_PATTERN = /(?:type|Type)\\s*:\\s*(?:String|Number|Boolean|Date|Object|Array|Mixed|mongoose\\.Schema|DataTypes|Sequelize)/i;\nconst TS_TYPE_DECLARATION = /^\\s*(?:password|passwd|secret|token|key|apiKey|api_key|credential)\\s*[?:]?\\s*:\\s*(?:string|number|boolean|any)\\b/i;\n\n// ─── Main Analyzer Function ────────────────────────────────────────────────\n\n/**\n * Analyze source code for hardcoded secrets and credentials.\n */\nexport function analyzeSecrets(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath } = context;\n\n if (content.length < 10) return findings;\n\n // Skip binary-looking or minified files\n const ext = filePath.toLowerCase();\n for (const skipExt of SKIP_ENTROPY_EXTENSIONS) {\n if (ext.endsWith(skipExt)) return findings;\n }\n\n const inTestFile = isTestFile(filePath);\n\n // Run password patterns — skip in test files (dummy credentials are expected)\n if (!inTestFile) {\n for (const pattern of PASSWORD_PATTERNS) {\n findings.push(...detectSecretPattern(content, filePath, pattern));\n }\n }\n\n // Run API key patterns — ALWAYS run (API keys in tests = real leaks)\n for (const pattern of API_KEY_PATTERNS) {\n findings.push(...detectSecretPattern(content, filePath, pattern));\n }\n\n // Run private key patterns — ALWAYS run (private keys in tests = real leaks)\n for (const pattern of PRIVATE_KEY_PATTERNS) {\n findings.push(...detectSecretPattern(content, filePath, pattern));\n }\n\n // Detect high-entropy strings — skip in test files\n if (!inTestFile) {\n findings.push(...detectHighEntropyStrings(content, filePath));\n }\n\n return findings;\n}\n\n// ─── Internal Helpers ──────────────────────────────────────────────────────\n\nfunction detectSecretPattern(source: string, filePath: string, pattern: SecretPattern): Finding[] {\n const findings: Finding[] = [];\n const matches = matchPattern(source, pattern.regex);\n\n for (const match of matches) {\n // Skip lines that look like comments, docs, or test data\n const trimmed = match.lineContent.trimStart();\n if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('#') || trimmed.startsWith('/*')) {\n continue;\n }\n // Skip lines that reference environment variables (good practice)\n if (/process\\.env\\b|os\\.environ|System\\.getenv|ENV\\[/i.test(match.lineContent)) {\n continue;\n }\n // Skip example/placeholder values (excluding high-fidelity test keys like AWS keys containing EXAMPLE)\n if (\n !/^(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}$/i.test(match.match) &&\n /(?:example|placeholder|your[_-]|changeme|xxxx|TODO|FIXME)/i.test(match.match)\n ) {\n continue;\n }\n\n // Skip ORM/schema/model field definitions (password: { type: String })\n if (SCHEMA_DEFINITION_PATTERN.test(match.lineContent)) {\n continue;\n }\n // Skip TypeScript/interface type declarations (password?: string)\n if (TS_TYPE_DECLARATION.test(trimmed)) {\n continue;\n }\n\n // For password patterns, skip trivially low-entropy values ('test', 'admin', 'password')\n if (pattern.subcategory === 'hardcoded-password') {\n const secretValueMatch = match.match.match(/[=:]\\s*['\"]([^'\"]+)['\"]/);\n if (secretValueMatch) {\n const secretValue = secretValueMatch[1];\n if (shannonEntropy(secretValue) < 2.0) {\n continue;\n }\n }\n }\n\n const snippet = extractSnippet(source, match.line);\n findings.push(\n createFinding({\n ruleId: pattern.id,\n scanner: 'security',\n severity: pattern.severity,\n confidence: pattern.confidence,\n category: 'secrets',\n subcategory: pattern.subcategory,\n title: `Hardcoded Secret${pattern.service ? ` (${pattern.service})` : ''}`,\n message: pattern.message,\n filePath,\n lineNumber: match.line,\n column: match.column,\n snippet,\n cwe: ['CWE-798'],\n owasp: ['A02:2021'],\n fix: {\n description: 'Move secrets to environment variables, a vault service, or a secrets manager. Never commit secrets to source control.',\n references: [\n 'https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html',\n ],\n },\n tags: ['secrets', 'credentials', ...(pattern.service ? [pattern.service.toLowerCase()] : [])],\n }),\n );\n }\n\n return findings;\n}\n\n/**\n * Detect high-entropy strings that may be secrets.\n */\nfunction detectHighEntropyStrings(source: string, filePath: string): Finding[] {\n const findings: Finding[] = [];\n const lines = source.split('\\n');\n\n // Regex to match string assignments that might contain secrets\n const stringAssignmentRegex = /(?:=|:)\\s*[\"']([A-Za-z0-9+/=_\\-]{20,})[\"']/g;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trimStart();\n\n // Skip comments\n if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('#')) continue;\n // Skip imports/requires\n if (/^\\s*(?:import|require|from|use)\\b/.test(line)) continue;\n // Skip lines referencing env vars\n if (/process\\.env|os\\.environ|System\\.getenv/i.test(line)) continue;\n\n let m: RegExpExecArray | null;\n const regex = new RegExp(stringAssignmentRegex.source, stringAssignmentRegex.flags);\n while ((m = regex.exec(line)) !== null) {\n const value = m[1];\n\n // Skip known false positives\n if (ENTROPY_FALSE_POSITIVES.has(value)) continue;\n // Skip short strings or very long strings (likely not secrets)\n if (value.length < 20 || value.length > 256) continue;\n // Skip if it looks like a URL path, CSS class, or file path\n if (/^[a-z][a-z0-9-]*(?:\\/[a-z][a-z0-9-]*)*$/i.test(value)) continue;\n // Skip base64-encoded images or data URIs\n if (/^data:/.test(value)) continue;\n\n const entropy = shannonEntropy(value);\n // High entropy threshold: base64 charset ~= 4.5, hex charset ~= 3.7\n if (entropy >= 4.2) {\n const snippet = extractSnippet(source, i + 1);\n findings.push(\n createFinding({\n ruleId: 'SEC-SEC-050',\n scanner: 'security',\n severity: 'medium',\n confidence: 'low',\n category: 'secrets',\n subcategory: 'high-entropy',\n title: 'High-Entropy String (Possible Secret)',\n message: `High-entropy string detected (entropy: ${entropy.toFixed(2)}). This may be a hardcoded secret or key.`,\n filePath,\n lineNumber: i + 1,\n column: m.index + 1,\n snippet,\n cwe: ['CWE-798'],\n owasp: ['A02:2021'],\n fix: {\n description: 'If this is a secret, move it to environment variables or a secrets manager.',\n references: [],\n },\n tags: ['secrets', 'entropy'],\n }),\n );\n }\n\n if (m.index === regex.lastIndex) regex.lastIndex++;\n }\n }\n\n return findings;\n}\n","// ─── Auth Analyzer ─────────────────────────────────────────────────────────\n// Phát hiện lỗ hổng xác thực và phân quyền\n// Detects weak authentication, missing CSRF, insecure sessions, hardcoded JWT secrets\n\nimport type { Finding, Severity, Confidence } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport { createFinding, extractSnippet, matchPattern, isPatternDefinitionContext, isInSafeASTContext } from '../../base-scanner.js';\n\n// ─── Pattern Definitions ───────────────────────────────────────────────────\n\ninterface AuthPattern {\n regex: RegExp;\n message: string;\n severity: Severity;\n confidence: Confidence;\n subcategory: string;\n ruleId: string;\n cwe: string[];\n}\n\nconst AUTH_PATTERNS: AuthPattern[] = [\n // ── Weak password comparison ──\n {\n regex: /(?:password|passwd|pwd)\\s*===?\\s*[\"'][^\"']+[\"']/i,\n message: 'Password compared against hardcoded string – use proper hashing (bcrypt, argon2)',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'weak-password',\n ruleId: 'SEC-AUTH-001',\n cwe: ['CWE-798', 'CWE-259'],\n },\n {\n regex: /if\\s*\\(\\s*(?:password|passwd|pwd|pass)\\s*===?\\s*(?:req|request|params|body)\\b[^)]*\\)/i,\n message: 'Direct password comparison without hashing – timing attack and plaintext storage risk',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'weak-password',\n ruleId: 'SEC-AUTH-001',\n cwe: ['CWE-916'],\n },\n {\n regex: /(?:password|passwd|pwd)\\s*==\\s*(?!null|undefined|\"\")\\w+/i,\n message: 'Loose equality (==) used for password comparison – use constant-time comparison',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'weak-password',\n ruleId: 'SEC-AUTH-001',\n cwe: ['CWE-208'],\n },\n {\n regex: /\\.(?:compare|equals)\\s*\\(\\s*(?:password|passwd|pwd)\\s*,\\s*(?:password|passwd|pwd)\\s*\\)/i,\n message: 'Verify that password comparison uses a constant-time function (e.g., bcrypt.compare)',\n severity: 'low',\n confidence: 'low',\n subcategory: 'weak-password',\n ruleId: 'SEC-AUTH-001',\n cwe: ['CWE-208'],\n },\n\n // ── Missing CSRF protection ──\n {\n regex: /(?:csrf|xsrf)\\s*[:=]\\s*(?:false|disabled|off)/i,\n message: 'CSRF protection explicitly disabled',\n severity: 'high',\n confidence: 'high',\n subcategory: 'csrf',\n ruleId: 'SEC-AUTH-002',\n cwe: ['CWE-352'],\n },\n {\n regex: /app\\.(?:disable|set)\\s*\\(\\s*[\"']csrf[\"']\\s*(?:,\\s*false)?\\s*\\)/i,\n message: 'CSRF protection disabled in application configuration',\n severity: 'high',\n confidence: 'high',\n subcategory: 'csrf',\n ruleId: 'SEC-AUTH-002',\n cwe: ['CWE-352'],\n },\n {\n regex: /@csrf_exempt/i,\n message: 'Django @csrf_exempt decorator – endpoint lacks CSRF protection',\n severity: 'medium',\n confidence: 'high',\n subcategory: 'csrf',\n ruleId: 'SEC-AUTH-002',\n cwe: ['CWE-352'],\n },\n {\n regex: /verify_authenticity_token\\s*.*skip/i,\n message: 'Rails authenticity token verification skipped',\n severity: 'high',\n confidence: 'high',\n subcategory: 'csrf',\n ruleId: 'SEC-AUTH-002',\n cwe: ['CWE-352'],\n },\n\n // ── Insecure session configuration ──\n {\n regex: /(?:session|cookie)\\s*(?::\\s*\\{[^}]*|\\.)\\s*(?:secure\\s*[:=]\\s*false)/i,\n message: 'Session cookie Secure flag set to false – cookie sent over HTTP',\n severity: 'high',\n confidence: 'high',\n subcategory: 'session',\n ruleId: 'SEC-AUTH-003',\n cwe: ['CWE-614'],\n },\n {\n regex: /(?:session|cookie)\\s*(?::\\s*\\{[^}]*|\\.)\\s*(?:httpOnly\\s*[:=]\\s*false)/i,\n message: 'Session cookie HttpOnly flag set to false – cookie accessible via JavaScript',\n severity: 'high',\n confidence: 'high',\n subcategory: 'session',\n ruleId: 'SEC-AUTH-003',\n cwe: ['CWE-1004'],\n },\n {\n regex: /sameSite\\s*[:=]\\s*[\"'](?:none|None)[\"']/i,\n message: 'SameSite cookie attribute set to None – may enable CSRF',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'session',\n ruleId: 'SEC-AUTH-003',\n cwe: ['CWE-1275'],\n },\n {\n regex: /(?:express-session|session)\\s*\\(\\s*\\{[^}]*secret\\s*:\\s*[\"'][^\"']{1,10}[\"']/i,\n message: 'Session secret is too short – use a strong, random secret',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'session',\n ruleId: 'SEC-AUTH-003',\n cwe: ['CWE-331'],\n },\n {\n regex: /SESSION_COOKIE_SECURE\\s*=\\s*False/i,\n message: 'Django SESSION_COOKIE_SECURE set to False',\n severity: 'high',\n confidence: 'high',\n subcategory: 'session',\n ruleId: 'SEC-AUTH-003',\n cwe: ['CWE-614'],\n },\n\n // ── Hardcoded JWT secrets ──\n {\n regex: /jwt\\.sign\\s*\\([^,]+,\\s*[\"'][^\"']{1,30}[\"']/i,\n message: 'JWT signed with hardcoded secret – use environment variable',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'jwt',\n ruleId: 'SEC-AUTH-004',\n cwe: ['CWE-798'],\n },\n {\n regex: /jwt\\.verify\\s*\\([^,]+,\\s*[\"'][^\"']+[\"']/i,\n message: 'JWT verified with hardcoded secret – use environment variable',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'jwt',\n ruleId: 'SEC-AUTH-004',\n cwe: ['CWE-798'],\n },\n {\n regex: /(?:jwt_secret|JWT_SECRET|jwtSecret)\\s*[:=]\\s*[\"'][^\"']+[\"']/i,\n message: 'JWT secret hardcoded in source code',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'jwt',\n ruleId: 'SEC-AUTH-004',\n cwe: ['CWE-798'],\n },\n {\n regex: /algorithm\\s*[:=]\\s*[\"']none[\"']/i,\n message: 'JWT algorithm set to \"none\" – tokens are unsigned and easily forged',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'jwt',\n ruleId: 'SEC-AUTH-004',\n cwe: ['CWE-327'],\n },\n\n // ── Disabled security middleware ──\n {\n regex: /(?:helmet|cors|csurf|rate.?limit)\\s*\\(\\s*\\{[^}]*disable[^}]*\\}/i,\n message: 'Security middleware explicitly disabled or misconfigured',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'middleware',\n ruleId: 'SEC-AUTH-005',\n cwe: ['CWE-693'],\n },\n {\n regex: /cors\\s*\\(\\s*\\{[^}]*origin\\s*:\\s*(?:true|[\"']\\*[\"'])/i,\n message: 'CORS configured with wildcard origin (*) or all origins – may allow unauthorized cross-origin requests',\n severity: 'medium',\n confidence: 'high',\n subcategory: 'middleware',\n ruleId: 'SEC-AUTH-005',\n cwe: ['CWE-942'],\n },\n {\n regex: /\\.disable\\s*\\(\\s*[\"'](?:x-powered-by|etag)[\"']\\s*\\)/i,\n message: 'Security header disabled – verify this is intentional',\n severity: 'low',\n confidence: 'low',\n subcategory: 'middleware',\n ruleId: 'SEC-AUTH-005',\n cwe: ['CWE-693'],\n },\n {\n regex: /ALLOWED_HOSTS\\s*=\\s*\\[\\s*[\"']\\*[\"']\\s*\\]/i,\n message: 'Django ALLOWED_HOSTS set to wildcard – host header injection risk',\n severity: 'high',\n confidence: 'high',\n subcategory: 'middleware',\n ruleId: 'SEC-AUTH-005',\n cwe: ['CWE-20'],\n },\n {\n regex: /DEBUG\\s*=\\s*True/,\n message: 'Debug mode enabled in production configuration',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'middleware',\n ruleId: 'SEC-AUTH-005',\n cwe: ['CWE-489'],\n },\n];\n\n// ─── Main Analyzer Function ────────────────────────────────────────────────\n\n/**\n * Analyze source code for authentication and authorization vulnerabilities.\n * Phân tích mã nguồn để phát hiện lỗ hổng xác thực và phân quyền\n */\nexport function analyzeAuth(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath } = context;\n\n if (content.length < 10) return findings;\n\n for (const pattern of AUTH_PATTERNS) {\n const matches = matchPattern(content, pattern.regex);\n for (const match of matches) {\n // Skip matches in safe AST contexts (string literals, comments, imports, type annotations)\n if (context.tree && isInSafeASTContext(context.tree, match.line, match.column)) continue;\n\n // Skip comments\n const trimmed = match.lineContent.trimStart();\n if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('#') || trimmed.startsWith('/*')) {\n continue;\n }\n\n // Skip matches inside pattern/rule definition contexts\n if (isPatternDefinitionContext(match.lineContent, match.column)) continue;\n\n const snippet = extractSnippet(content, match.line);\n findings.push(\n createFinding({\n ruleId: pattern.ruleId,\n scanner: 'security',\n severity: pattern.severity,\n confidence: pattern.confidence,\n category: 'auth',\n subcategory: pattern.subcategory,\n title: 'Authentication / Authorization Issue',\n message: pattern.message,\n filePath,\n lineNumber: match.line,\n column: match.column,\n snippet,\n cwe: pattern.cwe,\n owasp: ['A07:2021'],\n fix: {\n description: 'Follow secure authentication best practices: use bcrypt/argon2 for passwords, enable CSRF, set secure cookie flags, and use strong JWT secrets from environment variables.',\n references: [\n 'https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html',\n 'https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html',\n ],\n },\n tags: ['auth', 'owasp-top10'],\n }),\n );\n }\n }\n\n return findings;\n}\n","// ─── Crypto Analyzer ───────────────────────────────────────────────────────\n// Phát hiện lỗ hổng mật mã: thuật toán yếu, khóa hardcode, TLS bị tắt\n// Detects weak hash/encryption, insecure random, hardcoded keys, disabled TLS\n\nimport type { Finding, Severity, Confidence } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport { createFinding, extractSnippet, matchPattern, isPatternDefinitionContext, isInSafeASTContext } from '../../base-scanner.js';\n\n// ─── Pattern Definitions ───────────────────────────────────────────────────\n\ninterface CryptoPattern {\n regex: RegExp;\n message: string;\n severity: Severity;\n confidence: Confidence;\n subcategory: string;\n ruleId: string;\n cwe: string[];\n}\n\nconst CRYPTO_PATTERNS: CryptoPattern[] = [\n // ── Weak Hash Algorithms ──\n {\n regex: /createHash\\s*\\(\\s*[\"']md5[\"']\\s*\\)/i,\n message: 'MD5 hash used – MD5 is cryptographically broken, use SHA-256 or better',\n severity: 'high',\n confidence: 'high',\n subcategory: 'weak-hash',\n ruleId: 'SEC-CRYPTO-001',\n cwe: ['CWE-328'],\n },\n {\n regex: /createHash\\s*\\(\\s*[\"']sha1[\"']\\s*\\)/i,\n message: 'SHA-1 hash used – SHA-1 has known collisions, use SHA-256 or better',\n severity: 'medium',\n confidence: 'high',\n subcategory: 'weak-hash',\n ruleId: 'SEC-CRYPTO-001',\n cwe: ['CWE-328'],\n },\n {\n regex: /(?:hashlib|MessageDigest)\\s*\\.\\s*(?:md5|MD5)/i,\n message: 'MD5 hash usage detected – MD5 is cryptographically broken',\n severity: 'high',\n confidence: 'high',\n subcategory: 'weak-hash',\n ruleId: 'SEC-CRYPTO-001',\n cwe: ['CWE-328'],\n },\n {\n regex: /(?:hashlib|MessageDigest)\\s*\\.\\s*(?:sha1|SHA1|SHA-1)/i,\n message: 'SHA-1 hash usage detected – SHA-1 has known collision attacks',\n severity: 'medium',\n confidence: 'high',\n subcategory: 'weak-hash',\n ruleId: 'SEC-CRYPTO-001',\n cwe: ['CWE-328'],\n },\n {\n regex: /DigestUtils\\.md5(?:Hex)?\\s*\\(/i,\n message: 'Apache DigestUtils MD5 – use SHA-256 or better',\n severity: 'high',\n confidence: 'high',\n subcategory: 'weak-hash',\n ruleId: 'SEC-CRYPTO-001',\n cwe: ['CWE-328'],\n },\n {\n regex: /(?:MD5|md5)\\s*\\(\\s*(?:password|passwd|pwd|pass|secret)\\b/i,\n message: 'MD5 used for password hashing – use bcrypt, argon2, or scrypt instead',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'weak-hash',\n ruleId: 'SEC-CRYPTO-001',\n cwe: ['CWE-916'],\n },\n\n // ── Weak Encryption ──\n {\n regex: /createCipher(?:iv)?\\s*\\(\\s*[\"'](?:des|des-ecb|des-cbc|des3|rc4|rc2|blowfish)[\"']/i,\n message: 'Weak encryption algorithm (DES/RC4/RC2) – use AES-256-GCM or ChaCha20',\n severity: 'high',\n confidence: 'high',\n subcategory: 'weak-encryption',\n ruleId: 'SEC-CRYPTO-002',\n cwe: ['CWE-327'],\n },\n {\n regex: /(?:DES|DESede|RC4|RC2|Blowfish)\\.(?:new|getInstance)\\s*\\(/i,\n message: 'Weak encryption algorithm instantiated – use AES-256 instead',\n severity: 'high',\n confidence: 'high',\n subcategory: 'weak-encryption',\n ruleId: 'SEC-CRYPTO-002',\n cwe: ['CWE-327'],\n },\n {\n regex: /Cipher\\.getInstance\\s*\\(\\s*[\"'](?:DES|DESede|RC4|RC2|Blowfish)/i,\n message: 'Java Cipher with weak algorithm – use AES/GCM/NoPadding',\n severity: 'high',\n confidence: 'high',\n subcategory: 'weak-encryption',\n ruleId: 'SEC-CRYPTO-002',\n cwe: ['CWE-327'],\n },\n {\n regex: /(?:AES|Cipher).*(?:ECB|\\/ECB\\/)/i,\n message: 'ECB mode used for encryption – ECB does not provide semantic security, use CBC or GCM',\n severity: 'high',\n confidence: 'high',\n subcategory: 'weak-encryption',\n ruleId: 'SEC-CRYPTO-002',\n cwe: ['CWE-327'],\n },\n {\n regex: /createCipher\\s*\\(\\s*[\"']/i,\n message: 'crypto.createCipher is deprecated and insecure – use createCipheriv with a random IV',\n severity: 'high',\n confidence: 'high',\n subcategory: 'weak-encryption',\n ruleId: 'SEC-CRYPTO-002',\n cwe: ['CWE-327'],\n },\n\n // ── Insecure Random Number Generation ──\n {\n regex: /Math\\.random\\s*\\(\\s*\\)/i,\n message: 'Math.random() is not cryptographically secure – use crypto.randomBytes() or crypto.getRandomValues()',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'insecure-random',\n ruleId: 'SEC-CRYPTO-003',\n cwe: ['CWE-338'],\n },\n {\n regex: /(?:token|secret|key|password|nonce|salt|iv)\\s*=\\s*.*Math\\.random/i,\n message: 'Math.random() used to generate security-sensitive value – use CSPRNG',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'insecure-random',\n ruleId: 'SEC-CRYPTO-003',\n cwe: ['CWE-338'],\n },\n {\n regex: /random\\.random\\s*\\(\\s*\\)/i,\n message: 'Python random.random() is not cryptographically secure – use secrets module',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'insecure-random',\n ruleId: 'SEC-CRYPTO-003',\n cwe: ['CWE-338'],\n },\n {\n regex: /java\\.util\\.Random\\b/i,\n message: 'java.util.Random is not cryptographically secure – use java.security.SecureRandom',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'insecure-random',\n ruleId: 'SEC-CRYPTO-003',\n cwe: ['CWE-338'],\n },\n {\n regex: /rand\\s*\\(\\s*\\)|srand\\s*\\(/i,\n message: 'rand()/srand() is not cryptographically secure',\n severity: 'medium',\n confidence: 'low',\n subcategory: 'insecure-random',\n ruleId: 'SEC-CRYPTO-003',\n cwe: ['CWE-338'],\n },\n\n // ── Hardcoded Encryption Keys ──\n {\n regex: /(?:encryption_key|encrypt_key|cipher_key|aes_key|AES_KEY)\\s*[:=]\\s*[\"'][A-Za-z0-9+/=]{8,}[\"']/i,\n message: 'Hardcoded encryption key – store keys in a secure key management system',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'hardcoded-key',\n ruleId: 'SEC-CRYPTO-004',\n cwe: ['CWE-321'],\n },\n {\n regex: /(?:private_key|PRIVATE_KEY|privateKey)\\s*[:=]\\s*[\"'][^\"']{10,}[\"']/i,\n message: 'Hardcoded private key in source code',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'hardcoded-key',\n ruleId: 'SEC-CRYPTO-004',\n cwe: ['CWE-321'],\n },\n {\n regex: /(?:iv|IV|initVector|initialization_vector)\\s*[:=]\\s*[\"'][0-9a-fA-F]{16,}[\"']/i,\n message: 'Hardcoded initialization vector – IV should be randomly generated per encryption',\n severity: 'high',\n confidence: 'high',\n subcategory: 'hardcoded-key',\n ruleId: 'SEC-CRYPTO-004',\n cwe: ['CWE-329'],\n },\n {\n regex: /Buffer\\.from\\s*\\(\\s*[\"'][0-9a-fA-F]{16,}[\"']\\s*,\\s*[\"']hex[\"']\\s*\\)/i,\n message: 'Possible hardcoded key or IV created from hex string',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'hardcoded-key',\n ruleId: 'SEC-CRYPTO-004',\n cwe: ['CWE-321'],\n },\n\n // ── Disabled TLS Verification ──\n {\n regex: /rejectUnauthorized\\s*[:=]\\s*false/i,\n message: 'TLS certificate verification disabled (rejectUnauthorized: false) – vulnerable to MITM',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'tls',\n ruleId: 'SEC-CRYPTO-005',\n cwe: ['CWE-295'],\n },\n {\n regex: /NODE_TLS_REJECT_UNAUTHORIZED\\s*[:=]\\s*[\"']?0[\"']?/i,\n message: 'NODE_TLS_REJECT_UNAUTHORIZED set to 0 – disables all TLS verification',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'tls',\n ruleId: 'SEC-CRYPTO-005',\n cwe: ['CWE-295'],\n },\n {\n regex: /verify\\s*[:=]\\s*false|ssl_verify\\s*[:=]\\s*false|VERIFY_NONE/i,\n message: 'SSL/TLS verification disabled – vulnerable to man-in-the-middle attacks',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'tls',\n ruleId: 'SEC-CRYPTO-005',\n cwe: ['CWE-295'],\n },\n {\n regex: /InsecureRequestWarning.*disable/i,\n message: 'Insecure request warning suppressed – likely because TLS verification is disabled',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'tls',\n ruleId: 'SEC-CRYPTO-005',\n cwe: ['CWE-295'],\n },\n {\n regex: /ssl\\._create_unverified_context/i,\n message: 'Python ssl._create_unverified_context() – disables certificate verification',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'tls',\n ruleId: 'SEC-CRYPTO-005',\n cwe: ['CWE-295'],\n },\n {\n regex: /checkServerIdentity\\s*:\\s*\\(\\s*\\)\\s*=>\\s*(?:true|undefined|null|void)/i,\n message: 'Custom checkServerIdentity always returns true – disables hostname verification',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'tls',\n ruleId: 'SEC-CRYPTO-005',\n cwe: ['CWE-297'],\n },\n];\n\n// ─── Main Analyzer Function ────────────────────────────────────────────────\n\n/**\n * Analyze source code for cryptography vulnerabilities.\n * Phân tích mã nguồn để phát hiện lỗ hổng mật mã\n */\nexport function analyzeCrypto(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath } = context;\n\n if (content.length < 10) return findings;\n\n for (const pattern of CRYPTO_PATTERNS) {\n const matches = matchPattern(content, pattern.regex);\n for (const match of matches) {\n // Skip matches in safe AST contexts (string literals, comments, imports, type annotations)\n if (context.tree && isInSafeASTContext(context.tree, match.line, match.column)) continue;\n\n // Skip comments\n const trimmed = match.lineContent.trimStart();\n if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('#') || trimmed.startsWith('/*')) {\n continue;\n }\n\n // Skip matches inside pattern/rule definition contexts\n if (isPatternDefinitionContext(match.lineContent, match.column)) continue;\n\n // Skip Math.random() in non-cryptographic/non-security contexts (e.g. UI key/ID generation)\n if (pattern.subcategory === 'insecure-random' && pattern.regex.source.includes('Math\\\\.random')) {\n const isSafeContext = \n trimmed.includes('id:') ||\n trimmed.includes('id =') ||\n trimmed.includes('key:') ||\n trimmed.includes('key =') ||\n trimmed.includes('reactKey') ||\n trimmed.includes('index') ||\n trimmed.includes('assert') ||\n trimmed.includes('tc.') ||\n /^(?:const|let|var)\\s+\\w*(?:id|key|uuid|idx|index)\\w*\\s*=/i.test(trimmed);\n if (isSafeContext) {\n continue;\n }\n }\n\n const snippet = extractSnippet(content, match.line);\n findings.push(\n createFinding({\n ruleId: pattern.ruleId,\n scanner: 'security',\n severity: pattern.severity,\n confidence: pattern.confidence,\n category: 'crypto',\n subcategory: pattern.subcategory,\n title: 'Cryptography Issue',\n message: pattern.message,\n filePath,\n lineNumber: match.line,\n column: match.column,\n snippet,\n cwe: pattern.cwe,\n owasp: ['A02:2021'],\n fix: {\n description: 'Use strong, modern cryptographic algorithms. SHA-256+ for hashing, AES-256-GCM for encryption, CSPRNG for randomness. Never hardcode keys or disable TLS.',\n references: [\n 'https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html',\n 'https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Security_Cheat_Sheet.html',\n ],\n },\n tags: ['crypto', 'owasp-top10'],\n }),\n );\n }\n }\n\n return findings;\n}\n","// ─── File Operations Analyzer ──────────────────────────────────────────────\n// Phát hiện lỗ hổng thao tác tệp: path traversal, quyền truy cập không an toàn\n// Detects path traversal, unsafe permissions, temp file issues\n\nimport type { Finding, Severity, Confidence } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport { createFinding, extractSnippet, matchPattern, isPatternDefinitionContext, isInSafeASTContext } from '../../base-scanner.js';\n\n// ─── Pattern Definitions ───────────────────────────────────────────────────\n\ninterface FileOpsPattern {\n regex: RegExp;\n message: string;\n severity: Severity;\n confidence: Confidence;\n subcategory: string;\n ruleId: string;\n cwe: string[];\n}\n\nconst FILE_OPS_PATTERNS: FileOpsPattern[] = [\n // ── Path Traversal ──\n {\n regex: /\\b(?:readFile|readFileSync|createReadStream|writeFile|writeFileSync|appendFile|unlink|unlinkSync|stat|statSync|access|accessSync|open|openSync)\\b\\s*\\(\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'File operation with user-controlled path – vulnerable to path traversal',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'path-traversal',\n ruleId: 'SEC-FILE-001',\n cwe: ['CWE-22'],\n },\n {\n regex: /\\b(?:readFile|readFileSync|createReadStream|writeFile|writeFileSync)\\b\\s*\\(\\s*(?:[\"'`][^\"'`]*[\"'`]\\s*\\+\\s*\\w+|\\w+\\s*\\+\\s*[\"'`])/i,\n message: 'File path built with string concatenation – potential path traversal',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'path-traversal',\n ruleId: 'SEC-FILE-001',\n cwe: ['CWE-22'],\n },\n {\n regex: /\\b(?:readFile|readFileSync|createReadStream|writeFile|writeFileSync)\\b\\s*\\(\\s*`[^`]*\\$\\{[^}]+\\}[^`]*`/i,\n message: 'File path with template literal interpolation – potential path traversal',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'path-traversal',\n ruleId: 'SEC-FILE-001',\n cwe: ['CWE-22'],\n },\n {\n regex: /path\\.(?:join|resolve)\\s*\\(\\s*[^,)]+,\\s*(?:req|request|params|query|body|args|input|user)\\b/i,\n message: 'path.join/resolve with user input – validate that the result stays within allowed directory',\n severity: 'medium',\n confidence: 'high',\n subcategory: 'path-traversal',\n ruleId: 'SEC-FILE-001',\n cwe: ['CWE-22'],\n },\n {\n regex: /\\.\\.(?:\\/|\\\\)/,\n message: 'Relative path traversal pattern (../) detected – verify this is safe',\n severity: 'low',\n confidence: 'low',\n subcategory: 'path-traversal',\n ruleId: 'SEC-FILE-001',\n cwe: ['CWE-22'],\n },\n {\n // Python open() with user input\n regex: /\\bopen\\b\\s*\\(\\s*(?:request\\.|req\\.|params|user_input)\\b/i,\n message: 'Python open() with potentially user-controlled path – path traversal risk',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'path-traversal',\n ruleId: 'SEC-FILE-001',\n cwe: ['CWE-22'],\n },\n {\n // Express static file serving with user input\n regex: /\\bres\\.sendFile\\b\\s*\\(\\s*(?:req|request)\\b/i,\n message: 'res.sendFile with user-controlled path – path traversal risk',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'path-traversal',\n ruleId: 'SEC-FILE-001',\n cwe: ['CWE-22'],\n },\n {\n // PHP file inclusion\n regex: /(?:include|require|include_once|require_once)\\s*\\(\\s*\\$_(?:GET|POST|REQUEST)/i,\n message: 'PHP file inclusion with user input – Local/Remote File Inclusion vulnerability',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'path-traversal',\n ruleId: 'SEC-FILE-001',\n cwe: ['CWE-98'],\n },\n\n // ── Unsafe File Permissions ──\n {\n regex: /chmod\\s*\\(\\s*[^,]+,\\s*(?:0o?777|0o?766|0o?667|511|438)/i,\n message: 'File permissions set to world-writable (777/766) – restrict to minimum necessary',\n severity: 'high',\n confidence: 'high',\n subcategory: 'permissions',\n ruleId: 'SEC-FILE-002',\n cwe: ['CWE-732'],\n },\n {\n regex: /chmod\\s*\\(\\s*[^,]+,\\s*(?:0o?666|0o?664|0o?646)/i,\n message: 'File permissions set to world-readable/writable (666) – restrict permissions',\n severity: 'medium',\n confidence: 'high',\n subcategory: 'permissions',\n ruleId: 'SEC-FILE-002',\n cwe: ['CWE-732'],\n },\n {\n regex: /(?:writeFile|writeFileSync|appendFile)\\s*\\([^)]*mode\\s*:\\s*(?:0o?777|0o?766|0o?666)/i,\n message: 'File created with overly permissive mode',\n severity: 'high',\n confidence: 'high',\n subcategory: 'permissions',\n ruleId: 'SEC-FILE-002',\n cwe: ['CWE-732'],\n },\n {\n regex: /umask\\s*\\(\\s*0+\\s*\\)/i,\n message: 'umask set to 0 – all new files will have maximum permissions',\n severity: 'high',\n confidence: 'high',\n subcategory: 'permissions',\n ruleId: 'SEC-FILE-002',\n cwe: ['CWE-732'],\n },\n\n // ── Temporary File Issues ──\n {\n regex: /(?:\\/tmp\\/|\\\\temp\\\\|tempnam|tmpnam|mktemp(?!dir))\\b/i,\n message: 'Use of predictable temporary file path – use mkdtemp/mkstemp for secure temp files',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'temp-files',\n ruleId: 'SEC-FILE-003',\n cwe: ['CWE-377'],\n },\n {\n regex: /(?:tmpfile|tempfile\\.NamedTemporaryFile)\\s*\\([^)]*delete\\s*=\\s*False/i,\n message: 'Temporary file not auto-deleted – may leave sensitive data on disk',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'temp-files',\n ruleId: 'SEC-FILE-003',\n cwe: ['CWE-459'],\n },\n {\n regex: /(?:writeFile|writeFileSync)\\s*\\(\\s*[\"']\\/tmp\\//i,\n message: 'Writing to predictable /tmp path – may be vulnerable to symlink attacks',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'temp-files',\n ruleId: 'SEC-FILE-003',\n cwe: ['CWE-377'],\n },\n\n // ── Unsafe file upload ──\n {\n regex: /multer\\s*\\(\\s*\\{[^}]*(?:dest|storage)[^}]*\\}/i,\n message: 'File upload detected – ensure proper validation of file type, size, and content',\n severity: 'low',\n confidence: 'low',\n subcategory: 'file-upload',\n ruleId: 'SEC-FILE-004',\n cwe: ['CWE-434'],\n },\n {\n regex: /\\.(?:originalname|filename)\\s*(?:;|\\))/i,\n message: 'Original filename used directly – sanitize filenames to prevent directory traversal in uploads',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'file-upload',\n ruleId: 'SEC-FILE-004',\n cwe: ['CWE-434'],\n },\n {\n // Go/Generic path traversal with variables in ReadFile/Open/etc.\n regex: /\\b(?:ioutil\\.|os\\.)(?:ReadFile|Open|OpenFile|Create|Remove)\\b\\s*\\(\\s*[^'\"`)]*\\b(?:req|request|params|query|body|args|input|user|filename|uri|url)\\b/i,\n message: 'File read/open using dynamic path – potential path traversal risk',\n severity: 'high',\n confidence: 'medium',\n subcategory: 'path-traversal',\n ruleId: 'SEC-FILE-001',\n cwe: ['CWE-22'],\n },\n {\n // Python/Go/Generic path construction with potentially user-controlled variables\n regex: /\\b(?:filepath\\.|path\\.|os\\.path\\.)Join\\b\\s*\\(\\s*[^,]+,\\s*\\b(?:req|request|params|query|body|args|input|user|filename|uri|url)\\b/i,\n message: 'Path construction using variables – verify input is sanitized to prevent path traversal',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'path-traversal',\n ruleId: 'SEC-FILE-001',\n cwe: ['CWE-22'],\n },\n];\n\n// ─── Main Analyzer Function ────────────────────────────────────────────────\n\n/**\n * Analyze source code for file operation vulnerabilities.\n */\nexport function analyzeFileOps(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath } = context;\n\n if (content.length < 10) return findings;\n\n for (const pattern of FILE_OPS_PATTERNS) {\n const matches = matchPattern(content, pattern.regex);\n for (const match of matches) {\n // Skip matches in safe AST contexts (string literals, comments, imports, type annotations)\n if (context.tree && isInSafeASTContext(context.tree, match.line, match.column)) continue;\n\n // Skip comments and import/export statements\n const trimmed = match.lineContent.trimStart();\n if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('#') || trimmed.startsWith('/*')) {\n continue;\n }\n\n // Skip matches inside pattern/rule definition contexts\n if (isPatternDefinitionContext(match.lineContent, match.column)) continue;\n const isConfigFile = \n filePath.endsWith('.config.js') || \n filePath.endsWith('.config.ts') || \n filePath.includes('vite.config') || \n filePath.includes('webpack.') || \n filePath.includes('tailwind.');\n\n if (\n trimmed.startsWith('import ') ||\n trimmed.startsWith('export ') ||\n trimmed.startsWith('from ') ||\n trimmed.includes('require(') ||\n trimmed.includes('require ') ||\n trimmed.includes('require_once ') ||\n trimmed.includes('include ') ||\n trimmed.includes('include_once ') ||\n isConfigFile\n ) {\n continue;\n }\n\n // Skip static path constants starting points\n if (\n trimmed.includes('__DIR__') ||\n trimmed.includes('__dirname') ||\n trimmed.includes('__filename') ||\n trimmed.includes('__FILE__') ||\n trimmed.includes('import.meta.url')\n ) {\n if (!/(?:req|request|params|query|body|args|input|user|GET|POST|REQUEST)\\b/i.test(trimmed)) {\n continue;\n }\n }\n\n // For the generic ../ pattern, reduce noise – only flag if in a file ops context\n if (pattern.ruleId === 'SEC-FILE-001' && pattern.confidence === 'low') {\n if (!/(?:read|write|open|include|require|send|path|fs|file)\\b/i.test(match.lineContent)) {\n continue;\n }\n }\n\n const snippet = extractSnippet(content, match.line);\n findings.push(\n createFinding({\n ruleId: pattern.ruleId,\n scanner: 'security',\n severity: pattern.severity,\n confidence: pattern.confidence,\n category: 'file-ops',\n subcategory: pattern.subcategory,\n title: 'File Operation Issue',\n message: pattern.message,\n filePath,\n lineNumber: match.line,\n column: match.column,\n snippet,\n cwe: pattern.cwe,\n owasp: ['A01:2021'],\n fix: {\n description: 'Validate and sanitize file paths. Use path.resolve() and verify the resolved path is within the allowed directory. Set restrictive file permissions.',\n references: [\n 'https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html',\n 'https://owasp.org/www-community/attacks/Path_Traversal',\n ],\n },\n tags: ['file-ops'],\n }),\n );\n }\n }\n\n return findings;\n}\n","// ─── API Security Analyzer ──────────────────────────────────────────────────\n// Phát hiện lỗ hổng API & Misconfiguration: XXE, SSRF, CORS/CSRF, Rate Limiting\n// Detects XXE, SSRF, unsafe CORS, disabled CSRF, and missing rate limits\n\nimport type { Finding, Severity, Confidence } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport { createFinding, extractSnippet, matchPattern, isPatternDefinitionContext, isInSafeASTContext } from '../../base-scanner.js';\n\ninterface APISecPattern {\n regex: RegExp;\n message: string;\n severity: Severity;\n confidence: Confidence;\n subcategory: string;\n ruleId: string;\n cwe: string[];\n title: string;\n}\n\nconst API_SEC_PATTERNS: APISecPattern[] = [\n // ── XXE (XML External Entity) ──\n {\n regex: /DocumentBuilderFactory\\s*\\.\\s*(?:newInstance|newDefaultInstance)\\s*\\(/i,\n message: 'Java DocumentBuilderFactory instantiated – ensure DTD/external entities are explicitly disabled to prevent XXE',\n severity: 'critical',\n confidence: 'medium',\n subcategory: 'xxe',\n ruleId: 'SEC-XXE-001',\n cwe: ['CWE-611'],\n title: 'XML External Entity (XXE) Risk in Java',\n },\n {\n regex: /XMLInputFactory\\s*\\.\\s*(?:newInstance|newFactory)\\s*\\(/i,\n message: 'Java XMLInputFactory instantiated – ensure DTD/external entities are disabled to prevent XXE',\n severity: 'critical',\n confidence: 'medium',\n subcategory: 'xxe',\n ruleId: 'SEC-XXE-001',\n cwe: ['CWE-611'],\n title: 'XML External Entity (XXE) Risk in Java',\n },\n {\n regex: /libxmljs\\s*\\.\\s*parseXml\\s*\\(\\s*[^,)]+\\s*,\\s*\\{\\s*noent\\s*:\\s*true/i,\n message: 'libxmljs parseXml with noent: true – enables entity substitution, vulnerable to XXE',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'xxe',\n ruleId: 'SEC-XXE-002',\n cwe: ['CWE-611'],\n title: 'XML External Entity (XXE) via libxmljs',\n },\n {\n regex: /xml2js\\s*\\.\\s*Parser\\s*\\(\\s*\\{\\s*explicitCharkey\\s*:[^}]*\\}\\s*\\)/i,\n message: 'xml2js parser instantiated – ensure external entity parsing is disabled',\n severity: 'medium',\n confidence: 'low',\n subcategory: 'xxe',\n ruleId: 'SEC-XXE-002',\n cwe: ['CWE-611'],\n title: 'XML Parser Misconfiguration',\n },\n {\n regex: /etree\\s*\\.\\s*parse\\s*\\(/i,\n message: 'Python xml.etree.ElementTree.parse used – vulnerable to XML attacks, use defusedxml instead',\n severity: 'medium',\n confidence: 'medium',\n subcategory: 'xxe',\n ruleId: 'SEC-XXE-003',\n cwe: ['CWE-611'],\n title: 'Unsafe Python XML Parser',\n },\n\n // ── SSRF (Server-Side Request Forgery) ──\n {\n regex: /axios\\s*\\.\\s*(?:get|post|request|put|delete)\\s*\\(\\s*(?:req|request|params|query|body|args|input|user|url)\\b/i,\n message: 'Axios request with user-controlled URL – vulnerable to Server-Side Request Forgery (SSRF)',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'ssrf',\n ruleId: 'SEC-SRF-001',\n cwe: ['CWE-918'],\n title: 'Server-Side Request Forgery (SSRF)',\n },\n {\n regex: /fetch\\s*\\(\\s*(?:req|request|params|query|body|args|input|user|url)\\b/i,\n message: 'Fetch request with user-controlled URL – vulnerable to SSRF',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'ssrf',\n ruleId: 'SEC-SRF-001',\n cwe: ['CWE-918'],\n title: 'Server-Side Request Forgery (SSRF)',\n },\n {\n regex: /urllib\\s*\\.\\s*(?:request\\s*\\.\\s*)?urlopen\\s*\\(\\s*(?:req|request|params|user_input|url)\\b/i,\n message: 'Python urlopen with potentially user-controlled URL – vulnerable to SSRF',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'ssrf',\n ruleId: 'SEC-SRF-002',\n cwe: ['CWE-918'],\n title: 'Server-Side Request Forgery (SSRF)',\n },\n {\n regex: /requests\\s*\\.\\s*(?:get|post|request)\\s*\\(\\s*(?:req|request|params|user_input|url)\\b/i,\n message: 'Python requests with user-controlled URL – vulnerable to SSRF',\n severity: 'critical',\n confidence: 'high',\n subcategory: 'ssrf',\n ruleId: 'SEC-SRF-002',\n cwe: ['CWE-918'],\n title: 'Server-Side Request Forgery (SSRF)',\n },\n {\n regex: /(?:HttpURLConnection|HttpClient)\\b.*(?:openStream|send|execute)/i,\n message: 'Java HTTP request instantiated – verify target URL is validated against SSRF',\n severity: 'high',\n confidence: 'low',\n subcategory: 'ssrf',\n ruleId: 'SEC-SRF-003',\n cwe: ['CWE-918'],\n title: 'Potential SSRF in Java',\n },\n\n // ── CORS Misconfiguration ──\n {\n regex: /Access-Control-Allow-Origin[\"']\\s*[\\s,:=]\\s*[\"']\\*[\"']/i,\n message: 'CORS wildcard (*) origin allowed – can expose API responses to unauthorized websites',\n severity: 'high',\n confidence: 'high',\n subcategory: 'cors',\n ruleId: 'SEC-COR-001',\n cwe: ['CWE-942'],\n title: 'Unsafe CORS Wildcard Configuration',\n },\n {\n regex: /origin\\s*:\\s*[\"']\\*[\"']/i,\n message: 'Express CORS middleware configured with wildcard origin',\n severity: 'medium',\n confidence: 'high',\n subcategory: 'cors',\n ruleId: 'SEC-COR-001',\n cwe: ['CWE-942'],\n title: 'Unsafe CORS Wildcard Configuration',\n },\n {\n regex: /Access-Control-Allow-Origin[\"']\\s*[\\s,:=]\\s*req\\.headers\\s*\\[\\s*[\"']origin[\"']\\s*\\]/i,\n message: 'CORS origin dynamically reflected from headers without validation',\n severity: 'critical',\n confidence: 'medium',\n subcategory: 'cors',\n ruleId: 'SEC-COR-002',\n cwe: ['CWE-942'],\n title: 'Unvalidated Dynamic CORS Origin',\n },\n\n // ── CSRF Misconfiguration ──\n {\n regex: /csrf\\s*\\(\\s*\\)\\s*\\.\\s*disable\\s*\\(\\s*\\)/i,\n message: 'CSRF protection explicitly disabled in Spring Security configuration',\n severity: 'high',\n confidence: 'high',\n subcategory: 'csrf',\n ruleId: 'SEC-CSRF-001',\n cwe: ['CWE-352'],\n title: 'CSRF Protection Disabled',\n },\n {\n regex: /csurf\\s*\\(\\s*\\)/i,\n message: 'csurf middleware usage detected',\n severity: 'low',\n confidence: 'high',\n subcategory: 'csrf',\n ruleId: 'SEC-CSRF-002',\n cwe: ['CWE-352'],\n title: 'CSRF Protection Enabled',\n },\n\n // ── Missing Rate Limiting ──\n {\n regex: /app\\.(?:post|get|put|delete)\\s*\\(\\s*[\"']\\/api\\/auth\\/login[\"']\\s*,\\s*(?!(?:[a-zA-Z0-9_]+Limit|limiter)\\b)/i,\n message: 'Sensitive login API endpoint defined without rate limiting middleware',\n severity: 'medium',\n confidence: 'high',\n subcategory: 'rate-limiting',\n ruleId: 'SEC-RAT-001',\n cwe: ['CWE-770'],\n title: 'Missing Rate Limiting on Login Endpoint',\n },\n {\n regex: /app\\.(?:post|get|put|delete)\\s*\\(\\s*[\"']\\/api\\/auth\\/register[\"']\\s*,\\s*(?!(?:[a-zA-Z0-9_]+Limit|limiter)\\b)/i,\n message: 'Sensitive registration API endpoint defined without rate limiting middleware',\n severity: 'medium',\n confidence: 'high',\n subcategory: 'rate-limiting',\n ruleId: 'SEC-RAT-001',\n cwe: ['CWE-770'],\n title: 'Missing Rate Limiting on Register Endpoint',\n },\n];\n\n/**\n * Analyze source code for API security vulnerabilities and misconfigurations.\n * Phân tích mã nguồn để phát hiện lỗi bảo mật API và cấu hình sai\n */\nexport function analyzeAPISec(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath } = context;\n\n if (content.length < 10) return findings;\n\n for (const pattern of API_SEC_PATTERNS) {\n const matches = matchPattern(content, pattern.regex);\n for (const match of matches) {\n // Skip matches in safe AST contexts (string literals, comments, imports, type annotations)\n if (context.tree && isInSafeASTContext(context.tree, match.line, match.column)) continue;\n\n // Skip comments\n const trimmed = match.lineContent.trimStart();\n if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('#') || trimmed.startsWith('/*')) {\n continue;\n }\n\n // Skip matches inside pattern/rule definition contexts\n if (isPatternDefinitionContext(match.lineContent, match.column)) continue;\n\n // Skip Java DocumentBuilderFactory / XMLInputFactory if safe features are explicitly configured\n if (pattern.subcategory === 'xxe' && pattern.ruleId === 'SEC-XXE-001') {\n if (\n content.includes('disallow-doctype-decl') ||\n (content.includes('external-general-entities') && content.includes('external-parameter-entities')) ||\n content.includes('SUPPORT_DTD') ||\n content.includes('IS_SUPPORTING_EXTERNAL_ENTITIES')\n ) {\n continue;\n }\n }\n\n // Skip SSRF if URL validation patterns are present in the file\n if (pattern.subcategory === 'ssrf' && (pattern.ruleId === 'SEC-SRF-001' || pattern.ruleId === 'SEC-SRF-002')) {\n if (\n content.includes('startsWith') ||\n content.includes('validate') ||\n content.includes('whitelist') ||\n content.includes('trusted')\n ) {\n continue;\n }\n }\n\n const snippet = extractSnippet(content, match.line);\n findings.push(\n createFinding({\n ruleId: pattern.ruleId,\n scanner: 'security',\n severity: pattern.severity,\n confidence: pattern.confidence,\n category: 'api-security',\n subcategory: pattern.subcategory,\n title: pattern.title,\n message: pattern.message,\n filePath,\n lineNumber: match.line,\n column: match.column,\n snippet,\n cwe: pattern.cwe,\n owasp: ['A02:2021', 'A05:2021'], // Mapped to OWASP Categories\n fix: {\n description: 'Configure appropriate server parameters, validate target URLs, enable CSRF protection, and limit API requests.',\n references: [\n 'https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html',\n 'https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html',\n 'https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html',\n ],\n },\n tags: ['api-security', pattern.subcategory],\n }),\n );\n }\n }\n\n return findings;\n}\n","// ─── Security Scanner ──────────────────────────────────────────────────────\n// Bộ quét bảo mật – điều phối tất cả các analyzer bảo mật\n// Orchestrator that runs all security analyzers and implements IScanner\n\nimport type { Finding, Severity } from '../../types/finding.js';\nimport type { IScanner, ScanFileContext } from '../../types/scanner.js';\nimport type { DeepScanConfig } from '../../types/config.js';\nimport { BaseScanner, createFinding } from '../base-scanner.js';\nimport { analyzeTaintFlow } from '../../core/taint-tracker.js';\n\n// Import all security analyzers\nimport { analyzeInjection } from './analyzers/injection.js';\nimport { analyzeXSS } from './analyzers/xss.js';\nimport { analyzeSecrets } from './analyzers/secrets.js';\nimport { analyzeAuth } from './analyzers/auth.js';\nimport { analyzeCrypto } from './analyzers/crypto.js';\nimport { analyzeFileOps } from './analyzers/file-ops.js';\nimport { analyzeAPISec } from './analyzers/api-sec.js';\n\n// ─── Analyzer Registry ────────────────────────────────────────────────────\n\ninterface SecurityAnalyzer {\n name: string;\n analyze: (context: ScanFileContext) => Finding[];\n}\n\n/** All registered security analyzers */\nconst ANALYZERS: SecurityAnalyzer[] = [\n { name: 'injection', analyze: analyzeInjection },\n { name: 'xss', analyze: analyzeXSS },\n { name: 'secrets', analyze: analyzeSecrets },\n { name: 'auth', analyze: analyzeAuth },\n { name: 'crypto', analyze: analyzeCrypto },\n { name: 'file-ops', analyze: analyzeFileOps },\n { name: 'api-sec', analyze: analyzeAPISec },\n];\n\nconst TAINT_METADATA: Record<string, { severity: Severity; cwe: string[]; title: string }> = {\n code_injection: { severity: 'critical', cwe: ['CWE-94'], title: 'Code Injection via Taint Flow' },\n command_injection: { severity: 'critical', cwe: ['CWE-78'], title: 'Command Injection via Taint Flow' },\n sql_injection: { severity: 'critical', cwe: ['CWE-89'], title: 'SQL Injection via Taint Flow' },\n xss: { severity: 'high', cwe: ['CWE-79'], title: 'Cross-Site Scripting (XSS) via Taint Flow' },\n path_traversal: { severity: 'high', cwe: ['CWE-22'], title: 'Path Traversal via Taint Flow' },\n deserialization: { severity: 'critical', cwe: ['CWE-502'], title: 'Insecure Deserialization via Taint Flow' },\n buffer_overflow: { severity: 'high', cwe: ['CWE-120'], title: 'Buffer Overflow via Taint Flow' },\n format_string: { severity: 'high', cwe: ['CWE-134'], title: 'Format String Vulnerability via Taint Flow' },\n file_inclusion: { severity: 'critical', cwe: ['CWE-98'], title: 'File Inclusion via Taint Flow' },\n};\n\n// ─── Security Scanner Class ───────────────────────────────────────────────\n\n/**\n * Security scanner engine that orchestrates all security analyzers.\n * Bộ quét bảo mật điều phối tất cả analyzer: injection, XSS, secrets, auth, crypto, file-ops, api-security\n */\nexport class SecurityScanner extends BaseScanner implements IScanner {\n name = 'SecurityScanner';\n type = 'security' as const;\n\n private enabledSeverities: Set<string> = new Set();\n\n async initialize(config: DeepScanConfig): Promise<void> {\n await super.initialize(config);\n\n // Store enabled severity levels for filtering\n if (config.scanners.security.severity?.length) {\n this.enabledSeverities = new Set(config.scanners.security.severity);\n } else {\n // Default: all severity levels\n this.enabledSeverities = new Set(['critical', 'high', 'medium', 'low']);\n }\n }\n\n /**\n * Scan a file through all security analyzers.\n * Quét tệp qua tất cả analyzer bảo mật\n */\n async scanFile(context: ScanFileContext): Promise<Finding[]> {\n // Skip if security scanning is disabled\n if (this.config && !this.config.scanners.security.enabled) {\n return [];\n }\n\n const allFindings: Finding[] = [];\n\n // Run each analyzer and collect findings\n for (const analyzer of ANALYZERS) {\n try {\n const findings = analyzer.analyze(context);\n allFindings.push(...findings);\n } catch (error) {\n // Log error but don't stop scanning\n // Ghi lỗi nhưng không dừng quét\n console.error(`[SecurityScanner] Error in ${analyzer.name} analyzer:`, error);\n }\n }\n\n // Run taint flow analysis if deep analysis is enabled\n if (context.config?.deep) {\n try {\n const taintResults = analyzeTaintFlow(context.content, context.filePath, context.language, context.tree);\n for (const res of taintResults) {\n if (!res.hasTaintedSink || res.flow.length === 0) continue;\n const sinkStep = res.flow[res.flow.length - 1];\n const loc = sinkStep.location;\n const meta = TAINT_METADATA[res.sinkType] || {\n severity: 'high' as Severity,\n cwe: [],\n title: `Taint Flow: ${res.sinkType.replace(/_/g, ' ').toUpperCase()}`,\n };\n\n const finding = createFinding({\n ruleId: `security/taint-${res.sinkType.replace(/_/g, '-')}`,\n scanner: 'security',\n severity: meta.severity,\n confidence: 'high',\n category: 'taint-flow',\n subcategory: res.sinkType,\n title: meta.title,\n message: `Tainted data from source \"${res.sourceType}\" reaches sink \"${res.sinkType}\" via propagator.`,\n filePath: context.filePath,\n lineNumber: loc.startLine,\n column: loc.startColumn,\n snippet: loc.snippet,\n cwe: meta.cwe,\n owasp: ['A03:2021'],\n fix: {\n description: `Sanitize the tainted value before passing it to ${res.sinkType}.`,\n references: [],\n },\n tags: ['taint-flow', 'security'],\n });\n finding.taintFlow = res.flow;\n allFindings.push(finding);\n }\n } catch (error) {\n console.error('[SecurityScanner] Error in taint flow analysis:', error);\n }\n }\n\n // Also run rule-based pattern matching if rules are provided\n if (context.rules.length > 0) {\n const securityRules = context.rules.filter(\n (r) => r.category && ['injection', 'xss', 'secrets', 'auth', 'crypto', 'file-ops', 'api-security'].includes(r.category),\n );\n if (securityRules.length > 0) {\n try {\n const ruleFindings = this.matchRulePatterns(context, securityRules);\n allFindings.push(...ruleFindings);\n } catch (error) {\n console.error('[SecurityScanner] Error in rule matching:', error);\n }\n }\n }\n\n // Filter by enabled severity levels\n const filteredFindings = allFindings.filter((f) => this.enabledSeverities.has(f.severity));\n\n // Deduplicate findings by fingerprint\n // Loại bỏ trùng lặp bằng fingerprint\n const seen = new Set<string>();\n const deduplicated: Finding[] = [];\n for (const finding of filteredFindings) {\n if (!seen.has(finding.metadata.fingerprint)) {\n seen.add(finding.metadata.fingerprint);\n deduplicated.push(finding);\n }\n }\n\n return deduplicated;\n }\n\n async destroy(): Promise<void> {\n await super.destroy();\n this.enabledSeverities.clear();\n }\n}\n","// ─── Complexity Analyzer ───────────────────────────────────────────────────\n// Phân tích độ phức tạp: cyclomatic, nesting depth, function length\n// Calculates cyclomatic complexity, detects deep nesting and long functions\n\nimport type { Finding } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport type { QualityThresholds } from '../../../types/config.js';\nimport { createFinding, extractSnippet } from '../../base-scanner.js';\n\n// ─── Default Thresholds ────────────────────────────────────────────────────\n\nconst DEFAULT_THRESHOLDS: QualityThresholds = {\n maxComplexity: 10,\n maxCognitiveComplexity: 15,\n maxFileLength: 500,\n maxFunctionLength: 50,\n maxNestingDepth: 4,\n minCommentRatio: 0.1,\n};\n\n// ─── Regex Patterns for Decision Points ────────────────────────────────────\n\n/** Decision point patterns that increase cyclomatic complexity */\nconst DECISION_POINT_PATTERNS: RegExp[] = [\n /\\bif\\s*\\(/, // if statements\n /\\belse\\s+if\\s*\\(/, // else if\n /\\bfor\\s*\\(/, // for loops\n /\\bwhile\\s*\\(/, // while loops\n /\\bdo\\s*\\{/, // do-while\n /\\bcase\\s+[^:]+:/, // switch case\n /\\bcatch\\s*\\(/, // catch blocks\n /\\?\\s*[^:]+\\s*:/, // ternary operator\n /\\?\\./, // optional chaining (counts as potential branch)\n /&&(?!=)/, // logical AND\n /\\|\\|(?!=)/, // logical OR\n /\\?\\?/, // nullish coalescing\n];\n\n/** Function declaration/expression patterns */\nconst FUNCTION_PATTERNS: RegExp[] = [\n /(?:function\\s+\\w+|(?:const|let|var)\\s+\\w+\\s*=\\s*(?:async\\s+)?function)\\s*\\(/,\n /(?:const|let|var)\\s+\\w+\\s*=\\s*(?:async\\s+)?\\([^)]*\\)\\s*=>/,\n /(?:const|let|var)\\s+\\w+\\s*=\\s*(?:async\\s+)?\\w+\\s*=>/,\n /(?:public|private|protected|static|async)\\s+\\w+\\s*\\([^)]*\\)\\s*(?::\\s*\\w+[<\\[\\]>|&\\s]*)?\\s*\\{/,\n /\\w+\\s*\\([^)]*\\)\\s*\\{/, // method shorthand\n /def\\s+\\w+\\s*\\(/, // Python function def\n];\n\n// ─── Nesting Depth Tracking ───────────────────────────────────────────────\n\ninterface NestingInfo {\n line: number;\n depth: number;\n}\n\n/**\n * Track nesting depth throughout the file.\n * Theo dõi độ sâu lồng nhau trong tệp\n */\nfunction calculateNestingDepths(lines: string[]): NestingInfo[] {\n const results: NestingInfo[] = [];\n let currentDepth = 0;\n let inMultiLineComment = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n\n // Track multi-line comments\n if (line.includes('/*') && !line.includes('*/')) {\n inMultiLineComment = true;\n }\n if (line.includes('*/')) {\n inMultiLineComment = false;\n continue;\n }\n if (inMultiLineComment || line.startsWith('//') || line.startsWith('#') || line.startsWith('*')) {\n results.push({ line: i + 1, depth: currentDepth });\n continue;\n }\n\n // Count braces to track depth\n const openBraces = (line.match(/\\{/g) || []).length;\n const closeBraces = (line.match(/\\}/g) || []).length;\n\n // Depth before processing this line (for accurate reporting)\n results.push({ line: i + 1, depth: currentDepth + openBraces });\n\n currentDepth += openBraces - closeBraces;\n if (currentDepth < 0) currentDepth = 0;\n }\n\n return results;\n}\n\n// ─── Function Extraction ───────────────────────────────────────────────────\n\ninterface FunctionInfo {\n name: string;\n startLine: number;\n endLine: number;\n complexity: number;\n lineCount: number;\n}\n\n/**\n * Extract functions and calculate their complexity.\n * Trích xuất hàm và tính độ phức tạp cyclomatic\n */\nfunction extractFunctions(lines: string[]): FunctionInfo[] {\n const functions: FunctionInfo[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trim();\n\n // Skip comments\n if (trimmed.startsWith('//') || trimmed.startsWith('#') || trimmed.startsWith('*') || trimmed.startsWith('/*')) {\n continue;\n }\n\n // Check if this line starts a function\n let funcName = '';\n for (const pattern of FUNCTION_PATTERNS) {\n const match = pattern.exec(trimmed);\n if (match) {\n // Try to extract function name\n const nameMatch = trimmed.match(/(?:function\\s+(\\w+)|(?:const|let|var)\\s+(\\w+)\\s*=|(\\w+)\\s*\\(|def\\s+(\\w+))/);\n funcName = nameMatch?.[1] || nameMatch?.[2] || nameMatch?.[3] || nameMatch?.[4] || 'anonymous';\n break;\n }\n }\n\n if (!funcName) continue;\n\n // Find the end of the function by tracking braces\n let braceCount = 0;\n let startedBody = false;\n let endLine = i;\n\n for (let j = i; j < lines.length; j++) {\n const currentLine = lines[j];\n for (const ch of currentLine) {\n if (ch === '{') {\n braceCount++;\n startedBody = true;\n } else if (ch === '}') {\n braceCount--;\n }\n }\n if (startedBody && braceCount <= 0) {\n endLine = j;\n break;\n }\n // Safety: don't look beyond 500 lines\n if (j - i > 500) {\n endLine = j;\n break;\n }\n }\n\n // For Python (indentation-based), estimate end by looking at indentation\n if (!startedBody && trimmed.startsWith('def ')) {\n const baseIndent = line.length - line.trimStart().length;\n endLine = i;\n for (let j = i + 1; j < lines.length; j++) {\n const jLine = lines[j];\n if (jLine.trim() === '') continue;\n const jIndent = jLine.length - jLine.trimStart().length;\n if (jIndent <= baseIndent && jLine.trim() !== '') break;\n endLine = j;\n }\n }\n\n // Calculate cyclomatic complexity for this function\n let complexity = 1; // Base complexity\n for (let j = i; j <= endLine; j++) {\n const funcLine = lines[j];\n for (const dpPattern of DECISION_POINT_PATTERNS) {\n const dpMatches = funcLine.match(new RegExp(dpPattern.source, 'g'));\n if (dpMatches) {\n complexity += dpMatches.length;\n }\n }\n }\n\n functions.push({\n name: funcName,\n startLine: i + 1,\n endLine: endLine + 1,\n complexity,\n lineCount: endLine - i + 1,\n });\n }\n\n return functions;\n}\n\n// ─── Main Analyzer Function ────────────────────────────────────────────────\n\n/**\n * Analyze source code for complexity issues.\n * Phân tích mã nguồn về vấn đề độ phức tạp\n */\nexport function analyzeComplexity(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath, config } = context;\n\n if (content.length < 10) return findings;\n\n const thresholds = config?.scanners?.quality?.thresholds ?? DEFAULT_THRESHOLDS;\n const lines = content.split('\\n');\n\n // Extract functions and analyze complexity\n const functions = extractFunctions(lines);\n\n for (const func of functions) {\n // Check cyclomatic complexity\n if (func.complexity > thresholds.maxComplexity) {\n const contextLines = 3;\n const snippet = extractSnippet(content, func.startLine, func.endLine, contextLines);\n const snippetStartLine = Math.max(1, func.startLine - contextLines);\n findings.push(\n createFinding({\n ruleId: 'QUA-CMPLX-001',\n scanner: 'quality',\n severity: func.complexity > thresholds.maxComplexity * 2 ? 'high' : 'medium',\n confidence: 'high',\n category: 'complexity',\n subcategory: 'cyclomatic',\n title: 'High Cyclomatic Complexity',\n message: `Function '${func.name}' has cyclomatic complexity of ${func.complexity} (threshold: ${thresholds.maxComplexity})`,\n filePath,\n lineNumber: func.startLine,\n endLine: func.endLine,\n snippet,\n snippetStartLine,\n tags: ['complexity', 'maintainability'],\n fix: {\n description: 'Refactor the function to reduce complexity. Extract helper functions, use early returns, or simplify conditional logic.',\n references: [],\n },\n }),\n );\n }\n\n // Check function length\n if (func.lineCount > thresholds.maxFunctionLength) {\n const contextLines = 3;\n const snippet = extractSnippet(content, func.startLine, func.endLine, contextLines);\n const snippetStartLine = Math.max(1, func.startLine - contextLines);\n findings.push(\n createFinding({\n ruleId: 'QUA-CMPLX-002',\n scanner: 'quality',\n severity: func.lineCount > thresholds.maxFunctionLength * 2 ? 'high' : 'medium',\n confidence: 'high',\n category: 'complexity',\n subcategory: 'function-length',\n title: 'Long Function',\n message: `Function '${func.name}' has ${func.lineCount} lines (threshold: ${thresholds.maxFunctionLength})`,\n filePath,\n lineNumber: func.startLine,\n endLine: func.endLine,\n snippet,\n snippetStartLine,\n tags: ['complexity', 'maintainability'],\n fix: {\n description: 'Break the function into smaller, focused functions. Each function should do one thing well.',\n references: [],\n },\n }),\n );\n }\n }\n\n // Check nesting depth\n const nestingInfos = calculateNestingDepths(lines);\n let lastReportedLine = -1;\n\n for (const info of nestingInfos) {\n if (info.depth > thresholds.maxNestingDepth && info.line - lastReportedLine > 5) {\n const lineContent = lines[info.line - 1]?.trim();\n // Only report on lines that actually introduce nesting\n if (lineContent && (lineContent.includes('{') || /^\\s*(?:if|for|while|switch|try)\\b/.test(lineContent))) {\n const snippet = extractSnippet(content, info.line);\n findings.push(\n createFinding({\n ruleId: 'QUA-CMPLX-003',\n scanner: 'quality',\n severity: info.depth > thresholds.maxNestingDepth + 2 ? 'high' : 'medium',\n confidence: 'high',\n category: 'complexity',\n subcategory: 'nesting-depth',\n title: 'Deep Nesting',\n message: `Code is nested ${info.depth} levels deep (threshold: ${thresholds.maxNestingDepth})`,\n filePath,\n lineNumber: info.line,\n snippet,\n tags: ['complexity', 'readability'],\n fix: {\n description: 'Reduce nesting by using early returns, guard clauses, or extracting logic into helper functions.',\n references: [],\n },\n }),\n );\n lastReportedLine = info.line;\n }\n }\n }\n\n return findings;\n}\n","// ─── Code Smells Analyzer ──────────────────────────────────────────────────\n// Phát hiện code smells: tệp dài, import chưa dùng, magic numbers, console logs\n// Detects long files, unused imports, magic numbers, console logs, TODO/FIXME, empty catch\n\nimport type { Finding, Severity } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport type { QualityThresholds } from '../../../types/config.js';\nimport { createFinding, extractSnippet } from '../../base-scanner.js';\n\n// ─── Default Thresholds ────────────────────────────────────────────────────\n\nconst DEFAULT_MAX_FILE_LENGTH = 500;\n\n// ─── Main Analyzer Function ────────────────────────────────────────────────\n\n/**\n * Analyze source code for code smells.\n * Phân tích mã nguồn để phát hiện code smells\n */\nexport function analyzeCodeSmells(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath, config } = context;\n\n if (content.length < 10) return findings;\n\n const thresholds = config?.scanners?.quality?.thresholds;\n const maxFileLength = thresholds?.maxFileLength ?? DEFAULT_MAX_FILE_LENGTH;\n\n const lines = content.split('\\n');\n\n // ── Detect long files ──\n findings.push(...detectLongFile(lines, filePath, content, maxFileLength));\n\n // ── Detect unused imports ──\n findings.push(...detectUnusedImports(lines, filePath, content));\n\n // ── Detect magic numbers ──\n findings.push(...detectMagicNumbers(lines, filePath, content));\n\n // ── Detect console.log / print statements ──\n findings.push(...detectConsoleLogs(lines, filePath, content));\n\n // ── Detect TODO/FIXME/HACK comments ──\n findings.push(...detectTodoComments(lines, filePath, content));\n\n // ── Detect empty catch blocks ──\n findings.push(...detectEmptyCatch(lines, filePath, content));\n\n return findings;\n}\n\n// ─── Long File Detection ───────────────────────────────────────────────────\n\nfunction detectLongFile(lines: string[], filePath: string, content: string, maxFileLength: number): Finding[] {\n if (lines.length <= maxFileLength) return [];\n\n const severity: Severity = lines.length > maxFileLength * 2 ? 'high' : 'medium';\n\n return [\n createFinding({\n ruleId: 'QUA-SMELL-001',\n scanner: 'quality',\n severity,\n confidence: 'high',\n category: 'code-smells',\n subcategory: 'long-file',\n title: 'File Too Long',\n message: `File has ${lines.length} lines (threshold: ${maxFileLength}). Consider splitting into smaller modules.`,\n filePath,\n lineNumber: 1,\n snippet: lines.slice(0, 5).join('\\n'),\n tags: ['code-smell', 'maintainability'],\n fix: {\n description: 'Split the file into smaller, focused modules. Group related functions and classes together.',\n references: [],\n },\n }),\n ];\n}\n\n// ─── Unused Import Detection ───────────────────────────────────────────────\n\n/**\n * Basic unused import detection using regex.\n * Checks if imported identifiers are used elsewhere in the file.\n * Phát hiện import chưa sử dụng bằng regex\n */\nfunction detectUnusedImports(lines: string[], filePath: string, content: string): Finding[] {\n const findings: Finding[] = [];\n const imports: Array<{ name: string; line: number }> = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Match ES import patterns: import { Foo, Bar } from '...'\n const namedImportMatch = line.match(/import\\s+\\{([^}]+)\\}\\s+from\\s+/);\n if (namedImportMatch) {\n const names = namedImportMatch[1].split(',').map((n) => {\n const parts = n.trim().split(/\\s+as\\s+/);\n return parts[parts.length - 1].trim(); // Use alias if present\n });\n for (const name of names) {\n if (name && name !== 'type') {\n imports.push({ name, line: i + 1 });\n }\n }\n }\n\n // Match default import: import Foo from '...'\n const defaultImportMatch = line.match(/import\\s+(\\w+)\\s+from\\s+/);\n if (defaultImportMatch && !line.includes('{')) {\n imports.push({ name: defaultImportMatch[1], line: i + 1 });\n }\n\n // Match Python import: from xxx import yyy\n const pyImportMatch = line.match(/from\\s+\\S+\\s+import\\s+(.+)/);\n if (pyImportMatch) {\n const names = pyImportMatch[1].split(',').map((n) => {\n const parts = n.trim().split(/\\s+as\\s+/);\n return parts[parts.length - 1].trim();\n });\n for (const name of names) {\n if (name) imports.push({ name, line: i + 1 });\n }\n }\n\n // Match Python import: import xxx\n const pySimpleImportMatch = line.match(/^import\\s+(\\w+)/);\n if (pySimpleImportMatch && !line.includes('from')) {\n imports.push({ name: pySimpleImportMatch[1], line: i + 1 });\n }\n }\n\n // Check which imports are used in the rest of the file (excluding import lines)\n const nonImportContent = lines\n .filter((l) => !/^\\s*(?:import|from)\\b/.test(l))\n .join('\\n');\n\n for (const imp of imports) {\n // Skip type-only imports (TypeScript)\n if (/import\\s+type\\b/.test(lines[imp.line - 1])) continue;\n\n // Check if the identifier is used anywhere in non-import code\n // Use word boundary to avoid false matches\n const usageRegex = new RegExp(`\\\\b${escapeRegex(imp.name)}\\\\b`);\n if (!usageRegex.test(nonImportContent)) {\n const snippet = extractSnippet(content, imp.line);\n findings.push(\n createFinding({\n ruleId: 'QUA-SMELL-002',\n scanner: 'quality',\n severity: 'low',\n confidence: 'medium',\n category: 'code-smells',\n subcategory: 'unused-import',\n title: 'Unused Import',\n message: `Import '${imp.name}' appears to be unused`,\n filePath,\n lineNumber: imp.line,\n snippet,\n tags: ['code-smell', 'dead-code'],\n fix: {\n description: 'Remove unused imports to keep the code clean and reduce bundle size.',\n references: [],\n },\n }),\n );\n }\n }\n\n return findings;\n}\n\n// ─── Magic Number Detection ────────────────────────────────────────────────\n\n/** Numbers that are commonly used and not considered \"magic\" */\nconst ALLOWED_NUMBERS = new Set([\n '0', '1', '2', '-1', '0.0', '1.0', '100', '0.5',\n '1000', '60', '24', '3600', '86400', // time-related\n '200', '201', '204', '301', '302', '400', '401', '403', '404', '500', // HTTP status codes\n '1024', '2048', '4096', '8192', // powers of 2\n]);\n\n/**\n * Detect magic numbers in code.\n * Phát hiện các số magic (không có tên biến mô tả)\n */\nfunction detectMagicNumbers(lines: string[], filePath: string, content: string): Finding[] {\n const findings: Finding[] = [];\n const magicNumberRegex = /(?<!\\w)(-?\\d+\\.?\\d*)\\b/g;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trim();\n\n // Skip comments, imports, const declarations (defining the constant), and enum values\n if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('#')) continue;\n if (/^\\s*(?:import|from|require)\\b/.test(line)) continue;\n if (/^\\s*(?:const|final|static)\\s+\\w+\\s*[:=]/.test(line)) continue;\n if (/^\\s*(?:export\\s+)?(?:const|enum)\\b/.test(line)) continue;\n // Skip array indices, common patterns\n if (/\\[\\s*\\d+\\s*\\]/.test(trimmed)) continue;\n\n const regex = new RegExp(magicNumberRegex.source, magicNumberRegex.flags);\n let m: RegExpExecArray | null;\n while ((m = regex.exec(line)) !== null) {\n const num = m[1];\n if (ALLOWED_NUMBERS.has(num)) continue;\n // Skip if it's part of a string literal\n const before = line.substring(0, m.index);\n const singleQuotes = (before.match(/'/g) || []).length;\n const doubleQuotes = (before.match(/\"/g) || []).length;\n const backticks = (before.match(/`/g) || []).length;\n if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0 || backticks % 2 !== 0) continue;\n // Skip version numbers (e.g., \"1.2.3\")\n if (/\\d+\\.\\d+\\.\\d+/.test(line.substring(Math.max(0, m.index - 5), m.index + num.length + 5))) continue;\n\n // Skip numbers that are small integers\n const numVal = parseFloat(num);\n if (Number.isNaN(numVal) || (numVal >= -2 && numVal <= 10)) continue;\n\n const snippet = extractSnippet(content, i + 1);\n findings.push(\n createFinding({\n ruleId: 'QUA-SMELL-003',\n scanner: 'quality',\n severity: 'low',\n confidence: 'low',\n category: 'code-smells',\n subcategory: 'magic-number',\n title: 'Magic Number',\n message: `Magic number ${num} – consider extracting to a named constant for readability`,\n filePath,\n lineNumber: i + 1,\n column: m.index + 1,\n snippet,\n tags: ['code-smell', 'readability'],\n fix: {\n description: 'Extract magic numbers into named constants to improve readability and maintainability.',\n references: [],\n },\n }),\n );\n\n if (m.index === regex.lastIndex) regex.lastIndex++;\n }\n }\n\n return findings;\n}\n\n// ─── Console Log Detection ─────────────────────────────────────────────────\n\n/**\n * Detect console.log/print statements left in code.\n * Phát hiện console.log/print còn sót trong mã nguồn\n */\nfunction detectConsoleLogs(lines: string[], filePath: string, content: string): Finding[] {\n const findings: Finding[] = [];\n const consolePattern = /\\bconsole\\.(?:log|debug|info|warn|error|trace|dir|table)\\s*\\(/;\n const printPattern = /\\b(?:print|println|puts|NSLog|System\\.out\\.print(?:ln)?)\\s*\\(/;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trim();\n\n // Skip comments\n if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('#')) continue;\n\n let match = consolePattern.exec(trimmed);\n if (!match) match = printPattern.exec(trimmed);\n\n if (match) {\n const snippet = extractSnippet(content, i + 1);\n findings.push(\n createFinding({\n ruleId: 'QUA-SMELL-004',\n scanner: 'quality',\n severity: 'low',\n confidence: 'medium',\n category: 'code-smells',\n subcategory: 'console-log',\n title: 'Console/Print Statement',\n message: 'Debug logging statement found – consider using a proper logger or removing before production',\n filePath,\n lineNumber: i + 1,\n column: match.index + 1,\n snippet,\n tags: ['code-smell', 'debug'],\n fix: {\n description: 'Replace console.log/print with a structured logging library (e.g., winston, pino, log4j).',\n references: [],\n },\n }),\n );\n }\n }\n\n return findings;\n}\n\n// ─── TODO/FIXME/HACK Comment Detection ─────────────────────────────────────\n\n/**\n * Detect TODO, FIXME, HACK, XXX, BUG comments.\n * Phát hiện các comment TODO/FIXME/HACK\n */\nfunction detectTodoComments(lines: string[], filePath: string, content: string): Finding[] {\n const findings: Finding[] = [];\n const todoPattern = /\\b(TODO|FIXME|HACK|XXX|BUG|TEMP|WORKAROUND)\\b[:\\s]*(.*)/i;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const match = todoPattern.exec(line);\n\n if (match) {\n const tag = match[1].toUpperCase();\n const description = match[2]?.trim() || '';\n const severity: Severity = tag === 'FIXME' || tag === 'BUG' ? 'medium' : 'low';\n\n const snippet = extractSnippet(content, i + 1);\n findings.push(\n createFinding({\n ruleId: 'QUA-SMELL-005',\n scanner: 'quality',\n severity,\n confidence: 'high',\n category: 'code-smells',\n subcategory: 'todo-comment',\n title: `${tag} Comment`,\n message: `${tag} comment found${description ? ': ' + description : ''}`,\n filePath,\n lineNumber: i + 1,\n column: (match.index ?? 0) + 1,\n snippet,\n tags: ['code-smell', 'technical-debt', tag.toLowerCase()],\n }),\n );\n }\n }\n\n return findings;\n}\n\n// ─── Empty Catch Block Detection ───────────────────────────────────────────\n\n/**\n * Detect empty catch blocks that silently swallow exceptions.\n * Phát hiện khối catch rỗng\n */\nfunction detectEmptyCatch(lines: string[], filePath: string, content: string): Finding[] {\n const findings: Finding[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n\n // Match catch block\n if (/\\bcatch\\s*\\(/.test(line)) {\n // Check if the catch block is empty\n // Pattern 1: catch (...) { } on same line\n if (/catch\\s*\\([^)]*\\)\\s*\\{\\s*\\}/.test(line)) {\n const snippet = extractSnippet(content, i + 1);\n findings.push(createEmptyCatchFinding(filePath, i + 1, snippet));\n continue;\n }\n\n // Pattern 2: catch on one line, empty body on next lines\n if (i + 1 < lines.length) {\n const nextLine = lines[i + 1]?.trim();\n const nextNextLine = lines[i + 2]?.trim();\n\n // catch (...) {\n // }\n if (nextLine === '}' || (nextLine === '' && nextNextLine === '}')) {\n const snippet = extractSnippet(content, i + 1);\n findings.push(createEmptyCatchFinding(filePath, i + 1, snippet));\n }\n }\n }\n }\n\n return findings;\n}\n\nfunction createEmptyCatchFinding(filePath: string, line: number, snippet: string): Finding {\n return createFinding({\n ruleId: 'QUA-SMELL-006',\n scanner: 'quality',\n severity: 'medium',\n confidence: 'high',\n category: 'code-smells',\n subcategory: 'empty-catch',\n title: 'Empty Catch Block',\n message: 'Empty catch block silently swallows exceptions – at minimum, log the error',\n filePath,\n lineNumber: line,\n snippet,\n tags: ['code-smell', 'error-handling'],\n fix: {\n description: 'Add error handling logic to the catch block. At minimum, log the error. If intentionally ignoring, add a comment explaining why.',\n references: [],\n },\n });\n}\n\n// ─── Utility ───────────────────────────────────────────────────────────────\n\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n","// ─── Duplication Analyzer ──────────────────────────────────────────────────\n// Phát hiện mã nguồn trùng lặp sử dụng token-based comparison\n// Token-based code duplication detection\n\nimport type { Finding } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport { createFinding, extractSnippet } from '../../base-scanner.js';\n\n// ─── Configuration ─────────────────────────────────────────────────────────\n\n/** Default minimum number of lines for a block to be considered a duplicate */\nconst DEFAULT_MIN_LINES = 6;\n\n/** Default minimum token count for a match */\nconst DEFAULT_MIN_TOKENS = 30;\n\n// ─── Token Normalization ───────────────────────────────────────────────────\n\n/**\n * Normalize a line of code into a token sequence.\n * Removes whitespace, comments, and normalizes identifiers to detect structural duplicates.\n * Chuẩn hóa dòng mã thành chuỗi token\n */\nfunction tokenizeLine(line: string): string {\n let normalized = line.trim();\n\n // Remove single-line comments\n normalized = normalized.replace(/\\/\\/.*$/, '');\n normalized = normalized.replace(/#.*$/, '');\n\n // Remove inline comments\n normalized = normalized.replace(/\\/\\*.*?\\*\\//g, '');\n\n // Normalize whitespace\n normalized = normalized.replace(/\\s+/g, ' ').trim();\n\n // Skip empty lines after normalization\n if (normalized.length === 0) return '';\n\n // Normalize string literals to a placeholder\n normalized = normalized.replace(/\"[^\"]*\"/g, '\"STR\"');\n normalized = normalized.replace(/'[^']*'/g, \"'STR'\");\n normalized = normalized.replace(/`[^`]*`/g, '`STR`');\n\n // Normalize numeric literals\n normalized = normalized.replace(/\\b\\d+\\.?\\d*\\b/g, 'NUM');\n\n return normalized;\n}\n\n// ─── Block Hashing ─────────────────────────────────────────────────────────\n\ninterface CodeBlock {\n startLine: number;\n endLine: number;\n hash: string;\n tokenCount: number;\n}\n\n/**\n * Generate rolling hashes for blocks of normalized code.\n * Tạo hash cuốn cho các khối mã đã chuẩn hóa\n */\nfunction generateBlocks(lines: string[], minLines: number): CodeBlock[] {\n const blocks: CodeBlock[] = [];\n const tokenizedLines: Array<{ line: number; tokens: string }> = [];\n\n // Tokenize each line, skipping empty and trivial lines\n for (let i = 0; i < lines.length; i++) {\n const tokens = tokenizeLine(lines[i]);\n if (tokens.length > 0 && tokens !== '}' && tokens !== '{' && tokens !== ');') {\n tokenizedLines.push({ line: i + 1, tokens });\n }\n }\n\n // Create sliding windows of minLines\n for (let i = 0; i <= tokenizedLines.length - minLines; i++) {\n const blockTokens: string[] = [];\n let totalTokenCount = 0;\n\n for (let j = 0; j < minLines; j++) {\n blockTokens.push(tokenizedLines[i + j].tokens);\n totalTokenCount += tokenizedLines[i + j].tokens.split(' ').length;\n }\n\n const hash = blockTokens.join('\\n');\n blocks.push({\n startLine: tokenizedLines[i].line,\n endLine: tokenizedLines[i + minLines - 1].line,\n hash,\n tokenCount: totalTokenCount,\n });\n }\n\n return blocks;\n}\n\n// ─── Duplicate Detection ───────────────────────────────────────────────────\n\ninterface DuplicatePair {\n blockA: CodeBlock;\n blockB: CodeBlock;\n}\n\n/**\n * Find duplicate blocks within a file.\n * Tìm các khối mã trùng lặp trong tệp\n */\nfunction findDuplicates(blocks: CodeBlock[], minTokens: number): DuplicatePair[] {\n const hashMap = new Map<string, CodeBlock[]>();\n const duplicates: DuplicatePair[] = [];\n\n for (const block of blocks) {\n if (block.tokenCount < minTokens) continue;\n\n const existing = hashMap.get(block.hash);\n if (existing) {\n existing.push(block);\n } else {\n hashMap.set(block.hash, [block]);\n }\n }\n\n // Track reported line ranges to avoid overlapping reports\n const reportedRanges = new Set<string>();\n\n for (const [, blockGroup] of hashMap) {\n if (blockGroup.length < 2) continue;\n\n // Report pairs (only report first duplicate pair per unique block)\n for (let i = 0; i < blockGroup.length - 1; i++) {\n for (let j = i + 1; j < blockGroup.length; j++) {\n const blockA = blockGroup[i];\n const blockB = blockGroup[j];\n\n // Skip overlapping blocks\n if (\n (blockA.startLine >= blockB.startLine && blockA.startLine <= blockB.endLine) ||\n (blockB.startLine >= blockA.startLine && blockB.startLine <= blockA.endLine)\n ) {\n continue;\n }\n\n const rangeKey = `${blockA.startLine}-${blockA.endLine}:${blockB.startLine}-${blockB.endLine}`;\n const reverseKey = `${blockB.startLine}-${blockB.endLine}:${blockA.startLine}-${blockA.endLine}`;\n\n if (reportedRanges.has(rangeKey) || reportedRanges.has(reverseKey)) continue;\n\n reportedRanges.add(rangeKey);\n duplicates.push({ blockA, blockB });\n }\n }\n }\n\n return duplicates;\n}\n\n// ─── Main Analyzer Function ────────────────────────────────────────────────\n\n/**\n * Analyze source code for duplicated blocks.\n * Phân tích mã nguồn để tìm các khối mã trùng lặp\n */\nexport function analyzeDuplication(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath } = context;\n\n if (content.length < 100) return findings;\n\n const lines = content.split('\\n');\n\n // Skip very short files\n if (lines.length < DEFAULT_MIN_LINES * 2) return findings;\n\n // Generate normalized code blocks\n const blocks = generateBlocks(lines, DEFAULT_MIN_LINES);\n\n // Find duplicates\n const duplicates = findDuplicates(blocks, DEFAULT_MIN_TOKENS);\n\n // Cap the number of findings per file to avoid noise\n const maxFindings = 10;\n const limitedDuplicates = duplicates.slice(0, maxFindings);\n\n for (const dup of limitedDuplicates) {\n const snippet = extractSnippet(content, dup.blockA.startLine, dup.blockA.endLine, 1);\n const snippetStartLine = Math.max(1, dup.blockA.startLine - 1);\n const lineCount = dup.blockA.endLine - dup.blockA.startLine + 1;\n\n findings.push(\n createFinding({\n ruleId: 'QUA-DUP-001',\n scanner: 'quality',\n severity: lineCount > 20 ? 'medium' : 'low',\n confidence: 'high',\n category: 'duplication',\n subcategory: 'code-clone',\n title: 'Duplicated Code Block',\n message: `Duplicated code block (${lineCount} lines): lines ${dup.blockA.startLine}-${dup.blockA.endLine} and lines ${dup.blockB.startLine}-${dup.blockB.endLine}`,\n filePath,\n lineNumber: dup.blockA.startLine,\n endLine: dup.blockA.endLine,\n snippet,\n snippetStartLine,\n tags: ['duplication', 'maintainability'],\n fix: {\n description: 'Extract the duplicated code into a shared function or utility. Follow the DRY principle.',\n references: [],\n },\n }),\n );\n }\n\n return findings;\n}\n","// ─── Metrics Analyzer ──────────────────────────────────────────────────────\n// Tính toán các chỉ số code: LOC, comment ratio, blank lines\n// Calculate lines of code, comment ratio, and generate warnings\n\nimport type { Finding } from '../../../types/finding.js';\nimport type { ScanFileContext } from '../../../types/scanner.js';\nimport type { QualityThresholds } from '../../../types/config.js';\nimport { createFinding } from '../../base-scanner.js';\n\n// ─── Default Thresholds ────────────────────────────────────────────────────\n\nconst DEFAULT_MIN_COMMENT_RATIO = 0.1;\n\n// ─── Metrics Interface ────────────────────────────────────────────────────\n\nexport interface CodeMetrics {\n totalLines: number;\n codeLines: number;\n commentLines: number;\n blankLines: number;\n commentRatio: number;\n}\n\n// ─── Comment Patterns ──────────────────────────────────────────────────────\n\ninterface CommentPatterns {\n singleLine: RegExp[];\n multiLineStart: RegExp;\n multiLineEnd: RegExp;\n}\n\n/** Get comment patterns based on file language */\nfunction getCommentPatterns(language: string): CommentPatterns {\n switch (language) {\n case 'python':\n return {\n singleLine: [/^\\s*#/],\n multiLineStart: /^\\s*(?:\"\"\"|''')/,\n multiLineEnd: /(?:\"\"\"|''')\\s*$/,\n };\n case 'html':\n case 'xml':\n return {\n singleLine: [],\n multiLineStart: /^\\s*<!--/,\n multiLineEnd: /-->\\s*$/,\n };\n case 'css':\n case 'scss':\n case 'less':\n return {\n singleLine: [/^\\s*\\/\\//],\n multiLineStart: /^\\s*\\/\\*/,\n multiLineEnd: /\\*\\/\\s*$/,\n };\n case 'ruby':\n return {\n singleLine: [/^\\s*#/],\n multiLineStart: /^\\s*=begin/,\n multiLineEnd: /^\\s*=end/,\n };\n case 'lua':\n return {\n singleLine: [/^\\s*--(?!\\[)/],\n multiLineStart: /^\\s*--\\[\\[/,\n multiLineEnd: /\\]\\]/,\n };\n // JavaScript, TypeScript, Java, C, C++, C#, Go, Rust, PHP, Swift, Kotlin\n default:\n return {\n singleLine: [/^\\s*\\/\\//, /^\\s*\\*/],\n multiLineStart: /^\\s*\\/\\*/,\n multiLineEnd: /\\*\\/\\s*$/,\n };\n }\n}\n\n// ─── Metric Calculation ────────────────────────────────────────────────────\n\n/**\n * Calculate code metrics for the given source.\n * Tính toán các chỉ số code cho mã nguồn\n */\nexport function calculateMetrics(content: string, language: string): CodeMetrics {\n const lines = content.split('\\n');\n const patterns = getCommentPatterns(language);\n\n let codeLines = 0;\n let commentLines = 0;\n let blankLines = 0;\n let inMultiLineComment = false;\n\n for (const line of lines) {\n const trimmed = line.trim();\n\n // Blank line\n if (trimmed.length === 0) {\n blankLines++;\n continue;\n }\n\n // Multi-line comment handling\n if (inMultiLineComment) {\n commentLines++;\n if (patterns.multiLineEnd.test(trimmed)) {\n inMultiLineComment = false;\n }\n continue;\n }\n\n // Check for multi-line comment start\n if (patterns.multiLineStart.test(trimmed)) {\n commentLines++;\n // Check if multi-line comment ends on same line\n if (!patterns.multiLineEnd.test(trimmed) || trimmed === '/**/') {\n // For patterns where start and end are the same (Python docstrings)\n if (patterns.multiLineStart.source === patterns.multiLineEnd.source) {\n // Count opening triple-quotes on the line\n const startMatches = trimmed.match(patterns.multiLineStart);\n if (startMatches && (trimmed.match(/\"\"\"/g) || []).length < 2 && (trimmed.match(/'''/g) || []).length < 2) {\n inMultiLineComment = true;\n }\n } else if (!patterns.multiLineEnd.test(trimmed.substring(trimmed.indexOf('/*') + 2))) {\n inMultiLineComment = true;\n }\n }\n continue;\n }\n\n // Single-line comment\n let isComment = false;\n for (const singlePattern of patterns.singleLine) {\n if (singlePattern.test(trimmed)) {\n commentLines++;\n isComment = true;\n break;\n }\n }\n if (isComment) continue;\n\n // Code line (may contain inline comment but still counts as code)\n codeLines++;\n }\n\n const totalLines = lines.length;\n const commentRatio = totalLines > 0 ? commentLines / totalLines : 0;\n\n return {\n totalLines,\n codeLines,\n commentLines,\n blankLines,\n commentRatio,\n };\n}\n\n// ─── Main Analyzer Function ────────────────────────────────────────────────\n\n/**\n * Analyze source code and calculate metrics, generating findings if thresholds are breached.\n * Phân tích mã nguồn, tính toán chỉ số và tạo finding nếu vượt ngưỡng\n */\nexport function analyzeMetrics(context: ScanFileContext): Finding[] {\n const findings: Finding[] = [];\n const { content, filePath, language, config } = context;\n\n if (content.length < 10) return findings;\n\n const thresholds = config?.scanners?.quality?.thresholds;\n const minCommentRatio = thresholds?.minCommentRatio ?? DEFAULT_MIN_COMMENT_RATIO;\n\n const metrics = calculateMetrics(content, language);\n\n // Generate info finding with metrics summary\n findings.push(\n createFinding({\n ruleId: 'QUA-METRICS-001',\n scanner: 'quality',\n severity: 'low',\n confidence: 'high',\n category: 'metrics',\n subcategory: 'code-metrics',\n title: 'Code Metrics',\n message: `Lines: ${metrics.totalLines} total, ${metrics.codeLines} code, ${metrics.commentLines} comments, ${metrics.blankLines} blank. Comment ratio: ${(metrics.commentRatio * 100).toFixed(1)}%`,\n filePath,\n lineNumber: 1,\n snippet: '',\n tags: ['metrics'],\n }),\n );\n\n // Warn if comment ratio is below threshold (only for files with enough code)\n if (metrics.codeLines > 50 && metrics.commentRatio < minCommentRatio) {\n findings.push(\n createFinding({\n ruleId: 'QUA-METRICS-002',\n scanner: 'quality',\n severity: 'low',\n confidence: 'medium',\n category: 'metrics',\n subcategory: 'comment-ratio',\n title: 'Low Comment Ratio',\n message: `Comment ratio is ${(metrics.commentRatio * 100).toFixed(1)}% (threshold: ${(minCommentRatio * 100).toFixed(1)}%). Consider adding documentation comments.`,\n filePath,\n lineNumber: 1,\n snippet: '',\n tags: ['metrics', 'documentation'],\n fix: {\n description: 'Add JSDoc/docstring comments to exported functions, classes, and complex logic. Focus on \"why\" rather than \"what\".',\n references: [],\n },\n }),\n );\n }\n\n return findings;\n}\n","import type { Finding } from '../../types/finding.js';\nimport type { ScanFileContext, IScanner } from '../../types/scanner.js';\nimport type { DeepScanConfig } from '../../types/config.js';\nimport { analyzeComplexity } from './analyzers/complexity.js';\nimport { analyzeCodeSmells } from './analyzers/code-smells.js';\nimport { analyzeDuplication } from './analyzers/duplication.js';\nimport { analyzeMetrics } from './analyzers/metrics.js';\n\n/**\n * Quality Scanner - Orchestrates all code quality analyzers\n *\n * Analyzers:\n * - Complexity: cyclomatic complexity, nesting depth, function length\n * - Code Smells: long files, magic numbers, empty catch, console.log, TODO/FIXME\n * - Duplication: token-based duplicate code detection\n * - Metrics: LOC, comment ratio\n */\nexport class QualityScanner implements IScanner {\n name = 'QualityScanner';\n type = 'quality' as const;\n private config!: DeepScanConfig;\n\n async initialize(config: DeepScanConfig): Promise<void> {\n this.config = config;\n }\n\n async scanFile(context: ScanFileContext): Promise<Finding[]> {\n const findings: Finding[] = [];\n\n if (!context.content || context.content.trim().length === 0) return findings;\n\n try {\n const complexityFindings = analyzeComplexity(context);\n findings.push(...complexityFindings);\n } catch {\n // Skip on error\n }\n\n try {\n const smellFindings = analyzeCodeSmells(context);\n findings.push(...smellFindings);\n } catch {\n // Skip on error\n }\n\n try {\n const dupFindings = analyzeDuplication(context);\n findings.push(...dupFindings);\n } catch {\n // Skip on error\n }\n\n try {\n const metricFindings = analyzeMetrics(context);\n findings.push(...metricFindings);\n } catch {\n // Skip on error\n }\n\n return findings;\n }\n\n async destroy(): Promise<void> {\n // No cleanup needed\n }\n}\n","import { basename } from 'node:path';\n\n/**\n * Dependency information extracted from a manifest file\n */\nexport interface DependencyInfo {\n name: string;\n version: string;\n ecosystem: string;\n lineNumber?: number;\n isDev?: boolean;\n}\n\n/**\n * Parse dependencies from a manifest file\n */\nexport function parseDependencies(content: string, filePath: string): DependencyInfo[] {\n const fileName = basename(filePath).toLowerCase();\n\n switch (fileName) {\n case 'package.json':\n return parsePackageJson(content);\n case 'package-lock.json':\n return parsePackageLockJson(content);\n case 'requirements.txt':\n return parseRequirementsTxt(content);\n case 'pipfile':\n case 'pipfile.lock':\n return parsePipfile(content, fileName);\n case 'go.mod':\n return parseGoMod(content);\n case 'pom.xml':\n return parsePomXml(content);\n case 'build.gradle':\n case 'build.gradle.kts':\n return parseGradle(content);\n case 'cargo.toml':\n return parseCargoToml(content);\n case 'gemfile':\n case 'gemfile.lock':\n return parseGemfile(content, fileName);\n case 'composer.json':\n case 'composer.lock':\n return parseComposerJson(content, fileName);\n case 'pyproject.toml':\n return parsePyprojectToml(content);\n default:\n return [];\n }\n}\n\n/**\n * Parse package.json (npm/yarn)\n */\nfunction parsePackageJson(content: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n try {\n const pkg = JSON.parse(content);\n\n if (pkg.dependencies) {\n for (const [name, version] of Object.entries(pkg.dependencies)) {\n deps.push({\n name,\n version: cleanVersion(version as string),\n ecosystem: 'npm',\n isDev: false,\n });\n }\n }\n\n if (pkg.devDependencies) {\n for (const [name, version] of Object.entries(pkg.devDependencies)) {\n deps.push({\n name,\n version: cleanVersion(version as string),\n ecosystem: 'npm',\n isDev: true,\n });\n }\n }\n } catch {\n // Invalid JSON\n }\n return deps;\n}\n\n/**\n * Parse package-lock.json\n */\nfunction parsePackageLockJson(content: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n try {\n const lockfile = JSON.parse(content);\n const packages = lockfile.packages || lockfile.dependencies || {};\n\n for (const [path, info] of Object.entries(packages)) {\n const pkg = info as Record<string, unknown>;\n if (!path || path === '') continue; // Skip root\n const name = path.replace(/^node_modules\\//, '');\n if (pkg.version) {\n deps.push({\n name,\n version: pkg.version as string,\n ecosystem: 'npm',\n isDev: pkg.dev === true,\n });\n }\n }\n } catch {\n // Invalid JSON\n }\n return deps;\n}\n\n/**\n * Parse requirements.txt (Python)\n */\nfunction parseRequirementsTxt(content: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n if (!line || line.startsWith('#') || line.startsWith('-')) continue;\n\n // Match patterns: package==1.0.0, package>=1.0.0, package~=1.0.0\n const match = line.match(/^([a-zA-Z0-9_.-]+)\\s*(?:[=~!<>]=?\\s*)([a-zA-Z0-9_.*-]+)?/);\n if (match) {\n deps.push({\n name: match[1],\n version: match[2] || '*',\n ecosystem: 'PyPI',\n lineNumber: i + 1,\n });\n }\n }\n return deps;\n}\n\n/**\n * Parse Pipfile/Pipfile.lock\n */\nfunction parsePipfile(content: string, fileName: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n\n if (fileName === 'pipfile.lock') {\n try {\n const lockfile = JSON.parse(content);\n for (const section of ['default', 'develop']) {\n const packages = lockfile[section] || {};\n for (const [name, info] of Object.entries(packages)) {\n const pkg = info as Record<string, unknown>;\n deps.push({\n name,\n version: cleanVersion((pkg.version || '*') as string),\n ecosystem: 'PyPI',\n isDev: section === 'develop',\n });\n }\n }\n } catch {\n // Invalid JSON\n }\n } else {\n // Basic TOML-like parsing for Pipfile\n let inPackages = false;\n let isDev = false;\n const lines = content.split('\\n');\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed === '[packages]') { inPackages = true; isDev = false; continue; }\n if (trimmed === '[dev-packages]') { inPackages = true; isDev = true; continue; }\n if (trimmed.startsWith('[')) { inPackages = false; continue; }\n\n if (inPackages) {\n const match = trimmed.match(/^([a-zA-Z0-9_.-]+)\\s*=\\s*\"?([^\"]*)\"?/);\n if (match) {\n deps.push({\n name: match[1],\n version: cleanVersion(match[2]),\n ecosystem: 'PyPI',\n isDev,\n });\n }\n }\n }\n }\n return deps;\n}\n\n/**\n * Parse go.mod (Go)\n */\nfunction parseGoMod(content: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n const lines = content.split('\\n');\n let inRequire = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n\n if (line === 'require (') {\n inRequire = true;\n continue;\n }\n if (line === ')') {\n inRequire = false;\n continue;\n }\n\n // Single-line require\n const singleMatch = line.match(/^require\\s+(\\S+)\\s+(\\S+)/);\n if (singleMatch) {\n deps.push({\n name: singleMatch[1],\n version: singleMatch[2],\n ecosystem: 'Go',\n lineNumber: i + 1,\n });\n continue;\n }\n\n // Multi-line require block\n if (inRequire) {\n const match = line.match(/^\\s*(\\S+)\\s+(\\S+)/);\n if (match && !match[1].startsWith('//')) {\n deps.push({\n name: match[1],\n version: match[2],\n ecosystem: 'Go',\n lineNumber: i + 1,\n });\n }\n }\n }\n return deps;\n}\n\n/**\n * Parse pom.xml (Maven) - basic regex parsing\n */\nfunction parsePomXml(content: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n const depRegex = /<dependency>\\s*<groupId>([^<]+)<\\/groupId>\\s*<artifactId>([^<]+)<\\/artifactId>\\s*(?:<version>([^<]+)<\\/version>)?/g;\n\n let match;\n while ((match = depRegex.exec(content)) !== null) {\n deps.push({\n name: `${match[1]}:${match[2]}`,\n version: match[3] || '*',\n ecosystem: 'Maven',\n });\n }\n return deps;\n}\n\n/**\n * Parse build.gradle / build.gradle.kts\n */\nfunction parseGradle(content: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n // Match: implementation 'group:artifact:version'\n const gradleRegex = /(?:implementation|api|compileOnly|runtimeOnly|testImplementation)\\s*[('\"]([^:'\"]+):([^:'\"]+):([^'\")\\s]+)/g;\n\n let match;\n while ((match = gradleRegex.exec(content)) !== null) {\n deps.push({\n name: `${match[1]}:${match[2]}`,\n version: match[3],\n ecosystem: 'Maven',\n });\n }\n return deps;\n}\n\n/**\n * Parse Cargo.toml (Rust)\n */\nfunction parseCargoToml(content: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n let inDeps = false;\n let isDev = false;\n const lines = content.split('\\n');\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed === '[dependencies]') { inDeps = true; isDev = false; continue; }\n if (trimmed === '[dev-dependencies]') { inDeps = true; isDev = true; continue; }\n if (trimmed.startsWith('[') && trimmed !== '[dependencies]' && trimmed !== '[dev-dependencies]') {\n inDeps = false; continue;\n }\n\n if (inDeps) {\n // Simple: package = \"version\"\n const simpleMatch = trimmed.match(/^([a-zA-Z0-9_-]+)\\s*=\\s*\"([^\"]+)\"/);\n if (simpleMatch) {\n deps.push({\n name: simpleMatch[1],\n version: cleanVersion(simpleMatch[2]),\n ecosystem: 'crates.io',\n isDev,\n });\n continue;\n }\n\n // Complex: package = { version = \"1.0\", features = [...] }\n const complexMatch = trimmed.match(/^([a-zA-Z0-9_-]+)\\s*=\\s*\\{.*version\\s*=\\s*\"([^\"]+)\"/);\n if (complexMatch) {\n deps.push({\n name: complexMatch[1],\n version: cleanVersion(complexMatch[2]),\n ecosystem: 'crates.io',\n isDev,\n });\n }\n }\n }\n return deps;\n}\n\n/**\n * Parse Gemfile/Gemfile.lock (Ruby)\n */\nfunction parseGemfile(content: string, fileName: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n\n if (fileName === 'gemfile.lock') {\n // Parse Gemfile.lock specs section\n let inSpecs = false;\n for (const line of content.split('\\n')) {\n if (line.trim() === 'specs:') { inSpecs = true; continue; }\n if (!line.startsWith(' ') && inSpecs) { inSpecs = false; continue; }\n\n if (inSpecs) {\n const match = line.match(/^\\s{4}(\\S+)\\s+\\(([^)]+)\\)/);\n if (match) {\n deps.push({\n name: match[1],\n version: match[2],\n ecosystem: 'RubyGems',\n });\n }\n }\n }\n } else {\n // Parse Gemfile\n const gemRegex = /gem\\s+['\"]([^'\"]+)['\"](?:\\s*,\\s*['\"]([^'\"]+)['\"])?/g;\n let match;\n while ((match = gemRegex.exec(content)) !== null) {\n deps.push({\n name: match[1],\n version: match[2] ? cleanVersion(match[2]) : '*',\n ecosystem: 'RubyGems',\n });\n }\n }\n return deps;\n}\n\n/**\n * Parse composer.json/composer.lock (PHP)\n */\nfunction parseComposerJson(content: string, fileName: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n try {\n const pkg = JSON.parse(content);\n\n if (fileName === 'composer.lock') {\n for (const p of pkg.packages || []) {\n deps.push({\n name: p.name,\n version: cleanVersion(p.version || '*'),\n ecosystem: 'Packagist',\n });\n }\n } else {\n for (const section of ['require', 'require-dev']) {\n const packages = pkg[section] || {};\n for (const [name, version] of Object.entries(packages)) {\n if (name === 'php' || name.startsWith('ext-')) continue;\n deps.push({\n name,\n version: cleanVersion(version as string),\n ecosystem: 'Packagist',\n isDev: section === 'require-dev',\n });\n }\n }\n }\n } catch {\n // Invalid JSON\n }\n return deps;\n}\n\n/**\n * Parse pyproject.toml (Python - PEP 621)\n */\nfunction parsePyprojectToml(content: string): DependencyInfo[] {\n const deps: DependencyInfo[] = [];\n let inDeps = false;\n\n for (const line of content.split('\\n')) {\n const trimmed = line.trim();\n if (trimmed === 'dependencies = [') { inDeps = true; continue; }\n if (inDeps && trimmed === ']') { inDeps = false; continue; }\n\n if (inDeps) {\n const match = trimmed.match(/[\"']([a-zA-Z0-9_.-]+)(?:[>=<~!]+([a-zA-Z0-9_.*-]+))?[\"'],?/);\n if (match) {\n deps.push({\n name: match[1],\n version: match[2] || '*',\n ecosystem: 'PyPI',\n });\n }\n }\n }\n return deps;\n}\n\n/**\n * Clean version string by removing prefixes like ^, ~, >=, etc.\n */\nfunction cleanVersion(version: string): string {\n return version.replace(/^[~^>=<!\\s]+/, '').trim();\n}\n","import type { DependencyInfo } from './parsers/package-parser.js';\n\n/**\n * Vulnerability match result from database query\n */\nexport interface VulnerabilityMatch {\n id: string;\n summary: string;\n severity: string;\n package: string;\n version: string;\n ecosystem: string;\n fixedVersion?: string;\n lineNumber?: number;\n cwe?: string[];\n references?: string[];\n}\n\n/** In-memory cache for vulnerability queries */\nconst queryCache = new Map<string, VulnerabilityMatch[]>();\n\n/**\n * Query vulnerabilities for a list of dependencies using the OSV API\n *\n * @see https://osv.dev/docs/\n * @see https://api.osv.dev/v1/query\n */\nexport async function queryVulnerabilities(\n dependencies: DependencyInfo[],\n): Promise<VulnerabilityMatch[]> {\n const results: VulnerabilityMatch[] = [];\n\n // Process in batches of 100\n const batchSize = 100;\n for (let i = 0; i < dependencies.length; i += batchSize) {\n const batch = dependencies.slice(i, i + batchSize);\n const batchResults = await queryBatch(batch);\n results.push(...batchResults);\n }\n\n return results;\n}\n\n/**\n * Fetch detailed vulnerability info by ID\n */\nasync function fetchVulnerabilityDetails(id: string): Promise<OSVVulnerability | null> {\n try {\n const response = await fetch(`https://api.osv.dev/v1/vulns/${id}`);\n if (response.ok) {\n return await response.json() as OSVVulnerability;\n }\n } catch {\n // Ignore error\n }\n return null;\n}\n\n/**\n * Query a batch of dependencies against OSV\n */\nasync function queryBatch(dependencies: DependencyInfo[]): Promise<VulnerabilityMatch[]> {\n const results: VulnerabilityMatch[] = [];\n\n // Use batch query endpoint\n const queries = dependencies.map(dep => ({\n version: dep.version !== '*' ? dep.version : undefined,\n package: {\n name: dep.name,\n ecosystem: mapEcosystem(dep.ecosystem),\n },\n }));\n\n // Check cache first\n const uncached: Array<{ query: typeof queries[0]; dep: DependencyInfo; index: number }> = [];\n\n for (let i = 0; i < queries.length; i++) {\n const cacheKey = `${queries[i].package.ecosystem}:${queries[i].package.name}:${queries[i].version}`;\n const cached = queryCache.get(cacheKey);\n if (cached) {\n for (const vuln of cached) {\n results.push({ ...vuln, lineNumber: dependencies[i].lineNumber });\n }\n } else {\n uncached.push({ query: queries[i], dep: dependencies[i], index: i });\n }\n }\n\n if (uncached.length === 0) return results;\n\n try {\n // Make batch request to OSV API\n const response = await fetch('https://api.osv.dev/v1/querybatch', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n queries: uncached.map(u => u.query),\n }),\n });\n\n if (!response.ok) {\n // If API is unavailable, return empty results gracefully\n return results;\n }\n\n const data = await response.json() as { results: Array<{ vulns?: OSVVulnerability[] }> };\n\n // Fetch full details for all found vulnerabilities in parallel\n const allIds = new Set<string>();\n for (const res of data.results) {\n if (res.vulns) {\n for (const v of res.vulns) {\n allIds.add(v.id);\n }\n }\n }\n\n const detailsMap = new Map<string, OSVVulnerability>();\n if (allIds.size > 0) {\n const fetchPromises = Array.from(allIds).map(async (id) => {\n const details = await fetchVulnerabilityDetails(id);\n if (details) {\n detailsMap.set(id, details);\n }\n });\n await Promise.all(fetchPromises);\n }\n\n // Process results\n for (let i = 0; i < uncached.length; i++) {\n const { dep, query } = uncached[i];\n const vulns = data.results[i]?.vulns || [];\n const cacheKey = `${query.package.ecosystem}:${query.package.name}:${query.version}`;\n\n const matches: VulnerabilityMatch[] = vulns.map(v => {\n const vuln = detailsMap.get(v.id) || v;\n return {\n id: vuln.id,\n summary: vuln.summary || vuln.details?.slice(0, 200) || 'No description available',\n severity: extractSeverity(vuln),\n package: dep.name,\n version: dep.version,\n ecosystem: dep.ecosystem,\n fixedVersion: extractFixedVersion(vuln, dep.name),\n lineNumber: dep.lineNumber,\n cwe: extractCWE(vuln),\n references: vuln.references?.map(r => r.url).filter(Boolean) || [],\n };\n });\n\n queryCache.set(cacheKey, matches);\n results.push(...matches);\n }\n } catch {\n // Network error - OSV API unavailable, silently skip\n // This is expected in offline/air-gapped environments\n }\n\n return results;\n}\n\n// ─── OSV Response Types ────────────────────────────────────────────────────\n\ninterface OSVVulnerability {\n id: string;\n summary?: string;\n details?: string;\n severity?: Array<{\n type: string;\n score: string;\n }>;\n affected?: Array<{\n package: {\n name: string;\n ecosystem: string;\n };\n ranges?: Array<{\n type: string;\n events: Array<{\n introduced?: string;\n fixed?: string;\n last_affected?: string;\n }>;\n }>;\n }>;\n references?: Array<{\n type: string;\n url: string;\n }>;\n database_specific?: Record<string, unknown>;\n}\n\n// ─── Helper Functions ──────────────────────────────────────────────────────\n\n/**\n * Map our ecosystem names to OSV ecosystem names\n */\nfunction mapEcosystem(ecosystem: string): string {\n const mapping: Record<string, string> = {\n 'npm': 'npm',\n 'PyPI': 'PyPI',\n 'Maven': 'Maven',\n 'Go': 'Go',\n 'crates.io': 'crates.io',\n 'RubyGems': 'RubyGems',\n 'Packagist': 'Packagist',\n 'NuGet': 'NuGet',\n };\n return mapping[ecosystem] || ecosystem;\n}\n\n/**\n * Extract severity from OSV vulnerability\n */\nfunction extractSeverity(vuln: OSVVulnerability): string {\n if (vuln.severity && vuln.severity.length > 0) {\n const cvss = vuln.severity.find(s => s.type === 'CVSS_V3');\n if (cvss?.score) {\n const score = parseFloat(cvss.score);\n if (score >= 9.0) return 'CRITICAL';\n if (score >= 7.0) return 'HIGH';\n if (score >= 4.0) return 'MEDIUM';\n return 'LOW';\n }\n }\n\n // Check database_specific for severity hints\n const dbSpecific = vuln.database_specific as Record<string, unknown> | undefined;\n if (dbSpecific?.severity) {\n return String(dbSpecific.severity).toUpperCase();\n }\n\n return 'MEDIUM'; // Default\n}\n\n/**\n * Extract fixed version from OSV vulnerability\n */\nfunction extractFixedVersion(vuln: OSVVulnerability, packageName: string): string | undefined {\n if (!vuln.affected) return undefined;\n\n for (const affected of vuln.affected) {\n if (affected.package.name !== packageName) continue;\n if (!affected.ranges) continue;\n\n for (const range of affected.ranges) {\n for (const event of range.events) {\n if (event.fixed) return event.fixed;\n }\n }\n }\n\n return undefined;\n}\n\n/**\n * Extract CWE identifiers from OSV vulnerability\n */\nfunction extractCWE(vuln: OSVVulnerability): string[] {\n const cwes: string[] = [];\n\n const dbSpecific = vuln.database_specific as Record<string, unknown> | undefined;\n if (dbSpecific?.cwe_ids && Array.isArray(dbSpecific.cwe_ids)) {\n cwes.push(...(dbSpecific.cwe_ids as string[]));\n }\n\n return cwes;\n}\n\n/**\n * Clear the vulnerability cache\n */\nexport function clearCache(): void {\n queryCache.clear();\n}\n","import type { Finding, Severity } from '../../types/finding.js';\nimport type { ScanFileContext, IScanner } from '../../types/scanner.js';\nimport type { DeepScanConfig } from '../../types/config.js';\nimport { parseDependencies, type DependencyInfo } from './parsers/package-parser.js';\nimport { queryVulnerabilities, type VulnerabilityMatch } from './vulnerability-db.js';\nimport { createHash } from 'node:crypto';\n\n/**\n * CVE/SCA Scanner - Software Composition Analysis\n *\n * Parses dependency manifests and checks for known vulnerabilities\n * using the OSV (Open Source Vulnerabilities) database.\n */\nexport class CVEScanner implements IScanner {\n name = 'CVEScanner';\n type = 'cve' as const;\n private config!: DeepScanConfig;\n\n async initialize(config: DeepScanConfig): Promise<void> {\n this.config = config;\n }\n\n async scanFile(context: ScanFileContext): Promise<Finding[]> {\n const { content, filePath } = context;\n const findings: Finding[] = [];\n\n if (!content) return findings;\n\n try {\n // Parse dependencies from manifest file\n const dependencies = parseDependencies(content, filePath);\n\n if (dependencies.length === 0) return findings;\n\n // Query for vulnerabilities\n const vulnerabilities = await queryVulnerabilities(dependencies);\n\n // Convert to findings\n for (const vuln of vulnerabilities) {\n const severity = mapSeverity(vuln.severity);\n const fingerprint = createHash('sha256')\n .update(`cve:${vuln.id}:${vuln.package}:${filePath}`)\n .digest('hex')\n .slice(0, 16);\n\n const refs = [...(vuln.references || [])];\n if (vuln.id.startsWith('GHSA-')) {\n const ghsaUrl = `https://github.com/advisories/${vuln.id}`;\n if (!refs.includes(ghsaUrl)) {\n refs.unshift(ghsaUrl);\n }\n } else if (vuln.id.startsWith('CVE-')) {\n const cveUrl = `https://nvd.nist.gov/vuln/detail/${vuln.id}`;\n if (!refs.includes(cveUrl)) {\n refs.unshift(cveUrl);\n }\n }\n\n findings.push({\n id: `cve-${fingerprint.slice(0, 8)}`,\n ruleId: 'cve/known-vulnerability',\n scanner: 'cve',\n severity,\n confidence: 'high',\n category: 'vulnerability',\n title: `${vuln.id}: ${vuln.summary.slice(0, 100)}`,\n message: `Package \"${vuln.package}@${vuln.version}\" has a known vulnerability: ${vuln.summary}`,\n location: {\n file: filePath,\n startLine: vuln.lineNumber || 1,\n startColumn: 0,\n endLine: vuln.lineNumber || 1,\n endColumn: 0,\n snippet: `${vuln.package}: ${vuln.version}`,\n },\n cwe: vuln.cwe || [],\n fix: {\n description: vuln.fixedVersion\n ? `Upgrade ${vuln.package} to version ${vuln.fixedVersion}`\n : `No fix available yet. Consider finding an alternative package.`,\n references: refs,\n },\n references: refs,\n metadata: {\n fingerprint,\n tags: ['cve', 'dependency', vuln.ecosystem],\n },\n });\n }\n } catch (error) {\n // Skip on error - network issues, etc.\n }\n\n return findings;\n }\n\n async destroy(): Promise<void> {\n // No cleanup needed\n }\n}\n\n/**\n * Map vulnerability severity string to our Severity type\n */\nfunction mapSeverity(severity: string): Severity {\n const lower = severity.toLowerCase();\n if (lower === 'critical') return 'critical';\n if (lower === 'high') return 'high';\n if (lower === 'medium' || lower === 'moderate') return 'medium';\n return 'low';\n}\n"],"mappings":";AAAA,SAAS,gBAAAA,eAAc,cAAAC,aAAY,aAAa,gBAAgB;AAChE,SAAS,WAAAC,UAAS,YAAqB;AACvC,OAAOC,WAAU;AACjB,SAAS,eAAe;;;ACHxB,SAAS,SAAS;AAIlB,IAAM,iBAAiB,EAAE,KAAK,CAAC,YAAY,QAAQ,UAAU,KAAK,CAAC;AACnE,IAAM,qBAAqB,EAAE,KAAK,CAAC,QAAQ,OAAO,QAAQ,SAAS,SAAS,CAAC;AAE7E,IAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,SAAS,EAAE,QAAQ,EAAE,QAAQ,IAAI;AAAA,EACjC,UAAU,EAAE,MAAM,cAAc,EAAE,QAAQ,CAAC,YAAY,QAAQ,UAAU,KAAK,CAAC;AACjF,CAAC,EAAE,QAAQ,CAAC,CAAC;AAEb,IAAM,0BAA0B,EAAE,OAAO;AAAA,EACvC,eAAe,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ,EAAE;AAAA,EAC3C,wBAAwB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ,EAAE;AAAA,EACpD,eAAe,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,QAAQ,GAAG;AAAA,EAC7C,mBAAmB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ,EAAE;AAAA,EAC/C,iBAAiB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAAA,EAC5C,iBAAiB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,QAAQ,GAAG;AACvD,CAAC,EAA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O,CAAC;AAAA,UAClB,KAAK;AAAA,YACH,aAAa,KAAK,eACd,WAAW,KAAK,OAAO,eAAe,KAAK,YAAY,KACvD;AAAA,YACJ,YAAY;AAAA,UACd;AAAA,UACA,YAAY;AAAA,UACZ,UAAU;AAAA,YACR;AAAA,YACA,MAAM,CAAC,OAAO,cAAc,KAAK,SAAS;AAAA,UAC5C;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAAS,OAAO;AAAA,IAEhB;AAEA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,UAAyB;AAAA,EAE/B;AACF;AAKA,SAAS,YAAY,UAA4B;AAC/C,QAAM,QAAQ,SAAS,YAAY;AACnC,MAAI,UAAU,WAAY,QAAO;AACjC,MAAI,UAAU,OAAQ,QAAO;AAC7B,MAAI,UAAU,YAAY,UAAU,WAAY,QAAO;AACvD,SAAO;AACT;","names":["readFileSync","existsSync","resolve","yaml","resolve","existsSync","readFileSync","yaml","consola","readFileSync","statSync","resolve","extname","consola","resolve","statSync","extname","consola","readFileSync","consola","resolve","join","existsSync","consola","consola","readFileSync","existsSync","resolve","dirname","yaml","consola","consola","resolve","existsSync","dirname","readFileSync","yaml","writeFileSync","mkdirSync","existsSync","dirname","createHash","generateFingerprint","walk","TEST_PATH_PATTERN","TEST_FILE_PATTERN","basename","createHash"]}