CodeFlow Documentation

repository·main·Indexed 26 days ago

https://github.com/braedonsaunders/codeflow

A browser-based tool for visualizing codebase architecture, dependency graphs, and health metrics. It includes the codeflow-card GitHub Action (v1.0.0) to generate auto-updating SVG cards for READMEs and post PR receipts summarizing changes to LOC, fragility, and health. Supports analysis of public/private GitHub repositories and local files across multiple languages including JavaScript, TypeScript, Python, Java, Go, Rust, and C++.

Tokens
10K
Snippets
17
Records
57
Agent score
86%

What's inside CodeFlow

  1. Adjust Debug Statements severity based on path

    main

    The Debug Statements security rule (triggered by excessive console.log, console.debug, or console.info calls) should have its severity adjusted based on whether the file is part of the backend architecture.

    • Backend/Server paths: Severity should be info.
    • Client/Other paths: Severity should be low.

    This uses the isArchitectureBackendPath(path) classifier to determine the appropriate level.

    if(scanContent.match(/console\.(log|debug|info)\(\)){
        var consoleCount=(scanContent.match(/console\.(log|debug|info)\(\)/g)||[]).length;
        if(consoleCount>3){
            var debugSeverity=isArchitectureBackendPath(f.path)?'info':'low';
            issues.push({
                severity:debugSeverity,
                title:'Debug Statements',
                file:f.name,
                path:f.path,
                desc:consoleCount+' console statements found. Remove before production.',
                code:''
            });
        }
    }
  2. Test layer violation detection with golden fixtures

    main

    To verify layer violation logic, follow the existing golden-fixture pattern used in tests/codeflow-golden.test.mjs. This involves extracting the analyzer from index.html via vm, providing constructed files and connections, and asserting on the output.

    When testing Parser.detectLayerViolations and Parser.detectLayer directly, ensure the following behaviors are validated:

    • Healthy dependencies: A file in a higher layer (e.g., services) depending on a file in a lower layer (e.g., utils) should produce 0 violations.
    • Genuine violations: A file in a lower layer (e.g., utils) depending on a file in a higher layer (e.g., services) should produce 1 violation. The violation object should include from (the violating file) and a suggestion such as "utils should not import from services".
    • Gap threshold: Dependencies between adjacent layers (a level difference of 1) should produce no violations.
    • Root-level folder detection: Ensure detectLayer correctly identifies layers for paths like services/x.ts (layer: services) or nested paths like src/services/x.ts (layer: services).
    • Non-regression: Ensure node --test passes and existing golden fixtures remain green, as they exercise the full buildAnalysisData pipeline.
    node --test
  3. Fix Function Constructor security rule precision

    main

    The Function Constructor security rule can produce false positives if it matches substrings in comments (e.g., Function(). To ensure precision, the rule should use a word boundary anchor to only flag actual new Function(...) constructor calls.

    // Replace the substring check with a word-boundary regex
    if(scanContent.match(/\bnew\s+Function\s*\(\)){
        issues.push({
            severity:'medium',
            title:'Function Constructor',
            file:f.name,
            path:f.path,
            desc:'Function constructor is similar to eval(). Consider alternatives.',
            code:''
        });
    }
  4. Analyze Local Files and Folders

    main

    You can analyze code directly from your computer without uploading it to GitHub. This is ideal for private projects or offline work.

    1. Click the "Open Folder" button in the browser.
    2. Select a folder (for recursive analysis) or specific files.
    3. Alternatively, Drag & Drop files or folders directly onto the page.
    4. Use Custom Excludes to skip specific paths (e.g., uploads/**, **/cache/**, or *.png) before scanning.
  5. Fix layer violation direction in detectLayerViolations

    main

    If layer violations are being reported in the wrong direction (e.g., reporting a healthy downward dependency as a violation), you must ensure the logic correctly identifies the importer and the imported file.

    In the connections.forEach loop within detectLayerViolations, the target property of the connection object represents the importerFile. A violation is triggered if importerLevel > importedLevel and the difference between levels is greater than 1.

    // Correct implementation logic for detectLayerViolations
    connections.forEach(function(c){
        var importedFile=fileByPath[c.source];
        var importerFile=fileByPath[c.target];
        if(!importedFile||!importerFile)return;
        var importedLayer=(importedFile.layer||'').toLowerCase();
        var importerLayer=(importerFile.layer||'').toLowerCase();
        var importedLevel=layerOrder[importedLayer];
        var importerLevel=layerOrder[importerLayer];
        
        if(importerLevel!==undefined&&importedLevel!==undefined&&importerLevel>importedLevel&&importerLevel-importedLevel>1){
            violations.push({
                from:importerFile.path,
                fromLayer:importerFile.layer,
                to:importedFile.path,
                toLayer:importedFile.layer,
                fn:c.fn,
                suggestion:importerFile.layer+' should not import from '+importedFile.layer+'. Consider inverting the dependency or using dependency injection.'
            });
        }
    });
  6. Fix XSS Vulnerability rule for static literals

    main

    To prevent false positives in XSS detection, update the detectSecurity function in index.html to recognize when dangerouslySetInnerHTML is being used with a static string literal. The rule should still flag instances where variable interpolation (e.g., {{ __html: rawUserBio }}) is used, as these pose a real XSS risk.

    var hasInnerHtmlAssignment=scanContent.match(/innerHTML\s*=/");
    var hasDangerousHtmlRender=scanContent.match(/dangerouslySetInnerHTML/);
    var isSafePreviewRender=!hasInnerHtmlAssignment&&hasDangerousHtmlRender&&isSanitizedPreviewRenderer(f.content||'');
    var htmlValueMatch=scanContent.match(/dangerouslySetInnerHTML\s*[:=]\s*\{\{?\s*__html\s*:\s*([^}]+)\}/);
    var isLiteralOnlyHtml=!!(htmlValueMatch&&/^(['"`])(?:(?!\1)[\s\S])*\1$/.test(htmlValueMatch[1].trim()));
    var isSafeStaticHtml=!hasInnerHtmlAssignment&&hasDangerousHtmlRender&&isLiteralOnlyHtml;
    if((hasInnerHtmlAssignment||hasDangerousHtmlRender)&&!isSafePreviewRender&&!isSafeStaticHtml){
        issues.push({severity:'high',title:'XSS Vulnerability',file:f.name,path:f.path,desc:'Direct HTML injection can lead to XSS attacks. Sanitize user input.',code:''});
    }
  7. Fix SQL Injection Risk rule precision

    main

    The SQL Injection Risk rule in index.html should be updated to anchor detections to actual database call receivers (query, execute, or raw) and ensure it only flags code files (f.isCode). This prevents markdown prose containing SQL-like syntax from being incorrectly flagged. The rule now checks for both string concatenation (+) and template literal interpolation (${) within the arguments of a database call.

    var dbCallMatch=scanContent.match(/\b(?:query|execute|raw)\s*\(([^)]*)\)/i);
    var hasSqlConcat=scanContent.match(/query\s*\(\s*['"`][^'"`]*\s*\+/)||scanContent.match(/execute\s*\(\s*['"`][^'"`]*\$\{/);
    var hasSqlTemplateInjection=dbCallMatch&&/\$\{/.test(dbCallMatch[1])&&/(?:SELECT|INSERT|UPDATE|DELETE)/i.test(dbCallMatch[1]);
    if(f.isCode&&(hasSqlConcat||hasSqlTemplateInjection)){
        var m=scanContent.match(/.*(query|execute|SELECT|INSERT|UPDATE|DELETE).*(\+|\$\{).*/i);
        issues.push({severity:'high',title:'SQL Injection Risk',file:f.name,path:f.path,desc:'String concatenation in SQL queries. Use parameterized queries instead.',code:m?m[0].trim().substring(0,80):''});
    }
  8. Configure Security Severity levels and UI

    main

    When adding a new severity level like info, you must update four distinct areas in index.html to ensure consistent behavior:

    1. Sort Map: Update the sev object to include the new level (e.g., var sev={high:0,medium:1,low:2,info:3};) to prevent NaN results in sorting.
    2. UI Totals: Add a new badge in the totals row using React.createElement to display the count for the new severity.
    3. CSS Styles: Add a corresponding class (e.g., .security-item.info) using a neutral/muted color from the existing palette.
    4. Color Mapping: Update getSeverityColor to return a specific color for the new level so it is visually distinguishable from other severities.
  9. Install and setup the CodeFlow Card GitHub Action

    main

    The CodeFlow Card is a GitHub Action that generates an auto-updating SVG card for your repository's README, displaying metrics like health grade, scale, fragility, and hidden costs.

    To set it up:

    1. Create a workflow file at .github/workflows/codeflow-card.yml with the configuration provided below.
    2. Add the generated SVG to your README using an <img> tag.

    The Action requires contents: write permissions to commit the SVG and the history file. If you enable receipts, it also requires pull-requests: write permissions.

    name: CodeFlow Card
    on:
      push:
        branches: [main]
      pull_request:
        types: [closed]
      workflow_dispatch:
    
    jobs:
      card:
        runs-on: ubuntu-latest
        permissions:
          contents: write
          pull-requests: write
        steps:
          - uses: actions/checkout@v4
          - uses: braedonsaunders/codeflow/card@v1
            with:
              receipts: false  # set true to post merged-PR comments

    Then add this to your README:

    <img src=".github/codeflow-card.svg" alt="CodeFlow card" />
  10. Fix VBA and Python Shell Execution security rules

    main

    To reduce false positives for Shell Execution, wrap the VBA and Python detection logic in index.html with a check for !isNonProductionPath(f.path). This ensures that shell commands in non-production files (like configuration or scripts) do not trigger high-severity security issues.

    // VBA Fix
    if(!isNonProductionPath(f.path)&&scanContent.match(/Shell\s*\(/i)){
        issues.push({severity:'high',title:'Shell Command Execution',file:f.name,path:f.path,desc:'Shell() executes system commands. Ensure input is validated.',code:''});
    }
    
    // Python Fix
    if(!isNonProductionPath(f.path)&&scanContent.match(/subprocess\.\w+\([^)]*shell\s*=\s*True/)){
        issues.push({severity:'high',title:'Shell Injection Risk',file:f.name,path:f.path,desc:'subprocess with shell=True is vulnerable to command injection. Use shell=False with a list of args.',code:''});
    }
  11. Exclude test files from Architecture Violation reports

    main
    To prevent false positives where test files are flagged for importing services or utilities, use the isArchitectureTestFile classifier. Test files (matching patterns like test/, tests/, __tests__/, or *.test.*/*.spec.*) are considered universal consumers and are permitted to depend on any layer without triggering a violation.