# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
# FILE INFORMATION
# DEFGROUP: Gitea.Workflow
# INGROUP: MokoStandards.Security
# REPO: https://git.mokoconsulting.tech/MokoConsulting/MokoStandards
# PATH: /.gitea/workflows/security-audit.yml
# VERSION: 01.00.00
# BRIEF: Dependency vulnerability scanning for composer and npm packages

name: "Universal: Security Audit"

on:
  schedule:
    - cron: '0 6 * * 1'  # Weekly on Monday at 06:00 UTC
  pull_request:
    branches:
      - main
    paths:
      - 'composer.json'
      - 'composer.lock'
      - 'package.json'
      - 'package-lock.json'
  workflow_dispatch:

permissions:
  contents: read

env:
  NTFY_URL: ${{ vars.NTFY_URL || 'https://ntfy.mokoconsulting.tech' }}
  NTFY_TOPIC: ${{ vars.NTFY_TOPIC || 'gitea-security' }}

jobs:
  audit:
    name: Dependency Audit
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Composer audit
        if: hashFiles('composer.lock') != ''
        run: |
          echo "=== Composer Security Audit ==="
          if ! command -v composer &> /dev/null; then
            sudo apt-get update -qq
            sudo apt-get install -y -qq php-cli composer >/dev/null 2>&1
          fi
          composer audit --format=plain 2>&1 | tee /tmp/composer-audit.txt
          RESULT=$?
          if [ $RESULT -ne 0 ]; then
            echo "::warning::Composer vulnerabilities found"
            echo "composer_vulnerable=true" >> "$GITHUB_ENV"
          else
            echo "No known vulnerabilities in composer dependencies"
          fi

      - name: NPM audit
        if: hashFiles('package-lock.json') != ''
        run: |
          echo "=== NPM Security Audit ==="
          npm audit --production 2>&1 | tee /tmp/npm-audit.txt || true
          if npm audit --production 2>&1 | grep -q "found 0 vulnerabilities"; then
            echo "No known vulnerabilities in npm dependencies"
          else
            echo "::warning::NPM vulnerabilities found"
            echo "npm_vulnerable=true" >> "$GITHUB_ENV"
          fi

      - name: Notify on vulnerabilities
        if: env.composer_vulnerable == 'true' || env.npm_vulnerable == 'true'
        run: |
          REPO="${{ github.event.repository.name }}"
          curl -sS \
            -H "Title: ${REPO} has vulnerable dependencies" \
            -H "Tags: lock,warning" \
            -H "Priority: high" \
            -d "Security audit found vulnerabilities. Review dependency updates." \
            "${NTFY_URL}/${NTFY_TOPIC}" || true
