name: Security Scan

on:
  push:
    branches:
      - main
  pull_request:
    branches: 
      - main
  workflow_dispatch:

jobs:
  scan:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
      actions: read
    env:
      SECURITY_SNYK_TOKEN: ${{ secrets.SECURITY_SNYK_TOKEN }}
    steps:
      - uses: actions/checkout@v5
        with:
          fetch-depth: 0

      - name: Initialize CodeQL
        if: env.ACT != 'true'
        continue-on-error: true
        uses: github/codeql-action/init@v4
        with:
          languages: javascript-typescript, actions
          build-mode: none
          queries: security-extended,security-and-quality

      - name: Perform CodeQL Analysis
        if: env.ACT != 'true'
        continue-on-error: true
        uses: github/codeql-action/analyze@v4
        with:
          upload: true
          output: sarif-results

      - name: Install Gitleaks
        if: env.ACT != 'true'
        continue-on-error: true
        run: |
          GITLEAKS_VERSION="8.28.0"
          curl -sSL -o gitleaks.tar.gz "https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz"
          tar -xzf gitleaks.tar.gz gitleaks
          chmod +x gitleaks
          sudo mv gitleaks /usr/local/bin/gitleaks

      - name: Secret Detection
        if: env.ACT != 'true'
        continue-on-error: true
        run: |
          gitleaks git . --report-format sarif --report-path results.sarif --no-banner || true

      - name: Install Project Dependencies
        if: env.SECURITY_SNYK_TOKEN != ''
        env:
          SECURITY_PACKAGE: ${{ vars.SECURITY_PACKAGE || '' }}
        run: |
          echo "Preparing dependency lock files for security scanning..."
          if [ -z "$SECURITY_PACKAGE" ]; then
            echo "SECURITY_PACKAGE is empty, installing in root..."
            npm install --package-lock-only
          else
            echo "SECURITY_PACKAGE is set to: $SECURITY_PACKAGE"
            # Split by comma and install
            IFS=',' read -ra PACKAGES <<< "$SECURITY_PACKAGE"
            for pkg in "${PACKAGES[@]}"; do
              if [ -d "$pkg" ]; then
                echo "Installing in "$pkg"..."
                npm install --prefix "$pkg" --package-lock-only
              else
                echo "Warning: Directory $pkg not found, skipping."
              fi
            done
          fi

      - name: Dependency Scan
        id: snyk
        if: env.SECURITY_SNYK_TOKEN != ''
        continue-on-error: true
        run: |
          npm install -g snyk          
          snyk auth ${{ secrets.SECURITY_SNYK_TOKEN }}
          snyk test --all-projects --json-file-output=snyk_result.json > snyk_result.txt || true
        env:
          SECURITY_SNYK_TOKEN: ${{ secrets.SECURITY_SNYK_TOKEN }}

      - name: Check for Dockerfile
        id: check_docker
        run: |
          if [ -f "Dockerfile" ]; then
            echo "exists=true" >> $GITHUB_OUTPUT
          else
            echo "exists=false" >> $GITHUB_OUTPUT
          fi

      - name: Container Security Scan (Trivy)
        if: steps.check_docker.outputs.exists == 'true'
        continue-on-error: true
        run: |
          VERSION="0.56.1"
          echo "Installing Trivy $VERSION..."
          curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin "v$VERSION"
          trivy config . --format json --output trivy_result.json --severity CRITICAL,HIGH || true

      - name: Generate Security Report
        run: |
          # Gitleaks typically produces results.sarif if configured or by default in some versions
          # We'll ensure it exists for our reporter
          node .github/scripts/security.cjs
          
          # Also append to step summary for immediate visibility in GHA UI
          cat security-report.md >> $GITHUB_STEP_SUMMARY
          echo -e "\n---\n" >> $GITHUB_STEP_SUMMARY
          cat security-report-cn.md >> $GITHUB_STEP_SUMMARY

      - name: Upload Gitleaks Results to GitHub Security
        uses: github/codeql-action/upload-sarif@v4
        if: always()
        with:
          sarif_file: results.sarif
          category: gitleaks

      - name: Upload Security Report Artifacts
        if: always()
        uses: actions/upload-artifact@v6
        with:
          name: security-report
          if-no-files-found: ignore
          path: |
            security-report.md
            security-report-cn.md
            snyk_result.txt
            snyk_result.json
            trivy_result.json
            results.sarif
            sarif-results/*.sarif
