name: build-sign-and-attest

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
  workflow_dispatch:

permissions:
  contents: read
  id-token: write
  packages: write
  attestations: write

jobs:
  build:
    runs-on: ubuntu-24.04
    env:
      NODE_OPTIONS: "--openssl-legacy-provider=0"
    permissions:
      contents: read
      packages: write
      id-token: write
      attestations: write
    steps:
      - name: Harden runner
        uses: step-security/harden-runner@v2
        with:
          egress-policy: audit
      - name: Checkout
        uses: actions/checkout@v4
        with:
          persist-credentials: false
          fetch-depth: 1
      - name: Setup Node.js 22 LTS
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'
      - name: Install dependencies
        run: npm ci --ignore-scripts
      - name: Run security tests
        run: npm run lint && npm test
      - name: Build distributable
        run: npm run build
      - name: Generate CycloneDX SBOM
        uses: anchore/sbom-action@v0
        with:
          path: dist
          format: cyclonedx-json
          output-file: dist/app-sbom.json
      - name: Upload SBOM artifact
        uses: actions/upload-artifact@v4
        with:
          name: app-sbom
          path: dist/app-sbom.json
          if-no-files-found: error
      - name: Create SLSA Level 3 provenance
        uses: slsa-framework/slsa-github-generator@v2
        with:
          build-artifact-path: dist
          slsa-version: v1.5
      - name: Attest build with GitHub provenance
        uses: actions/attest-build-provenance@v1
        with:
          subject-path: dist/**
      - name: Publish package
        run: npm publish --provenance --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
