DeepScan là một công cụ scan bảo mật và chất lượng code mã nguồn mở, kết hợp tính năng của SonarQube, Coverity, và CVE scanner vào một CLI tool duy nhất. Xây dựng bằng TypeScript/Node.js với kiến trúc plugin-based, hỗ trợ tất cả ngôn ngữ lập trình thông qua Tree-sitter.
- Context-Aware Scanning - Hiểu business logic context (auth, payment, API) để giảm false positive
- AI-Assisted Validation - Tích hợp LLM để giải thích risk và validate findings
- Cross-File Taint Analysis - Theo dõi data flow xuyên nhiều file
- Semantic Pattern Matching - So sánh cấu trúc code ở mức semantic thay vì chỉ syntax
- Unified Scanner - Security + Quality + CVE trong một tool duy nhất
Important
Ngôn ngữ lập trình: TypeScript/Node.js với Tree-sitter WASM bindings. Performance-critical paths sẽ dùng worker threads.
Warning
AI-Assisted Validation: Tính năng này sẽ yêu cầu API key (OpenAI/Anthropic/local LLM). Cần quyết định: bắt buộc hay tùy chọn (optional, OFF by default)?
Important
Scope ban đầu: Dù target full language support, giai đoạn 1 sẽ tập trung hoàn thiện architecture + core engine + rules cho 5 ngôn ngữ phổ biến nhất (JavaScript/TypeScript, Python, Java, Go, C/C++). Các ngôn ngữ khác sẽ được thêm qua plugin system.
Important
- License: MIT hay Apache 2.0? MIT phổ biến hơn, Apache 2.0 có patent protection.
- AI Provider: Hỗ trợ OpenAI, Anthropic, hay Ollama (local)? Hay tất cả?
- Package name:
@deepscan/clihaydeepscan-clitrên npm? - CVE Database: Sử dụng NVD (National Vulnerability Database) hay OSV (Open Source Vulnerabilities by Google)?
┌─────────────────────────────────────────────────────────────────┐
│ DeepScan CLI │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │
│ │ scan │ │ init │ │ report │ │ rule-mgmt │ │
│ │ command │ │ config │ │ convert │ │ list/add/rm │ │
│ └────┬─────┘ └──────────┘ └──────────┘ └──────────────┘ │
│ │ │
│ ┌────▼──────────────────────────────────────────────────────┐ │
│ │ Pipeline Orchestrator │ │
│ │ ┌──────────┐ ┌───────────┐ ┌────────────────────────┐ │ │
│ │ │ File │ │ Language │ │ Parallel Execution │ │ │
│ │ │ Discovery│→ │ Detection │→ │ (Worker Threads) │ │ │
│ │ └──────────┘ └───────────┘ └────────────────────────┘ │ │
│ └────┬──────────────────────────────────────────────────────┘ │
│ │ │
│ ┌────▼──────────────────────────────────────────────────────┐ │
│ │ Scanner Engines │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ Security │ │ Quality │ │ CVE/SCA │ │ │
│ │ │ Scanner │ │ Scanner │ │ Scanner │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ │ • Injection │ │ • Complexity │ │ • Dependency │ │ │
│ │ │ • XSS │ │ • Duplicates │ │ • License │ │ │
│ │ │ • Secrets │ │ • CodeSmells │ │ • CVE Match │ │ │
│ │ │ • Auth │ │ • Standards │ │ • SBOM │ │ │
│ │ │ • Crypto │ │ • Metrics │ │ │ │ │
│ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ │
│ └─────────┼─────────────────┼─────────────────┼────────────┘ │
│ │ │ │ │
│ ┌─────────▼─────────────────▼─────────────────▼────────────┐ │
│ │ Analysis Core │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ Tree-sitter │ │ Taint │ │ Context │ │ │
│ │ │ Parser │ │ Tracker │ │ Analyzer │ │ │
│ │ │ (WASM) │ │ (DFA/CFA) │ │ (Business) │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ Pattern │ │ Semantic │ │ AI │ │ │
│ │ │ Matcher │ │ Engine │ │ Validator │ │ │
│ │ │ (Queries) │ │ (CPG) │ │ (Optional) │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ Rule Engine │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ Built-in │ │ Custom │ │ Rule │ │ │
│ │ │ Rules │ │ Rules │ │ Validator │ │ │
│ │ │ (YAML) │ │ (YAML/JS) │ │ & Loader │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ Output / Reporter │ │
│ │ ┌────┐ ┌─────┐ ┌──────┐ ┌───────┐ ┌──────────┐ │ │
│ │ │JSON│ │ CSV │ │ HTML │ │ SARIF │ │ Console │ │ │
│ │ └────┘ └─────┘ └──────┘ └───────┘ └──────────┘ │ │
│ └───────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
- Project metadata, dependencies, scripts
- CLI entry point configuration (
binfield) - Dependencies:
commander,tree-sitter,web-tree-sitter,chalk,glob,yaml,zod,consola - Dev dependencies:
typescript,tsup,vitest,tsx
- TypeScript strict mode configuration
- ES2022 target, ESM modules
- Path aliases cho clean imports
- Example default configuration file
- Sử dụng để scan chính project DeepScan
- Entry point cho CLI application
- Commander.js setup với các commands:
scan,init,report,rules - Global options:
--config,--format,--output,--verbose,--quiet
- Command chính:
deepscan scan [path] - Options:
--scanners security,quality,cve- chọn scanner engines--severity error,warning- filter theo severity--include "**/*.ts"- glob patterns cho files--exclude "node_modules/**"- exclude patterns--deep- enable deep analysis (taint + semantic)--ai- enable AI validation--parallel <n>- số worker threads--incremental- chỉ scan changed files (git-based)
deepscan init- tạo file.deepscan.ymlmặc định- Interactive mode hỏi user về project type, languages
deepscan rules list- liệt kê tất cả rulesdeepscan rules info <rule-id>- chi tiết 1 ruledeepscan rules create- scaffold custom rule
deepscan report convert --from json --to html- Convert giữa các format output
- Zod schemas cho configuration validation
- Type-safe config interfaces
// Cấu trúc .deepscan.yml interface DeepScanConfig { version: '1.0'; scanners: { security: { enabled: boolean; severity: Severity[] }; quality: { enabled: boolean; thresholds: QualityThresholds }; cve: { enabled: boolean; sources: string[] }; }; rules: { include: string[]; // Rule IDs hoặc categories exclude: string[]; custom: string[]; // Paths tới custom rule files }; languages: string[]; paths: { include: string[]; exclude: string[]; }; output: { format: 'json' | 'csv' | 'html' | 'sarif' | 'console'; file?: string; }; ai?: { enabled: boolean; provider: 'openai' | 'anthropic' | 'ollama'; model?: string; apiKey?: string; // Hoặc env var }; context?: { projectType: 'web' | 'api' | 'library' | 'mobile' | 'cli'; frameworks: string[]; // express, react, spring, etc. sensitivePatterns: string[]; // Custom sensitive data patterns }; }
- Load config từ
.deepscan.yml,.deepscan.json,.deepscan.js - Merge config: default → project → CLI args
- Environment variable substitution
- Default configuration values
- Preset configs cho common project types
- Tree-sitter WASM parser initialization
- Language-specific grammar loading (lazy)
- Parse file → CST (Concrete Syntax Tree)
- Caching parsed trees cho incremental analysis
- Utility functions cho tree traversal
- Node type queries, pattern matching helpers
- Source location mapping
Cross-File Taint Analysis Engine
- Build inter-procedural data flow graph
- Track tainted data từ sources (user input, network, env) tới sinks (SQL, exec, file write)
- Support cross-file tracking qua import/export analysis
- Configurable sources/sinks per language
interface TaintConfig { sources: TaintSource[]; // { pattern: "req.body.*", type: "user_input" } sinks: TaintSink[]; // { pattern: "db.query($TAINTED)", type: "sql_injection" } sanitizers: Sanitizer[]; // { pattern: "escape($X)", cleanses: ["sql_injection"] } propagators: Propagator[];// { from: "$X.toString()", to: "return" } }
Context-Aware Analysis Engine (Unique Feature)
- Phân tích business logic context:
- Detect auth-related code (login, token, session)
- Detect payment/financial code
- Detect data handling patterns (PII, GDPR)
- Detect API endpoints và access control
- Apply context-specific rules (ví dụ: auth code cần stricter checks)
- Reduce false positives bằng cách hiểu intent
interface CodeContext { type: 'auth' | 'payment' | 'data-handling' | 'api' | 'crypto' | 'file-io' | 'general'; confidence: number; // 0-1 indicators: string[]; // Tại sao classify như vậy relatedFiles: string[]; // Files liên quan trong cùng context }
Semantic Pattern Matching Engine (Unique Feature)
- So sánh code patterns ở mức semantic thay vì chỉ syntax
- Normalize code trước khi so sánh (rename vars, simplify expressions)
- Detect semantic equivalence (ví dụ:
!a || !b===!(a && b)) - Build Code Property Graph (CPG) cho semantic analysis
AI-Assisted Validation (Optional Feature)
- Nhận finding từ scanners → gửi code context tới LLM
- LLM validate: true positive hay false positive?
- LLM explain: tại sao đây là risk? Cách fix?
- Support multiple providers: OpenAI, Anthropic, Ollama (local)
- Rate limiting và cost management
- Fallback khi không có AI: trả về raw findings
- Scan directory recursively
- Respect
.gitignore,.deepscanignore - Language detection by extension + content sniffing
- Dependency file detection (package.json, pom.xml, etc.)
- Orchestrate toàn bộ scanning pipeline
- Parallel execution with worker threads
- Progress reporting
- Error handling và graceful degradation
- Abstract base class cho tất cả scanners
- Common interface:
scan(file, tree, context) → Finding[] - Rule loading và filtering
- Security scanner orchestrator
- Aggregates results từ các sub-analyzers
- SQL Injection detection (parameterized queries check)
- Command Injection (exec, spawn patterns)
- LDAP, XPath, NoSQL injection
- Template injection (SSTI)
- Cross-Site Scripting detection
- DOM-based XSS patterns
- Reflected XSS qua taint tracking
- Missing output encoding
- Hardcoded passwords, API keys, tokens
- High-entropy string detection
- Known secret patterns (AWS keys, GitHub tokens, etc.)
- .env file scanning
- Weak authentication patterns
- Missing authorization checks
- Insecure session management
- JWT misconfigurations
- Weak algorithms (MD5, SHA1, DES)
- Insecure random number generation
- Hardcoded encryption keys
- Missing TLS/SSL verification
- Path traversal vulnerabilities
- Unsafe file uploads
- Directory listing exposure
- Temporary file issues
- Quality scanner orchestrator
- Cyclomatic complexity calculation
- Cognitive complexity (SonarQube style)
- Nesting depth analysis
- Function length warnings
- Code duplication detection
- Token-based comparison
- Configurable minimum block size
- Cross-file duplication
- Long methods/functions
- Large classes/files
- Dead code detection
- Unused imports/variables
- Magic numbers
- Naming convention checks
- Language-specific conventions (camelCase, snake_case)
- Meaningless variable names
- Lines of code (LOC/SLOC)
- Comment ratio
- Test coverage estimation
- Maintainability index
- Software Composition Analysis orchestrator
- Parse dependency manifests:
package.json+package-lock.json(npm/yarn)requirements.txt+Pipfile.lock(Python)pom.xml+build.gradle(Java)go.mod+go.sum(Go)Cargo.toml+Cargo.lock(Rust)Gemfile.lock(Ruby)composer.lock(PHP)
- Fetch và cache CVE data từ OSV (Google) + NVD
- Local SQLite database cho offline scanning
- Periodic update mechanism
- Version range matching
- Detect dependency licenses
- License compatibility checking
- Policy enforcement (block certain licenses)
- Rule loading, validation, và execution
- Priority-based rule ordering
- Category filtering
- Custom rule plugin system
- Zod schema cho rule YAML format validation
# Ví dụ Custom Rule Format (.deepscan-rules/my-rule.yml) rules: - id: custom/no-eval name: "Prohibit eval() usage" description: "eval() is dangerous and should never be used in production code" category: security subcategory: injection severity: error confidence: high cwe: CWE-95 languages: [javascript, typescript, python] # Tree-sitter pattern matching patterns: - pattern: "eval($CODE)" message: "eval() với input không tin cậy có thể dẫn tới Code Injection" - pattern: "new Function($CODE)" message: "new Function() tương đương eval()" # Semantic conditions (optional) conditions: - type: taint-check source: "user_input" sink: "$CODE" - type: context-check not-in: ["test", "development"] # Fix suggestion fix: description: "Sử dụng JSON.parse() hoặc parser an toàn thay vì eval()" replacement: "JSON.parse($CODE)" # Metadata tags: [owasp-top-10, injection, a03] references: - https://owasp.org/Top10/A03_2021-Injection/ - https://cwe.mitre.org/data/definitions/95.html
security/- 50+ built-in security rulesquality/- 30+ built-in quality rules- Organized by category (injection, xss, secrets, complexity, etc.)
- Load custom rules từ local files hoặc remote URLs
- Support YAML rules (declarative) và JS/TS rules (programmatic)
- Rule inheritance và override
- Abstract base class cho reporters
- Common finding format
- JSON output với full metadata
- Pretty-print option
- Streaming output cho large results
- CSV output cho Excel/spreadsheet analysis
- Configurable columns
- Proper escaping
- Beautiful, interactive HTML report
- Dashboard với charts (severity distribution, top issues)
- Filterable findings table
- Code snippet highlighting
- Export to PDF option
- Self-contained single HTML file (no external deps)
- SARIF 2.1.0 compliant output
- GitHub Code Scanning compatible
- CWE và OWASP taxonomy references
- Terminal-friendly colored output
- Summary statistics
- Progress indicators
- Verbose/quiet modes
- Language registry và auto-detection
- Extension → language mapping
- Grammar lazy-loading
Mỗi ngôn ngữ có 1 config file chứa:
- Tree-sitter grammar package name
- Language-specific taint sources/sinks
- Naming conventions
- Common frameworks patterns
- File extensions
Ngôn ngữ hỗ trợ ban đầu:
javascript.ts,typescript.tspython.tsjava.tsgo.tsc-cpp.tscsharp.tsphp.tsruby.tsrust.tskotlin.tsswift.ts
interface Finding { id: string; // Unique finding ID ruleId: string; // Rule that triggered this finding scanner: 'security' | 'quality' | 'cve'; severity: 'critical' | 'error' | 'warning' | 'info'; confidence: 'high' | 'medium' | 'low'; category: string; // injection, xss, complexity, etc. title: string; message: string; location: { file: string; startLine: number; startColumn: number; endLine: number; endColumn: number; snippet: string; // Code context }; context?: CodeContext; // Business logic context taintFlow?: TaintFlowStep[]; // Data flow trace cwe?: string[]; // CWE references owasp?: string[]; // OWASP Top 10 references fix?: { description: string; suggestion?: string; // Code replacement references: string[]; }; aiValidation?: { isValid: boolean; explanation: string; confidence: number; fixSuggestion?: string; }; metadata: { fingerprint: string; // Cho dedup across scans firstSeen?: string; tags: string[]; }; }
d:/code/code-scan-security/
├── bin/
│ └── deepscan.ts # CLI entry point
├── src/
│ ├── cli/
│ │ ├── index.ts # CLI setup
│ │ └── commands/
│ │ ├── scan.ts
│ │ ├── init.ts
│ │ ├── rules.ts
│ │ └── report.ts
│ ├── config/
│ │ ├── schema.ts
│ │ ├── loader.ts
│ │ └── defaults.ts
│ ├── core/
│ │ ├── parser.ts # Tree-sitter parser
│ │ ├── ast-utils.ts
│ │ ├── taint-tracker.ts # Cross-file taint analysis
│ │ ├── context-analyzer.ts # Context-aware scanning
│ │ ├── semantic-engine.ts # Semantic pattern matching
│ │ ├── ai-validator.ts # AI-assisted validation
│ │ ├── file-discovery.ts
│ │ └── pipeline.ts # Orchestrator
│ ├── scanners/
│ │ ├── base-scanner.ts
│ │ ├── security/
│ │ │ ├── index.ts
│ │ │ └── analyzers/
│ │ │ ├── injection.ts
│ │ │ ├── xss.ts
│ │ │ ├── secrets.ts
│ │ │ ├── auth.ts
│ │ │ ├── crypto.ts
│ │ │ └── file-ops.ts
│ │ ├── quality/
│ │ │ ├── index.ts
│ │ │ └── analyzers/
│ │ │ ├── complexity.ts
│ │ │ ├── duplication.ts
│ │ │ ├── code-smells.ts
│ │ │ ├── naming.ts
│ │ │ └── metrics.ts
│ │ └── cve/
│ │ ├── index.ts
│ │ ├── parsers/
│ │ │ └── package-parser.ts
│ │ ├── vulnerability-db.ts
│ │ └── license-checker.ts
│ ├── rules/
│ │ ├── rule-engine.ts
│ │ ├── rule-schema.ts
│ │ ├── custom-loader.ts
│ │ └── built-in/
│ │ ├── security/
│ │ │ ├── injection.yml
│ │ │ ├── xss.yml
│ │ │ ├── secrets.yml
│ │ │ ├── auth.yml
│ │ │ ├── crypto.yml
│ │ │ └── file-ops.yml
│ │ └── quality/
│ │ ├── complexity.yml
│ │ ├── duplication.yml
│ │ ├── code-smells.yml
│ │ └── naming.yml
│ ├── reporters/
│ │ ├── base-reporter.ts
│ │ ├── json-reporter.ts
│ │ ├── csv-reporter.ts
│ │ ├── html-reporter.ts
│ │ ├── sarif-reporter.ts
│ │ ├── console-reporter.ts
│ │ └── templates/
│ │ └── html-report/ # HTML report template & assets
│ ├── languages/
│ │ ├── registry.ts
│ │ └── configs/
│ │ ├── javascript.ts
│ │ ├── python.ts
│ │ ├── java.ts
│ │ ├── go.ts
│ │ └── ...
│ └── types/
│ ├── finding.ts
│ ├── config.ts
│ ├── rule.ts
│ └── scanner.ts
├── rules/ # External custom rules directory
│ └── examples/
│ ├── custom-api-security.yml
│ └── custom-naming.yml
├── tests/
│ ├── unit/
│ ├── integration/
│ └── fixtures/ # Test code samples
├── docs/
│ ├── getting-started.md
│ ├── configuration.md
│ ├── writing-rules.md
│ └── api-reference.md
├── .deepscan.yml # Self-scan configuration
├── package.json
├── tsconfig.json
├── tsup.config.ts
├── vitest.config.ts
├── LICENSE
└── README.md
# Unit tests cho từng module npm run test # Integration tests - scan test fixtures npm run test:integration # Scan chính project DeepScan (self-test) npx deepscan scan ./src --format json # Type checking npm run typecheck # Lint npm run lint
- CLI Test: Chạy
deepscan scantrên các sample projects - Output Test: Verify JSON, CSV, HTML, SARIF outputs đều valid
- Rule Test: Tạo custom rule và verify nó hoạt động
- Config Test: Test various
.deepscan.ymlconfigurations - Cross-language Test: Scan projects đa ngôn ngữ
- Performance Test: Scan large codebase (>10k files) đo thời gian
- Tạo sample code với known vulnerabilities cho mỗi ngôn ngữ
- Verify detection rate (true positive, false positive, false negative)
- Benchmark với Semgrep và ESLint trên cùng test fixtures
- Project setup, TypeScript config, CLI framework
- Config system, file discovery, Tree-sitter parser
- Base scanner, rule engine, console reporter
- 10 security rules cơ bản cho JavaScript
- Security scanner với đầy đủ analyzers
- Quality scanner với complexity và code smells
- JSON, CSV, HTML reporters
- 50+ built-in rules cho 5 ngôn ngữ chính
- Taint tracker (cross-file)
- Context-aware analyzer
- Semantic pattern matching engine
- CVE/SCA scanner
- SARIF reporter
- AI validator integration
- Incremental scanning
- Performance optimization (worker threads)
- HTML report dashboard
- Documentation
- npm publish
# Install npm install -g deepscan-cli # Initialize config deepscan init # Basic scan deepscan scan ./src # Full scan với all options deepscan scan ./src \ --scanners security,quality,cve \ --format html \ --output report.html \ --deep \ --severity critical,error \ --parallel 4 # Scan với AI validation deepscan scan ./src --ai --ai-provider openai # Custom rules deepscan scan ./src --rules ./my-rules/ # Incremental scan (only changed files) deepscan scan ./src --incremental # List all rules deepscan rules list --category security # Convert report format deepscan report convert scan-results.json --to csv --output results.csv
# .deepscan.yml version: "1.0" scanners: security: enabled: true severity: [critical, error, warning] quality: enabled: true thresholds: maxComplexity: 15 maxFileLength: 500 maxFunctionLength: 50 cve: enabled: true failOnSeverity: critical rules: exclude: - quality/naming-convention custom: - ./my-rules/*.yml paths: exclude: - node_modules/** - dist/** - "**/*.test.ts" output: format: json file: deepscan-results.json